I'm trying to add a directory where I can throw some pyc files and call them from my script.
Basically it's an independent python script with a bunch of def's in it,
I want the name of the pyc file to be the command executed.
so far this works ok except for one thing, my GUI buttons are calling defs as they are
and python doesn't recognize them since the name space is wrong.
How can I import it in from the script as if it was imported like :
from Module import as *
I'm running this code to load it in:
def importModule(ModPath):
fullModName= ModPath.split('\\')[-1]
commandtorun=fullModName.split('.')[0]
mod_name,file_ext = os.path.splitext(os.path.split(ModPath)[-1])
if file_ext.lower() == '.py':
py_mod = imp.load_source(mod_name, ModPath)
elif file_ext.lower() == '.pyc':
py_mod = imp.load_compiled(mod_name, ModPath)
exec "from %s import *"%(commandtorun)
exec "%s()" % (commandtorun)
i know i can write : module.somefunction() , but that's not what i need...
i need the "module" to work independently..
Please help, this is driving me crazy, python is such an awesome language I cant believe you can't source a script from within a script and have it work.
please advise.
解决方案You could use a (rare-in-Python) semicolon in your exec call to make one exec out of the two you have
You might want to take a look at import_module(name, package) in importlib