这样做做什么,为什么应该包括: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
您可以将文件作为脚本脚本脚本和(或)可导入可导入模块.
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 口译员正在运行一个特定模块,那么__name__
全局变量将拥有值"__main__"
:
def a():
print("a")
def b():
print("b")
if __name__ == "__main__":
print ("you can see me")
a()
else:
print ("You can't see me")
b()
当您运行此脚本时, 它会打印 :
you can see me
a
如果您导入此文件, 请说A
要到文件的文件B
,然后执行文件B
时当时if __name__ == "__main__"
文件中的文件A
成为假假,所以它指纹:
You can't see me
b