When developing an external python script, it is often preferable to develop it in an external editor and source it through Maya. To speed up this workflow wouldn't it be nice to have a custom button on your shelf to be able to execute the external script? Here's how to do it:

Want to view a video tutorial on how to set this up? Check out this post instead.

1.

Open up the script editor in Maya and create a new Python tab by going to Command -> New Tab... and choosing Python.

New Python Tab

2.

Thanks to this handy Python function I found on CGTalk, you can copy and paste this script into your Python tab in the Maya Script Editor. Then update the two instances of name_of_python_file and enter the full path of the directory holding your script.

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 dirrectory 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 dirrectory 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( '/Users/Documents/3D/maya/path_to_directory/name_of_python_file.py' )

name_of_python_file.main()

3.

Go to the file menu and choose Save Script to Shelf. Give the button a name and it will show up in the active shelf.

New Python Tab

4.

Now you can edit your external script, save it, click the button on the shelf and have your script re-loaded and executed.

New Python Tab