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

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

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


当前回答

除了已经提供的资料外,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电话

其他回答

下代码的代码if __name__ == '__main__':仅仅如果将模块作为脚本引用,则执行该模块。

例如,考虑以下模块my_test_module.py:

# my_test_module.py

print('This is going to be printed out, no matter what')

if __name__ == '__main__':
    print('This is going to be printed out, only if user invokes the module as a script')

第一种可能性:进口my_test_module.py在另一个模块中

# main.py

import my_test_module

if __name__ == '__main__':
    print('Hello from main.py')

如果你现在祈祷main.py:

python main.py

>> 'This is going to be printed out, no matter what'
>> 'Hello from main.py'

请注意,只有最高层print()语中的语中my_test_module执行。


第二种可能性:my_test_module.py作为脚本

现在,如果你现在跑my_test_module.py作为 Python 脚本, 两者print()将执行语句:

python my_test_module.py

>>> 'This is going to be printed out, no matter what'
>>> 'This is going to be printed out, only if user invokes the module as a script'

更全面的解释,可读作:什么是什么东西if __name__ == '__main__'在 Python 中做.

if __name__ == "__main__"是在脚本从命令行运行时运行的部分,使用类似命令python myscript.py.

您可以查看特殊变量__name__使用此简单示例 :

创建创建文件1. py

if __name__ == "__main__":
    print("file1 is being run directly")
else:
    print("file1 is being imported")

创建 *file2。平平

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

执行文件2. py

Output:

file1 is being imported
__name__ from file1: file1
__name__ from file2: __main__
file2 is being run directly

简言之:

您所看到的代码下面的代码if __name__ == "__main__":只有当您的 Python 文件被执行时才会被调用 。python example1.py

但是,如果您想要导入您的 Python 文件example1.py以模块的形式使用另一个 Python 文件, 例如example2.py下的代码if __name__ == "__main__":将不会运行或产生任何效果。

用于从命令行调用 Python 文件。 它通常用于调用“ main ()) ” 函数或执行其他合适的启动代码, 比如, 处理命令行参数 。

也可以以几种方式写成。

def some_function_for_instance_main():
    dosomething()


__name__ == '__main__' and some_function_for_instance_main()

我不是说你应该用这个来做生产代码, 但是它可以说明,没有什么"神奇"if __name__ == '__main__'.

这只是援引 Python 文件中主要功能的常规 。