这样做做什么,为什么应该包括:if
语句?
if __name__ == "__main__":
print("Hello, World!")
如果你试图结束一个问题 如果你想要结束一个问题 在那里有人应该应该 使用这个学说,而不是,是不是, 考虑关闭作为 重复的为什么Python在我进口时 运行我的模块? 我该如何阻止它?。而对于某些问题,如果有人只是没有调用任何函数,或者错误地期望指定函数main
自动用作切入点,使用当我启动 Python 脚本时, 主函数为何不运行? 脚本从哪里开始运行 ?.
您可以将文件作为脚本脚本脚本和(或)可导入可导入模块.
vibbo.py (一个称为模块的模块)fibo
)
# Other modules can IMPORT this MODULE to use the function fib
def fib(n): # write Fibonacci series up to n
a, b = 0, 1
while b < n:
print(b, end=' ')
a, b = b, a+b
print()
# This allows the file to be used as a SCRIPT
if __name__ == "__main__":
import sys
fib(int(sys.argv[1]))
参考:https://docs.python.org/3.5/tutorial/modules.html
用于从命令行调用 Python 文件。 它通常用于调用“ main ()) ” 函数或执行其他合适的启动代码, 比如, 处理命令行参数 。
也可以以几种方式写成。
def some_function_for_instance_main():
dosomething()
__name__ == '__main__' and some_function_for_instance_main()
我不是说你应该用这个来做生产代码, 但是它可以说明,没有什么"神奇"if __name__ == '__main__'
.
这只是援引 Python 文件中主要功能的常规 。
当您在本地交互运行 Python 时__name__
变量的变量被指定值__main__
同样,当您从命令行执行 Python 模块时,而不是将它导入到另一个模块中时,它__name__
属性的属性被指定值__main__
,而不是模块的实际名称。这样,模块可以查看自己的__name__
用于确定它们是如何使用的值, 无论是作为对其它程序的支持还是作为从命令行执行的主要应用程序。 因此, 在 Python 模块中, 下列语系非常常见 :
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.
您可以查看特殊变量__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