View Full Version : import/reload from inside py script?

02-10-2011, 07:14 AM
I've setup a simple UI w/a textScrollBox so I can keep a list of my scripts and reload any of them by clicking. But the 'import' and 'reload' statements don't like that idea - they need a module.
When I click on the name of a script in the list, this is what happens:
Can anyone help?
def reloadScript():
# Query textScrollList for selected script:
selectedScript = cmds.textScrollList('scriptList', q=1, si=1)[0] # Items returned as a list
print selectedScript #This works and prints the name of the hilighted script in the textScrollBox
import selectedScript
# ImportError: No module named selectedScript #
reload (selectedScript)
# TypeError: reload() argument must be module # Thanks.

02-10-2011, 08:30 AM
doing the equivalent of an eval() in MEL with a catenation would do it:
exec('import '+selectedScript)although knowing the strange ways python works, I can't guarentee this is an advisable approach... but it's only Maya...

02-10-2011, 09:49 AM
selectedScript = 'someScript'
module = __import__(selectedScript)

02-10-2011, 02:23 PM
selectedScript = 'someScript'
module = __import__(selectedScript)
Perfect - even reloads itself.
Thanks much.

02-14-2011, 01:48 PM
the best solution is to go the "unload" way instead of "reload". deleting modules from sys.modules makes python forget about a module that was loaded.

something like that, might contain typos:

#unload module, need a full qualified module name with a package as well
import sys
# exception catching is there just in case such module was not loaded in first place,
# in which case this part of code just does nothing

#importing myModule here; this will actually run the import everytime this script is rerun
from myPackage.myModule import MyClass
myInstance = MyClass()

the "unload" method works best because once you have a lot of scripts cross-referencing each other, you would not know in which order you should be reloading them. at work, we just got a routine that just unloads every imported module by package name, which we just run before executing test code - haven't failed us for years now. can't post any code though, but it should not be hard for you to figure out from here.

02-15-2011, 02:15 PM
Thanks for that advice. So far I only use scripts that have all the code in them - I haven't learned to use packages, modules, and classes.
Its my impression that all of the modules called by a UI exist within the scope of that UI, so wouldn't all the modules in a script be removed when a UI window is closed?
if cmds.window(winName, q=True, ex=True):

Coincidently, because I do re-use defs and UI panels, I've been thinking about going modular w/my scripts, I'm going to post about that separately.
Thanks again.

CGTalk Moderation
02-15-2011, 02:15 PM
This thread has been automatically closed as it remained inactive for 12 months. If you wish to continue the discussion, please create a new thread in the appropriate forum.