Search code examples
python-2.7maya

In Maya, how to launch a python script in a python script


I want to make a def that is launching the script given in the str variable :

def launchScript(scriptname):
    import scriptname
    reload(scriptname)
    scriptname.do()

so I can do :

launchScript(test)

and it would launch the do() def from my test script


Solution

  • The easy way to do this is to make your script executable and then use execfile to run it: something like this:

    # scriptfile.py
    
    import maya.cmds as cmds
    def do():
         cmds.polyCube(n='new_cube')
    
    if __name__ == '__main__':
       do()
    

    the if __name__ == '__main__' block will run if the file is being executed but not if it's imported as as a module. Strictly speaking you could get by without it if you know you'll never use the file as a module.

    In maya you just do

     execfile ("path/to/scriptFile.py")
    

    and it will run do() automatically. Unlike importing a module you won't need to use reload(), everything in the file will be re-done on each execfile()

    In general this is fine for testing but not something you'll want to do for production code -- if nothing else, you'll paying the time to read the file off of disk on every run.