这样做做什么,为什么应该包括:if语句?

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

如果你试图结束一个问题 如果你想要结束一个问题 在那里有人应该应该 使用这个学说,而不是,是不是, 考虑关闭作为 重复的为什么Python在我进口时 运行我的模块? 我该如何阻止它?。而对于某些问题,如果有人只是没有调用任何函数,或者错误地期望指定函数main自动用作切入点,使用当我启动 Python 脚本时, 主函数为何不运行? 脚本从哪里开始运行 ?.


当前回答

if __name__ == "__main__"意指,如果您正在运行 Python 文件,通常就像python foo.py,它将指定特殊变量__name__"__main__".

但如果您正在像“ 进口 foo ” 那样导入文件, 它将会指派__name__"foo"并且不会运行函数。

其他回答

假设我在维基百科上为网上剪贴写功能和课程。 当然,这也许不是一个好例子。

我想在另一个程序里使用这些函数 而不改写它

嗯,我进口了它们, 但是在文件的结尾,我放__name__ == '__main__'

当我们importa 模块,其中的所有代码都从开始到结束执行。但是当它达到条件时,它不会运行调乐曲 func, 复真2c2cfluc2等,这是维基百科__scrape__.

那么,在全球范围内,Python(Python)__name__定义为'__main__'用于当前程序 。

当我们import模块,它定义为当前程序和当前程序的名称空间中的变量。__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')

Output

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'>

除了已经提供的资料外,if __name__ == "__main__":技术也是确保pytestunittest如果您不小心调用脚本, 脚本仍然在运行python代替pytest(或)python -m unittest举例来说:

def test_assert():
    assert 1 + 2 == 3

if __name__ == "__main__":
    import pytest
    pytest.main([__file__])

现在不管怎么称呼你的测试 都会在测试中进行pytestpython。在这里,这是unittest版本 :

import unittest

class Tests(unittest.TestCase):
    def test_assert(self):
        self.assertTrue(1 + 2 == 3)

if __name__ == "__main__":
    unittest.main()

然后您的脚本用python以一计号,以python -m unittest拨打。

现在,如果你也想确保 你所有的价码都通过pytest如果被召唤时python或者,如果你也想加入额外的参考物呢?

def test_assert():
    assert 1 + 2 == 3

if __name__ == "__main__":
    from pytest import main
    from sys import argv
    main([*argv, "-s"])

现在,你的python -v --html=report.html具有与pytest -v --html=report.html,等等。这是一个很好的方法,可以确保脚本仍然照原意运行, 即使没有按照预期运行pytestpython -m unittest电话

系统( Python 口译员) 提供源文件( 模块) 的变量。 您可以随时获得源文件的值, 因此, 让我们集中关注- 名称 - 名称 - 名称变量/属性 :

当 Python 装入源代码文件时, 它会执行其中的所有代码 。 (注意它不会调用文件中定义的所有方法和函数, 但是它会定义它们 。 )

在口译员执行源代码文件之前,它为该文件定义了几个特殊变量;- 名称 - 名称 - 名称是 Python 为每个源代码文件自动定义的特殊变量之一。

如果 Python 正在装入此源代码文件作为主程序( 即您运行的文件) , 它会设置特殊- 名称 - 名称 - 名称此文件有值的变量"... main..." "... main...".

如果这是从另一个模块导入的,- 名称 - 名称 - 名称将设定为该模块的名称。

所以,在你的部分例子中:

if __name__ == "__main__":
   lock = thread.allocate_lock()
   thread.start_new_thread(myfunction, ("Thread #: 1", 2, lock))
   thread.start_new_thread(myfunction, ("Thread #: 2", 2, lock))

意思是代码块:

lock = thread.allocate_lock()
thread.start_new_thread(myfunction, ("Thread #: 1", 2, lock))
thread.start_new_thread(myfunction, ("Thread #: 2", 2, lock))

只有当您直接运行模块模块时才会执行;如果另一个模块正在调用/导入代码块,代码块将不执行,因为- 名称 - 名称 - 名称" 等于 " 等于 " 等于 " 等于 " 等于 " 等于 " 等于 " 等于 " 等于 " 等于 " 等于 "主要" 在此特定情况下。

希望这能帮上忙

所有答案都大致解释了它的功能。但我将举一个例子来说明它的用法,这可能有助于进一步澄清这个概念。

假设你有两个Python文件,A.py和B.py。a.py进口进口进口b.py。我们运行a.py文件, 在哪里import b.py代码先执行。在其余a.py代码运行,文件中的代码b.py必须完全运行。

在b.py 代码中,有一些代码是那个文件的独有代码b.py我们不想要任何其他文件(不包括b.py已导入 b. py 文件来运行 。

这就是这行代码检查。如果它是主文件(即,b.py运行代码,在这种情况下它不是代码 (a.py是正在运行的主文件),然后只有代码才能被执行。

当我们的模块中有某些语句时(M.py)我们想要当它作为主(而非导入)运行时被执行, 我们可以将这些语句( 测试案例、 打印语句) 置于此下if区块。

默认值( 当模块作为主模式运行时, 不导入)__name__变量设置为"__main__",当它将进口__name__变量将获得不同的值, 最有可能是模块的名称('M'这有助于将模块的不同变量合并运行,并区分其具体的输入和输出语句,以及如果有任何测试案例的话。

简简,使用此“if __name__ == "main"防止模块导入时运行(确定)代码的块。