这是什么,为什么应该包括一个 if 声明?
if __name__ == "__main__":
print("Hello, World!")
如果你试图关闭一个问题,有人应该使用这个字符,而不是,考虑关闭作为一个复制为什么Python在我进口时运行我的模块,而我如何停止它? 问题,有人只是没有呼叫任何功能,或者错误地等待一个名为主的功能将自动作为一个输入点,使用为什么没有主()功能运行。
这是什么,为什么应该包括一个 if 声明?
if __name__ == "__main__":
print("Hello, World!")
如果你试图关闭一个问题,有人应该使用这个字符,而不是,考虑关闭作为一个复制为什么Python在我进口时运行我的模块,而我如何停止它? 问题,有人只是没有呼叫任何功能,或者错误地等待一个名为主的功能将自动作为一个输入点,使用为什么没有主()功能运行。
当前回答
您可以将文件作为一个脚本以及一个可进口的模块使用。
fibo.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 文件, a.py 和 b.py. 现在, a.py 输入 b.py. 我们运行 a.py 文件,其中输入 b.py 代码首先执行。
在 b.py 代码中,有一些代码是专属于 b.py 文件,我们不希望任何其他文件(除了 b.py 文件),已进口了 b.py 文件,运行它。
如果它是主要文件(即,b.py)运行代码,在这种情况下它不是(a.py是主要文件运行),那么只有代码被执行。
让我们以更抽象的方式来看看答案:
假设我们有这个代码在x.py:
...
<Block A>
if __name__ == '__main__':
<Block B>
...
区块 A 和 B 运行,当我们运行 x.py。
但只有区块A(而不是B)运行,当我们运行另一个模块,例如 y.py,其中 x.py 被进口,代码从那里运行(就像在 x.py 的函数从 y.py 被称为时一样)。
如果此.py 文件是由其他.py 文件进口的,则如果声明下的代码将不会被执行。
如果这个.py 是由 python 运行这个_py.py 在 Shell 下, 或在 Windows 中双击, 该代码在 if 声明 下将执行。
通常是用来测试的。
当您互动运行Python时,本地 __name__ 变量被分配为 __main__ 的值。 同样,当您从命令行中执行一个Python 模块时,而不是将其导入到另一个模块时,其 __name__ 属性被分配为 __main__ 的值,而不是模块的实际名称。
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__ == '__main__'
当我们进口一个模块时,它内部的所有代码都从开始到结束,但当它达到条件时,它不运行函数、函数2等,即维基百科 __scrape__。
好吧,在全球范围内,Python __name__ 为当前程序定义为“__main__”。
当我们进口一个模块时,它被定义为我们当前程序的名称空间中的变量,而当前程序 __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')
出口
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'>