开发者

Python dynamically importing a script, need to have its __name__ == "__main__" code to be called

While importing a python script from another script I want the script code that is classically protected by

if __name__ == "__main__":  
    ....  
    ....

to be run, how can I get that code run?

What I am trying to do is from a python script, dynamically change a module then import an existing script which should see the changes made and run its __main__ code like it was directly invoked by python?

I need to execute the 2nd python script in the same namespace as the 1st python script and pass the 2nd script command line parameters. execfile() suggested below might work but that doesn't take any command line parameters.

I would rather not edit the 2nd script (external code) 开发者_如何学Goas I want the 1st script to be a wrapper around it.


If you can edit the file being imported, one option is to follow the basic principle of putting important code inside of functions.

# Your script.
import foo

foo.main()

# The file being imported.
def main():
    print "running foo.main()"

if __name__ == "__main__":
    main()

If you can't edit the code being imported, execfile does provide a mechanism for passing arguments to the imported code, but this approach would make me nervous. Use with caution.

# Your script.
import sys

import foo

bar = 999
sys.argv = ['blah', 'fubb']

execfile( 'foo.py', globals() )

# The file being exec'd.
if __name__ == "__main__":
    print bar
    print sys.argv
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜