这是什么,为什么应该包括一个 if 声明?
if __name__ == "__main__":
print("Hello, World!")
如果你试图关闭一个问题,有人应该使用这个字符,而不是,考虑关闭作为一个复制为什么Python在我进口时运行我的模块,而我如何停止它? 问题,有人只是没有呼叫任何功能,或者错误地等待一个名为主的功能将自动作为一个输入点,使用为什么没有主()功能运行。
这是什么,为什么应该包括一个 if 声明?
if __name__ == "__main__":
print("Hello, World!")
如果你试图关闭一个问题,有人应该使用这个字符,而不是,考虑关闭作为一个复制为什么Python在我进口时运行我的模块,而我如何停止它? 问题,有人只是没有呼叫任何功能,或者错误地等待一个名为主的功能将自动作为一个输入点,使用为什么没有主()功能运行。
当前回答
简单地说,这是运行文件的输入点,就像C编程语言的主要功能一样。
其他回答
接收“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文件从命令线被召唤时,通常用来召唤一个“主()”函数或执行其他适当的启动代码,如命令线论点处理,例如。
它可以用多种方式写出来,另一个是:
def some_function_for_instance_main():
dosomething()
__name__ == '__main__' and some_function_for_instance_main()
我不是说你应该在生产代码中使用这一点,但它用来解释是否有“魔法”的东西。
它只是在Python文件中引用一个主要功能的条约。
当您输入某种具有此条件的代码时,它将返回虚假(进口代码内),但将返回正确的代码将运行。
如果 __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'
请注意,仅在 my_test_module 中执行顶级印刷() 声明。
第二种可能性:将 my_test_module.py 作为脚本提交
现在,如果你将 my_test_module.py 作为 Python 脚本运行,那么打印() 陈述将运行:
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'
对于更全面的解释,您可以阅读在 Python 中做什么 __name__ == '__main__' 。
如果 __name__ ==“__main__”意味着如果您正常运行 Python 文件如 python foo.py,则将特殊变量 __name__ 归分为“__main__”。
但是,如果您正在导入文件如“导入 foo”,则将 __name__ 归分为“foo”并且不会运行函数。