这是什么,为什么应该包括一个 if 声明?
if __name__ == "__main__":
print("Hello, World!")
如果你试图关闭一个问题,有人应该使用这个字符,而不是,考虑关闭作为一个复制为什么Python在我进口时运行我的模块,而我如何停止它? 问题,有人只是没有呼叫任何功能,或者错误地等待一个名为主的功能将自动作为一个输入点,使用为什么没有主()功能运行。
这是什么,为什么应该包括一个 if 声明?
if __name__ == "__main__":
print("Hello, World!")
如果你试图关闭一个问题,有人应该使用这个字符,而不是,考虑关闭作为一个复制为什么Python在我进口时运行我的模块,而我如何停止它? 问题,有人只是没有呼叫任何功能,或者错误地等待一个名为主的功能将自动作为一个输入点,使用为什么没有主()功能运行。
当前回答
原因为
if __name__ == "__main__":
main()
首先要避免进口锁问题,即将直接输入代码,您想要主()运行,如果您的文件被直接提交(这是 __name__ ==“__main__”案例),但如果您的代码被进口,则进口商必须从真正的主要模块输入代码,以避免进口锁问题。
一个副作用是,你自动登录到一个方法,支持多个输入点. 你可以运行你的程序使用主要()作为输入点,但你不需要. 虽然 setup.py 等待主要(),其他工具使用替代输入点. 例如,运行你的文件作为一个 gunicorn 过程,你定义一个 app() 函数而不是一个主要()。
其他回答
如果 Python 翻译器运行一个特定的模块,那么 __name__ 全球变量将有“__main__”的值:
def a():
print("a")
def b():
print("b")
if __name__ == "__main__":
print ("you can see me")
a()
else:
print ("You can't see me")
b()
当你运行这个脚本时,它打印:
you can see me
a
如果您输入此文件,请说 A 到 B 文件,然后执行 B 文件,然后如果 __name__ == “__main__” 在 A 文件中变成错误,那么它打印:
You can't see me
b
您可以通过这个简单的例子查看特殊变量 __name__:
创建 file1.py
if __name__ == "__main__":
print("file1 is being run directly")
else:
print("file1 is being imported")
创建 *file2.py
import file1 as f1
print("__name__ from file1: {}".format(f1.__name__))
print("__name__ from file2: {}".format(__name__))
if __name__ == "__main__":
print("file2 is being run directly")
else:
print("file2 is being imported")
执行 file2.py
出口:
file1 is being imported
__name__ from file1: file1
__name__ from file2: __main__
file2 is being run directly
简单地说,这是运行文件的输入点,就像C编程语言的主要功能一样。
例如,这是 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
考虑一下:
if __name__ == "__main__":
main()
它检查Python脚本的 __name__属性是否是“__main__”。换句话说,如果程序本身执行,属性将是 __main__,因此程序将执行(在这种情况下,主()函数)。
但是,如果您的 Python 脚本是由一个模块使用的,任何代码外的,如果声明将执行,所以如果 __name__ ==“__main__”是用来检查程序是否作为一个模块使用,因此决定是否运行代码。