转载:python中main的用处:
https://www.2cto.com/kf/201707/661732.html
在一个.py文件中,如果不是在定义函数,也就是说不是在def关键字的内嵌结构内,python会默认其余部分函数是main函数,并自动执行,但正规工程中,一般都会将main函数写为:if__name__==__main__
每个人都在写,但很少有人问,其实这个用法很巧妙!
1
2
3
4
5
6
7
8
|
<code>#hello.py
def sayHello():
str=
"hello"
print(str);
if
__name__ ==
"__main__"
:
print (
'This is main of module "hello.py"'
)
sayHello()</code>
|
单独执行
当单独执行该module时,比如单独执行以上hello.py: python hello.py,则输出
1
2
|
<code>This is main of module
"hello.py"
hello</code>
|
可以理解为”if name==”main“:” 这一句与c中的main()函数所表述的是一致的,即作为入口
用作引用时
当该module被其它module 引入使用时,其中的”if name==”main“:”所表示的Block不会被执行,这是因为此时module被其它module引用时,其name的 值将发生变化,name的值将会是module的名字。比如在python shell中import hello后,查看hello.name:
1
2
3
4
|
<code>>>>
import
hello
>>> hello.__name__
'hello'
>>></code>
|
因此,在python中,当一个module
作为整体被执行时,moduel.name的值将是”main“;而当一个 module
被其它module引用时,module.name将是module自己的名字,当然一个module被其它module引用时,其 本身并不需要一个可执行的入口main了。可以说python中的这种用法很灵活啊。