python-2.7scriptingmaya

Import a custom python script to maya


I am currently trying to import my custom script into maya. I have found this example. My gole is to be able to edit script externally, reload it on each click.

I have tried the following script in python console, and it seems to work. Unfortunately it give me some error when I click the custom button in maya.

This is the script of my custom button in maya:

import sys
import os

def psource(module):

    file = os.path.basename( module )
    dir = os.path.dirname( module )

    toks = file.split( '.' )
    modname = toks[0]

    # Check if directory is really a directory
    if( os.path.exists( dir ) ):

    # Check if the file directory already exists in the sys.path array
        paths = sys.path
        pathfound = 0
        for path in paths:
            if(dir == path):
                pathfound = 1

    # If the directory is not part of sys.path add it
        if not pathfound:
            sys.path.append( dir )

    # exec works like MEL's eval but you need to add in globals()
    # at the end to make sure the file is imported into the global
    # namespace else it will only be in the scope of this function
    exec ('import ' + modname) in globals()

    # reload the file to make sure its up to date
    exec( 'reload( ' + modname + ' )' ) in globals()

    # This returns the namespace of the file imported
    return modname

# When you import a file you must give it the full path
psource( '/The/correct/path/to/my/script/import_test_model.py' )


import_test_model.main()

While this is my custom script:

def main():
    print "funziona"
    return

if __name__ == "__main__":
    main()

This is error messages I'm getting:

...
# When you import a file you must give it the full path
psource( '/Users/rostyslavkostyuk/Documents/developing/py_maya/import_test_model.py' )


import_test_model.main()

# Error: SyntaxError: file <string> line 1: invalid syntax # 

# Error: invalid syntax # 

# Error: invalid syntax # 

# Error: invalid syntax # 

Solution

  • I don't know what was the issue, but to solve it I just deleted the old button, and created the new one, and it started to work.