[英]Set __name__ to '__main__' on module before execution
I currently have code that checks if __name__ == '__main__'
and then calls some function if that is the case. 我目前有检查
if __name__ == '__main__'
代码,如果是的话,然后调用某些函数。 Currently, I execute this code by spawning another python subprocess, but importing it as a module is cleaner. 目前,我通过产生另一个python子进程来执行此代码,但将其作为模块导入更干净。 The problem is that there is no
main
function in these modules is exactly what is executed under __name__ == '__main__'
varies. 问题在于这些模块中没有
main
功能,正是__name__ == '__main__'
下执行__name__ == '__main__'
不同。 The only option that I really have is to set the __name__
attribute before executing the module. 我真正拥有的唯一选择是在执行模块之前设置
__name__
属性。 What is the best way to do this? 做这个的最好方式是什么?
What I ended up doing is the following: 我最终要做的是以下几点:
imp_new_module = type(sys)
new_module = imp_new_module(module_name)
new_module.__dict__['__name__'] = '__main__'
exec(open(scriptname).read(), new_module.__dict__)
This is similar to what the importlib internals do, but does skip some attributes. 这与importlib内部操作类似,但是会跳过某些属性。
使用运行库。
runpy.run_module(module_name, run_name= "__main__")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.