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

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

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


当前回答

接收“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():锁上顶部,其中包含脚本的功能的主要流。

為什麼要實施這一點?

但代码在没有它的情况下工作。

其他回答

当您输入某种具有此条件的代码时,它将返回虚假(进口代码内),但将返回正确的代码将运行。

系统(Python 翻译器)为源文件(模块)提供的一些变量,您可以随时获得它们的值,所以,让我们专注于 __name__ 变量/属性:

如果 Python 将此源代码文件作为主程序(即您运行的文件),则将此文件的特殊 __name__ 变量设置为“__main__”值。

如果从另一个模块进口,则 __name__ 将设置到该模块的名称。

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

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

希望这能帮出来。


开发和测试您的代码

def do_important():
    """This function does something very important"""

do_important()

以此为主,以此为主,以此为主。

~$ python important.py

问题

但是,如果你想将模块导入到另一个脚本:

import important

# do_important() # I must remember to uncomment to execute this!

更好的方式

if __name__ == "__main__":
    do_important()

但是,在这一点上,有一个皮托尼的改善方式。

如果我们想从模块之外运行这个业务过程,怎么办?

如果我们把我们想要练习的代码,当我们开发并测试这样的功能时,然后立即检查“__main__”之后:

def main():
    """business logic for when running this module as the primary one!"""
    setup()
    foo = do_important()
    bar = do_even_more_important(foo)
    for baz in bar:
        do_super_important(baz)
    teardown()

# Here's our payoff idiom!
if __name__ == '__main__':
    main()

我们现在有一个最终功能,我们的模块的结束将运行,如果我们运行模块作为主模块。

它将允许模块及其功能和类被进口到其他脚本,而不运行主功能,并将允许模块(及其功能和类)在从不同的“__main__”模块运行时被召唤,即。

import important
important.main()

除了已经提供的信息,如果 __name__ ==“__main__”:技术也是一个很好的方式来确保您的最小和最单一的脚本仍然运行,如果你偶然用Python而不是Python(或Python -m最单一)。

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

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

import unittest

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

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

然后,你的脚本与 Python 呼叫相同,就像 Python -m 最单一的呼叫一样。

现在,如果你也想确保所有的麻烦被转移到问答,如果用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 等相同的效果,这是一个很好的方式来确保脚本仍然按照意图运行,即使不与预期的 pytest 或 python -m 最单一的通话运行。

当我们模块(M.py)中有某些声明时,我们希望当它作为主要(不进口)运行时,我们可以将这些声明(测试文件夹、印刷声明)置于此下,如果它被阻止。

默认情况下(当模块作为主运行时,不进口) __name__ 变量设置为“__main__”,当它被进口时, __name__ 变量将获得不同的值,最有可能是模块的名称(“M”)。

简而言之,使用这个“如果 __name__ ==“主””块,以防止(一定)代码在模块进口时运行。