if __name__ == "__main__":

在大多数编排得好一点的脚本或者程序里面都有这段if __name__ == "__main__": ,收集资料详细理解之后与大家分享。

对python中的__name__和__main__的解释可以看这篇文章:  http://www.crifan.com/python_detailed_explain_about___name___and___main__/comment-page-1/)

1、这段代码的功能

   一个python的文件有两种使用的方法,第一是直接作为脚本执行,第二是import到其他的python脚本中被调用(模块重用)执行。因此if __name__ == "__main__": 的作用就是控制这两种情况执行代码的过程,在if __name__ == "__main__": 下的代码只有在第一种情况下(即文件作为脚本直接执行)才会被执行,而import到其他脚本中是不会被执行的。

  举个例子,下面在test.py中写入如下代码:

    print "the first"
	print __name__

	if __name__=='main':
		print "the second"

  并直接执行test.py,结果如下图,可以成功print两行字符串。即, if __name__=="__main__": 语句之前和之后的代码都被执行

python脚本测试


然后在同一文件夹新建名称为import_test.py的脚本,只输入如代码:

import test

执行 import_test.py脚本,输出结果如下:

 
if __name__=="__main__"演示

只输出了第一行字符串。即,if __name__=="__main__": 之前的语句被执行,之后的没有被执行

 2、运行的原理

   每个python模块(python文件,也就是此处的test.py和import_test.py)都包含内置的变量__name__,当运行模块被执行的时候,__name__等于文件名(包含了后缀.py);如果import到其他模块中,则__name__等于模块名称(不包含后缀.py)。而“__main__”等于当前执行文件的名称(包含了后缀.py)。进而当模块被直接执行时,__name__ =="__main__"结果为真。

  同样举例说明,我们在test.py脚本的if __name__=="__main__":之前加入print __name__,即将__name__打印出来。文件内容和结果如下,

python脚本

  可以看出,此时变量__name__的值为"__main__";
  再执行import_test.py,模块内容和执行结果如下:

 __name__变量

  此时,test.py中的__name__变量值为test,不满足__name__=="__main__"的条件,因此,无法执行其后的代码。

 

总结一下:

如果我们是直接执行某个.py文件的时候,该文件中”__name__ == '__main__'“是True; 但是我们如果从另外一个.py文件通过import导入该文件的时候,这时__name__的值就是我们这个py文件的名字而不是__main__。

这就使得a.py在作为模块被b.py导入时,a中在该条件语句下面的内容不被执行,b可以有选择地调用并执行a中的类或函数;而当a作为执行主体运行时,就可以运行该条件语句下面的代码了。

这个功能还有一个用处:调试代码的时候,在”if __name__ == '__main__'“中加入一些我们的调试代码,我们可以让外部模块调用的时候不执行我们的调试代码,但是如果我们想排查问题的时候,直接执行该模块文件,调试代码能够正常运行!

Stackoverflow中大神Adam Rosenfield给出了下面的解释:

When your script is run by passing it as a command to the Python interpreter,

python myscript.py

all of the code that is at indentation level 0 gets executed. Functions and classes that are defined are, well, defined, but none of their code gets ran. Unlike other languages, there's no main()function that gets run automatically - the main() function is implicitly all the code at the top level.

In this case, the top-level code is an if block. __name__ is a built-in variable which evaluate to the name of the current module. However, if a module is being run directly (as in myscript.pyabove), then __name__ instead is set to the string "__main__". Thus, you can test whether your script is being run directly or being imported by something else by testing

if __name__ == "__main__":
    ...

If that code is being imported into another module, the various function and class definitions will be imported, but the main() code won't get run. As a basic example, consider the following two scripts:

# file one.py
def func():
    print("func() in one.py")

print("top-level in one.py")

if __name__ == "__main__":
    print("one.py is being run directly")
else:
    print("one.py is being imported into another module")

# file two.py
import one

print("top-level in two.py")
one.func()

if __name__ == "__main__":
    print("two.py is being run directly")
else:
    print("two.py is being imported into another module")

Now, if you invoke the interpreter as

python one.py

The output will be

top-level in one.py
one.py is being run directly

If you run two.py instead:

python two.py

You get

top-level in one.py
one.py is being imported into another module
top-level in two.py
func() in one.py
two.py is being run directly

Thus, when module one gets loaded, its __name__ equals "one" instead of __main__.

另一个过千赞的回答:

When the Python interpreter reads a source file, it executes all of the code found in it.

Before executing the code, it will define a few special variables. For example, if the python interpreter is running that module (the source file) as the main program, it sets the special __name__ variable to have a value "__main__". If this file is being imported from another module, __name__ will be set to the module's name.

In the case of your script, let's assume that it's executing as the main function, e.g. you said something like

python threading_example.py

on the command line. After setting up the special variables, it will execute the import statement and load those modules. It will then evaluate the def block, creating a function object and creating a variable called myfunction that points to the function object. It will then read the if statement and see that __name__ does equal "__main__", so it will execute the block shown there.

One of the reasons for doing this is that sometimes you write a module (a .py file) where it can be executed directly. Alternatively, it can also be imported and used in another module. By doing the main check, you can have that code only execute when you want to run the module as a program and not have it execute when someone just wants to import your module and call your functions themselves.

See this page for some extra details.


参考:

[1] http://www.dengfeilong.com/post/60.html

[2] http://stackoverflow.com/users/9530/adam-rosenfield

[3] https://stackoverflow.com/questions/419163/what-does-if-name-main-do/419189#419189?newreg=971dcc7c28b646cdb4c99462fb08d032

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值