How to automatically execute python script when Maya first loaded
I am trying to figure out how to use Python in Maya. I wanted to create a shelf in Maya and when I click that shelf, it will execute a file containing python code.
First thing, I figured out that we can't simply source
python script. I followed this tutorial, so now I have a function psource()
. In my shelf, I can just call psource("myPythonScript")
My problem is I have to somehow register psource()
when Maya first loaded.
Any idea how to do t开发者_Python百科his?
I suggest that you import the Python module with your button before calling the function. Assuming your script is in maya/scripts/tep.py, your button would do the following:
import tep
tep.psource()
If you wanted to modify the script and keep running the fresh version every time you hit the button, do this:
import tep
reload(tep)
tep.psource()
And if you want your module to load on Maya startup, create a file called userSetup.py in your maya/scripts directory and have it do this:
import tep
Then, your button can simply just:
tep.psource()
Or...
reload(tep)
tep.psource()
As part of the Maya startup sequence, it'll execute a file called userSetup.py
for you. Within that file you can stick in standard python code to set up your environment, etc.
docs: http://download.autodesk.com/global/docs/maya2013/en_us/index.html?url=files/Python_Python_in_Maya.htm,topicNumber=d30e725143
That's the 2013 docco, but it's valid in 2011 and 2012 too. I expect it to be correct going back further as well, but I'm not running anything older here
For an example btw, my userSetup.py file looks like this:
import sys
# import a separate pyscript dir - we keep the standard scriptdir for MEL
sys.path.append(r'C:/Users/tanantish/Documents/maya/2012-x64/pyscripts')
# odds on i'm going to want PyMEL loaded by default
# and we are going to try distinguish it from the old maya.cmds
# since the two since they're similar, but not the same.
# from pymel.core import *
import pymel.core as pm
# and we might as well get maya.cmds in for testing..
import maya.cmds as mc
# import local toolpack
import tantools
(edited to caps out userSetup.py as per @jdi's comment)
Which version of Maya are you running? If later than 8.5, Maya has python built in. Any python scripts you put in your local Maya script directory gets automatically sourced. You can inside the script editor source and run python scripts.
To automatically run:
- Create a userSetup.mel file in myDocs\maya\mayaVersion\scripts
- Inside the userSetup, use this syntax to import and run scripts:
python("from package import module");
python("module.method(\"passedVar1\", \"passedVar2\")");
Hope that helps
P.S Same syntax applies for shelf buttons. Just have to make sure that you have your python path set for Maya so that your code can be found. The local script directory is already included.....
I like to use
exec(open('c:\whatever\whatever\scriptname.py'))
See if that works for you! :)
精彩评论