How do I execute all the code inside a python file so I can use def’s in my current code? I have about 100 scripts that were all written like the script below.
For a simple example, I have a python file called:
D:/bt_test.py
His code looks like this:
def bt_test():
test = 2;
test += addFive(test)
return(test)
def addFive(test):
return(test+5)
Now, I want to from a completely new file, run bt_test()
I’ve tried doing this:
def openPyFile(script):
execfile(script)
openPyFile('D:/bt_test.py')
bt_test()
But this doesn’t work.
I’ve tried doing this as well:
sys.path.append('D:/')
def openPyFile(script):
name = script.split('/')[-1].split('.')[0]
command = 'from ' + name + ' import *'
exec command
openPyFile('D:/bt_test.py')
bt_test()
Does anyone know why this isn’t working?
Here’s a link to a quicktime video that will help explain what’s happening.
https://dl.dropbox.com/u/1612489/pythonHelp.mp4
In addition to Ned’s answer,
__import__()might be useful if you don’t want the file names hardcoded.http://docs.python.org/library/functions.html#__import__Update based on the video.
I don’t have access to Maya, but i can try and speculate.
cmds.button(l='print', c='bt_press()')is where the issue seems to lurk.bt_press()is passed as a string object, and whatever way the interpreter uses to resolve that identifier doesn’t look in the right namespace.1) Try passing
bt_press()with the module prepended:cmds.button(l='print', c='bt_test.bt_press()')2) See if you can bind
cdirectly to the function object:cmds.button(l='print', c=bt_press)Good luck.