[英]How to execute the python code below __name__== '__main__ ' *without* using the `subprocess` module?
I have a python script with the form我有一个格式为 python 的脚本
...
if __name__=='__main__':
parser = argparse.ArgumentParser()
#code
From another python script, how can I execute the code below __name__ == '__main__'
without using the subprocess
module?从另一个 python 脚本中,如何在不使用subprocess
进程模块的情况下执行__name__ == '__main__'
下面的代码?
[Edit] In addition, my python script takes input parameters with the argparse
module. [编辑] 此外,我的 python 脚本使用argparse
模块获取输入参数。 I also need to pass parameters when executing the code below the __name__
part.在执行__name__
部分下面的代码时,我还需要传递参数。
you might be able to get away with:你也许可以逃脱:
import sys
imp_new_module = type(sys)
new_module = imp_new_module(module_name)
new_module.__dict__['__name__'] = '__main__'
exec(open(scriptname).read(), new_module.__dict__)
But you shouldn't do it... :)但你不应该这样做...... :)
(updated question) (更新的问题)
Oh, since you're at it you can also import os, sys
and then update sys.argv
to what you want to pass on (eg sys.argv = [os.path.abspath('file.py'), '--my', 'par'])
... did I mention that you really shouldn't?哦,既然你在这,你也可以import os, sys
然后更新sys.argv
到你想要传递的内容(例如sys.argv = [os.path.abspath('file.py'), '--my', 'par'])
...我有没有提到你真的不应该这样做?
Seriously, if you have control over the script that you are calling you might want to put the code under if __name__ == '__main__':
in a function说真的,如果您可以控制正在调用的脚本,您可能希望将代码放在if __name__ == '__main__':
function 中
def main(argv):
...
parser.parse_args(argv)
...
if __name__ == '__main__':
main(sys.argv)
Or better still define a function (or functions, object) in the script that provides an API better suited to be called from a script, which is also called from __name__ == '__main__'
based on what is found in sys.argv
.或者更好的是在脚本中定义一个 function(或函数、对象),以提供更适合从脚本调用的 API,该脚本也根据sys.argv
中的内容从__name__ == '__main__'
调用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.