Import script in maya python

How to import scripts and make your projets modular



This is a tutorial to import your script in maya. All the code of the project are in my github here

  1. Problematic
  2. Maya and path not a good love storie
  3. Solution



I want to import my script to my project. with this method the project will be more maintainable and we will be more efficient to split the code to different file. Python have implement this features and you check the documentation here

(modules)Project arborescence :
└── project  
    ├── exemple1  

Working on Vs code debug but not in maya

from exemple1.testFunction import test


Maya and path not a good love storie

In maya when you import a script, the relative path is not taken into consideration. The path is ovewriden by the path script of maya. We can check it with the library pathlib


First we must put our project scipt in the maya folder script. For me it's here :


Then we must force it to the path of our project.

import maya.cmds as cmds
import sys 

def importMayaScript(nameFolder):

    # allows to recover le path du folder scrit
    myScriptDir = cmds.internalVar(userScriptDir=True)
    setScriptDir = myScriptDir+'project/src/'+str(nameFolder)+'/'

I use the library sys to add the path to my import library.

We will use this method to have the path of the scirpt folder:

Internal Var

Then we use sys.path.append(setScriptDir) to make append the module to our library project.


from testFunction import test


Now it's working !

Now we use our python files as components ! Example of use :

Voir un autre post
av logo

© 2023 Gilles Avraam. Tous droits réservés.