这是什么,为什么应该包括一个 if 声明?

if __name__ == "__main__":
    print("Hello, World!")

如果你试图关闭一个问题,有人应该使用这个字符,而不是,考虑关闭作为一个复制为什么Python在我进口时运行我的模块,而我如何停止它? 问题,有人只是没有呼叫任何功能,或者错误地等待一个名为主的功能将自动作为一个输入点,使用为什么没有主()功能运行。


当前回答

假设我在维基百科上写了网页扫描的功能和课程,当然,这可能不是一个好例子。

我想在另一个程序中使用这些功能,而不重写它。

好吧,我进口它们,但在该文件的结尾我把 __name__ == '__main__'

当我们进口一个模块时,它内部的所有代码都从开始到结束,但当它达到条件时,它不运行函数、函数2等,即维基百科 __scrape__。

好吧,在全球范围内,Python __name__ 为当前程序定义为“__main__”。

当我们进口一个模块时,它被定义为我们当前程序的名称空间中的变量,而当前程序 __name__ 是“__main__”:

文件测试.py

def func():
    # Do something
    pass

def func2():
    # Do something
    pass

print('The program name is set to ', globals()['__name__'])

if __name__=='__main__':
    # In the current program, __name__ is equal to '__main__'
    func('https://www.wikipedia.org')
    func2('https://www.wikipedia.org')
    # Or do more jobs

import test1
print('inside of current program')
print('name is current program', __name__)
print(globals()['test1'])
test1.func('another site')
test1.func2('another site')

出口

inside of test 1
name of program is set to test1
end of module
inside of current
__main__
<module 'test1' from 'C:\\users\\ir\\appdata\\local\\programs\\python\\python38\\lib\\test1.py'>

其他回答

考虑一下:

print __name__

上面的结果是 __main__。

if __name__ == "__main__":
  print "direct method"

上述声明是真实的,并打印“直接方法”。假设如果他们进口这个类别到另一个类别,它不会打印“直接方法”,因为在进口时,它将设置 __name__ 等于“第一型号名称”。

让我们以更抽象的方式来看看答案:

假设我们有这个代码在x.py:

...
<Block A>
if __name__ == '__main__':
    <Block B>
...

区块 A 和 B 运行,当我们运行 x.py。

但只有区块A(而不是B)运行,当我们运行另一个模块,例如 y.py,其中 x.py 被进口,代码从那里运行(就像在 x.py 的函数从 y.py 被称为时一样)。

只有你需要知道的事实

实际的机械是相当简单的,只有两个基本事实:

纯 Python 模块总是用“__main__”字符串设置的变量 __name__ 创建。 导入一个模块具有改变 __name__ 变量的副作用,而无需.py 扩展。

如何使用此信息

人們寫 __name__ == '__main__' 以測試是否有一個模組已被輸入。

通常有某些代码不应该在进口时运行:测试代码,一次使用代码,命令线前端或网页服务器前端。

正如你可以从其他答案中看到的那样,人们似乎能够无限地谈论这个主题,但它确实是一个简单的事情,并且很容易掌握。

如果我们有两本书,

#script1.py
print "Script 1's name: {}".format(__name__)

#script2.py
import script1
print "Script 2's name: {}".format(__name__)

此分類上一篇: Executing script1

Script 1's name: __main__

执行脚本2的结果是:

Script1's name is script1
Script 2's name: __main__

正如你可以看到的那样, __name__ 告诉我们哪个代码是“主要”模块,这是很好的,因为你只能写代码,并且不需要担心结构问题,如在 C/C++ 中,如果一个文件不执行一个“主要”函数,那么它不能作为一个可执行的编写,如果是这样,它不能用作图书馆。

箭头是进口链接. 对于三个模块,每个试图包含以前的模块代码,有六个文件(九个,计算实施文件)和五个链接. 这使得很难将其他代码纳入一个C项目,除非它是专门编写为图书馆。

此分類上一篇

当您互动运行Python时,本地 __name__ 变量被分配为 __main__ 的值。 同样,当您从命令行中执行一个Python 模块时,而不是将其导入到另一个模块时,其 __name__ 属性被分配为 __main__ 的值,而不是模块的实际名称。

if __name__ == '__main__':
    # Do something appropriate here, like calling a
    # main() function defined elsewhere in this module.
    main()
else:
    # Do nothing. This module has been imported by another
    # module that wants to make use of the functions,
    # classes and other useful bits it has defined.