[英]How to execute if __name__ != "__main__"?
I have a code which I cannot alter named temp.py which contains我有一个我无法更改的代码,名为 temp.py,其中包含
if __name__ == "__main__":
*some pieces of code not a function call*
I want to import temp
into an other file which I can edit but importing doesnot run the above part.我想
import temp
到我可以编辑的其他文件中,但导入不会运行上述部分。 I know I can use subprocess to run temp.py
but that is not what I want.我知道我可以使用 subprocess 来运行
temp.py
但这不是我想要的。 I want to import the module entirely but cannot alter the code.我想完全导入模块但不能更改代码。 I have heard of a module called
imp
but is depreceated now.我听说过一个名为
imp
的模块,但现在已弃用。
EDIT:编辑:
I am aware that code under the if statement is not meant to be excecuted when imported, but lets just assume temp.py
is written in a really worse way and I cannot alter it.我知道 if 语句下的代码并不意味着在导入时被执行,但让我们假设
temp.py
是以一种非常糟糕的方式编写的,我无法更改它。
You are trying to go against the import system.您正在尝试 go 针对导入系统。 Pretty much any thing you end up doing to achieve this will be a hack.
几乎任何你最终为实现这一目标而做的事情都将是一个 hack。
Consider we have a file:考虑我们有一个文件:
(py39) Juans-MacBook-Pro:~ juan$ cat subvert.py
def foo(x):
print("Hello, ", x)
if __name__ == "__main__":
foo("Goodbye")
Note, if I open up a REPL, I'm in __main__
, so at your top-level script, you could just do:注意,如果我打开一个 REPL,我在
__main__
中,所以在你的顶级脚本中,你可以这样做:
(py39) Juans-MacBook-Pro:~ juan$ python
Python 3.9.5 (default, May 18 2021, 12:31:01)
[Clang 10.0.0 ] :: Anaconda, Inc. on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> __name__
'__main__'
>>> exec(open("subvert.py").read())
Hello, Goodbye
Of course, just execing the source code directly in the same namespace is probably not what you want...当然,直接在同一个命名空间中直接执行源代码可能不是你想要的......
Note, we can pass our own namespace:注意,我们可以传递自己的命名空间:
>>> namespace = {"__name__": "__main__"}
>>> exec(open("subvert.py").read(), namespace)
Hello, Goodbye
So our module's namespace won't be clobbered.所以我们模块的命名空间不会被破坏。
Now, if you want an actual module after it, you could hack together something like:现在,如果你想在它后面有一个实际的模块,你可以像这样拼凑起来:
>>> import types
>>> module = types.ModuleType("__main__")
>>> module
<module '__main__'>
>>> exec(open("subvert.py").read(), module.__dict__)
Hello, Goodbye
>>> module.foo('bar')
Hello, bar
I wouldn't expect any of this to work well.我不希望这些都能很好地工作。 It won't have all the attributes of a fully loaded module, look at
importlib
if you find you need to flesh it out more.它不会具有完全加载模块的所有属性,如果您发现需要充实它,请查看
importlib
。
something like this is really bad practice but will work:这样的事情确实是不好的做法,但会起作用:
file1.py has the "main" part: file1.py 有“主要”部分:
def foo1():
print("foo1")
if __name__ == '__main__':
print("main function started")
foo1()
print("main function finished")
file2.py is an intermediary file: file2.py 是一个中间文件:
from file1 import *
with open('file1.py') as f:
lines = f.readlines()
a = "if __name__ == '__main__':\n"
new_main = ["def main():\n"] + lines[lines.index(a)+1:]
exec("".join(new_main))
file3.py used to import file2 as if it is the file1 module: file3.py 用于导入 file2,就好像它是 file1 模块一样:
import file2
file2.main()
file2.foo1()
output when running file3.py:运行 file3.py 时为 output:
main function started
foo1
main function finished
foo1
Python programmers use following mechanism for avoiding importing a main script on another scripts. Python 程序员使用以下机制来避免在另一个脚本上导入主脚本。
if __name__ == "__main__":
# TODO
Read its philosophia here . 在这里阅读它的理念。
When some code used if __name__ == "__main__":
means to you shouldn't import its code and this work isn't true.当一些代码使用
if __name__ == "__main__":
意味着你不应该导入它的代码并且这项工作是不正确的。
But you can use this mechanism:但是你可以使用这个机制:
def main():
# TODO
if __name__ == "__main__":
main()
In this case everyone can import your main script and use main
function.在这种情况下,每个人都可以导入您的主脚本并使用
main
function。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.