Python动态导入脚本,需要将其__name__ ==" __ main __"要调用的代码 [英] Python dynamically importing a script, need to have its __name__ == "__main__" code to be called
问题描述
从另一个脚本导入python脚本时,我希望受到
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?
我要做的是从python脚本,动态更改模块然后导入现有脚本,应该看到所做的更改并运行其 __ main __
代码,就像它是由python直接调用的那样?
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?
我需要执行第二个python脚本与第一个python脚本在同一名称空间中,并传递第二个脚本命令行参数。下面提到的execfile()可能有效,但不带任何命令行参数。
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) as 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()
如果您无法编辑导入的代码, execfile
确实提供了一种机制,用于将参数传递给导入的代码,但这种方法会使我紧张请谨慎使用。
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
这篇关于Python动态导入脚本,需要将其__name__ ==" __ main __"要调用的代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!