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

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

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


当前回答

在 Python 中,每个模块都有一个称为 __name__ 的属性. __name__ 的值是 __main__ 当模块直接运行时,如 python my_module.py. 否则(如您说 import my_module) __name__ 的值是模块的名称。

一个小例子要简要解释。

脚本测试.py

apple = 42

def hello_world():
    print("I am inside hello_world")

if __name__ == "__main__":
    print("Value of __name__ is: ", __name__)
    print("Going to call hello_world")
    hello_world()

我们可以直接这样做。

python test.py

出口

Value of __name__ is: __main__
Going to call hello_world
I am inside hello_world

现在假设我们从另一个脚本中称之为上面的脚本:

编辑 external_calling.py

import test

print(test.apple)
test.hello_world()

print(test.__name__)

当你执行这一点时,

python external_calling.py

出口

42
I am inside hello_world
test

因此,上述是自我解释的,当你从另一个脚本打电话测试时,如果在 test.py 中的 loop __name__ 不会执行。

其他回答

如果 __name__ ==“__main__”是当脚本从(说)命令线运行时运行的部分,使用像 python myscript.py 这样的命令。

简单的答案是下方写的代码,如果名称 ==“主”:如果您将其输入到另一个文件,则不会执行。

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

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

好吧,我进口它们,但在该文件的结尾我把 __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'>

创建以下两个文件:

# a.py

import b
# b.py

print("__name__ equals " + __name__)

if __name__ == '__main__':
    print("if-statement was executed")

现在将每个文件单独运行。


使用 Python A.Py:

$ python a.py
__name__ equals b

当 a.py 运行时,它会导入 b 模块,这会导致 b 内部的所有代码运行。


运行Python b.py:

$ python b.py
__name__ equals __main__
if-statement was executed

当只执行 b.py 文件时,Python 在此文件中将 globals()['__name__'] 设置为 "__main__". 因此,如果声明评估为 True 这一次。

如果我们有两本书,

#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项目,除非它是专门编写为图书馆。

此分類上一篇