Sourcing a Python Script


#1

Hi everyone! I’m a beginner in python and I’m having a bit of trouble running a script through the command flag of a menuItem. Right now i’m using execfile, adding the directory path of my script and adding the name of my .py script but it returns this error: Error: IOError: file line 1: 2

Here is an example of the script I’m running that creates the menu parented to MayaWindow:

import maya.cmds as cmds
import maya.mel as mel

myScriptDirectory= cmds.internalVar(userScriptDir= True)
myPythonVariable= mel.eval("$tempMelVar= $gMainWindow")

if cmds.menu(“testMenu”, exists= True):
cmds.menu(“testMenu”, edit= True, dai= True)
else:
cmds.setParent(myPythonVariable)
cmds.menu(“testMenu”, l= “Test Tool”, p= “MayaWindow”, to= True)

cmds.setParent(“testMenu”, m= True)

cmds.menuItem(l= “Misc”, sm= True, to= True)
cmds.menuItem(l= “HelloPrinter”, c= (“execfile(”" + myScriptDirectory + “HelloWorld.py”)"))
cmds.setParent("…", m= True)

And here is the script I’m trying to run remotely (saved with the name HelloWorld.py under the Maya scripts directory):

print “hello world!”


#2

Id recommend maybe looking into packages and such in python
if both scripts are in the same folder
simply importing the name of the script will load it and run it

but for the sake of cleanliness
if you have one file named “myTool.py say
def greet(*args):
print “hello”

and the main file at the top includes

import myTool as mt

you can later call
my.greet()
to run whenever

so if you tie it into a flag like cmds.menuItem(c=mt.greet)
it will be able to run the greet command