这是什么,为什么应该包括一个 if 声明?
if __name__ == "__main__":
print("Hello, World!")
如果你试图关闭一个问题,有人应该使用这个字符,而不是,考虑关闭作为一个复制为什么Python在我进口时运行我的模块,而我如何停止它? 问题,有人只是没有呼叫任何功能,或者错误地等待一个名为主的功能将自动作为一个输入点,使用为什么没有主()功能运行。
这是什么,为什么应该包括一个 if 声明?
if __name__ == "__main__":
print("Hello, World!")
如果你试图关闭一个问题,有人应该使用这个字符,而不是,考虑关闭作为一个复制为什么Python在我进口时运行我的模块,而我如何停止它? 问题,有人只是没有呼叫任何功能,或者错误地等待一个名为主的功能将自动作为一个输入点,使用为什么没有主()功能运行。
当前回答
例如,这是 test1.py 没有如果 __name__ ==“__main__”::
# "test1.py"
def hello()
print("Hello")
hello()
而且 test2.py 只輸入 test1.py:
# "test2.py"
import test1 # Here
然后,当运行 test2.py 时,一个 Hello 被打印,因为 test1.py 中的不需要的 hello() 代码也被运行:
python test2.py
Hello
当然,您可以在 test2.py 中拨打 test1.hello():
# "test2.py"
import test1
test1.hello() # Here
然后,当运行测试2时,印刷了两个Hello:
python test2.py
Hello
Hello
现在,添加如果 __name__ ==“__main__”:测试1.py 并将 hello() 放在下面:
# "test1.py"
def hello()
print("Hello")
if __name__ == "__main__":
hello()
此分類上一篇: Test2.py:
# "test2.py"
import test1
test1.hello()
然后,在运行 test2.py 时,只有一个 Hello 被打印,因为如果 __name__ ==“__main__”:在 test2.py 输入 test1.py 时阻止运行不需要的 hello() 代码:
python test2.py
Hello
此外, test1.py 是否有 __name__ == “__main__”: 或者不:
# "test1.py"
def hello()
print("Hello")
if __name__ == "__main__":
hello()
# "test1.py"
def hello()
print("Hello")
hello()
One Hello 在运行 test1.py 时正确打印:
python test1.py
Hello
其他回答
如果 __name__ ==“__main__”:该怎么办?
__name__ 是一个全球变量(在 Python 中,全球实际上意味着在模块层面)存在于所有名称空间。
作为唯一的特殊情况,但是,在任何Python过程你运行,如 mycode.py:
python mycode.py
否则匿名的全球名称空间将“__main__”的值归咎于其 __name__。
因此,包括最后的线条
if __name__ == '__main__':
main()
在您的 mycode.py 脚本的结尾,当它是由 Python 过程运行的主要输入点模块时,
将使您的脚本独特定义的主要功能运行。
使用此构造的另一个好处:您也可以将代码作为一个模块进口到另一个脚本,然后运行主功能,如果和当您的程序决定:
import mycode
# ... any amount of other code
mycode.main()
如果此.py 文件是由其他.py 文件进口的,则如果声明下的代码将不会被执行。
如果这个.py 是由 python 运行这个_py.py 在 Shell 下, 或在 Windows 中双击, 该代码在 if 声明 下将执行。
通常是用来测试的。
接收“ab.py”文件:
def a():
print('A function in ab file');
a()
import ab
def main():
print('main function: this is where the action is')
def x():
print ('peripheral task: might be useful in other projects')
x()
if __name__ == "__main__":
main()
当您执行 xy.py 时,您将导入 ab. 导入声明立即在导入上运行模块,因此 ab 的操作在 xy 的剩余之前进行。
当你运行一个脚本 - 无论你命名什么 - 翻译者称之为“__main__”,使它成为主或“家”脚本,在运行一个外部脚本后返回。
下面的两行意味着:“如果这是“__main__”或“home”脚本,执行称为main()的函数”。这就是为什么你会看到一个 def main():锁上顶部,其中包含脚本的功能的主要流。
為什麼要實施這一點?
但代码在没有它的情况下工作。
原因为
if __name__ == "__main__":
main()
首先要避免进口锁问题,即将直接输入代码,您想要主()运行,如果您的文件被直接提交(这是 __name__ ==“__main__”案例),但如果您的代码被进口,则进口商必须从真正的主要模块输入代码,以避免进口锁问题。
一个副作用是,你自动登录到一个方法,支持多个输入点. 你可以运行你的程序使用主要()作为输入点,但你不需要. 虽然 setup.py 等待主要(),其他工具使用替代输入点. 例如,运行你的文件作为一个 gunicorn 过程,你定义一个 app() 函数而不是一个主要()。
考虑一下:
print __name__
上面的结果是 __main__。
if __name__ == "__main__":
print "direct method"
上述声明是真实的,并打印“直接方法”。假设如果他们进口这个类别到另一个类别,它不会打印“直接方法”,因为在进口时,它将设置 __name__ 等于“第一型号名称”。