"if name =="__main__""在Python中是什么意思? [英] What does `if name == "__main__"` mean in Python?

查看:78
本文介绍了"if name =="__main__""在Python中是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
<如果 name ==“ main ”:>

Possible Duplicate:
What does <if name==“main”:> do?

我已经用Python编写了很长时间的脚本,并且在需要时我研究了更多的Python.在阅读别人的代码时,我经常遇到if name == "__main__":构造.

I have wrote scripts in Python for quite a while now and I study more of Python as I need it. When reading other people's code I meet if name == "__main__": construct quite often.

这有什么用?

推荐答案

这使您可以将同一文件用作库(通过导入)或应用程序的起点.

This allows you to use the same file both as a library (by importing it) or as the starting point for an application.

例如,考虑以下文件:

# hello.py
def hello(to=__name__):
    return "hello, %s" % to

if __name__ == "__main__":
    print hello("world")

您可以通过两种方式使用该代码.首先,您可以编写一个导入它的程序.如果导入库,则__name__将是库的名称,因此检查将失败,并且代码将无法执行(这是所需的行为):

You can use that code in two ways. For one, you can write a program that imports it. If you import the library, __name__ will be the name of the library and thus the check will fail, and the code will not execute (which is the desired behavior):

#program.py
from hello import hello # this won't cause anything to print
print hello("world")

如果您不想编写第二个文件,则可以使用以下命令直接从命令行运行代码:

If you don't want to write this second file, you can directly run your code from the command line with something like:

$ python hello.py
hello, __main__

所有行为都取决于特殊变量__name__,该变量将由python根据库是由解释器导入还是直接由解释器运行来设置.如果直接运行,它将设置为__main__.如果导入,它将被设置为库名称(在这种情况下为hello).

This behavior all depends on the special variable __name__ which python will set based on whether the library is imported or run directly by the interpreter. If run directly it will be set to __main__. If imported it will be set to the library name (in this case, hello).

通常,此构造用于将单元测试添加到您的代码中.这样,当您编写一个库时,可以将测试代码直接嵌入文件中,而不必担心正常使用库时该代码将被执行.当您要测试库时,不需要任何框架,因为您可以像运行程序一样运行库.

Often this construct is used to add unit tests to your code. This way, when you write a library you can embed the testing code right in the file without worrying that it will get executed when the library is used in the normal way. When you want to test the library, you don't need any framework because you can just run the library as if it were a program.

另请参见python文档中的 __main__ (尽管它非常稀疏)

See also __main__ in the python documentation (though it's remarkably sparse)

这篇关于"if name =="__main__""在Python中是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆