我们经常在python 程序中看到 if __name__ == '__main__' :这代表什么意思?
python中 模块是对象,并且所有的模块都有一个内置属性 __name__。一个模块的__name__的值取决于您如何应用模块。如果 import 一个模块,那么模块__name__ 的值通常为模块文件名,不带路径或者文件扩展名。但是您也可以像一个标准的程序样直接运行模块,在这 种情况下, __name__ 的值将是一个特别缺省"__main__"。
具体一点,在cmd 中直接运行.py文件,则__name__的值是'__main__';
而在import 一个.py文件后,__name__的值就不是'__main__'了;
从而用if __name__ == '__main__'来判断是否是在直接运行该.py文件
[root@rac1 python]# cat st.py
#!/usr/bin/evn python
import os
import time
file = "/root/sed.txt"
def dump(st):
mode,ino, dev, nlink, uid, gid, size, atime, mtime, ctime = st
print "- size :", size, "bytes"
print "- owner:", uid, gid
print "- created:", time.ctime(ctime)
print "- last accessed:", time.ctime(atime)
print "- last modified:", time.ctime(mtime)
print "- mode:", oct(mode)
print "- inode/dev:", ino, dev
# # get stats for a filename
if __name__ == '__main__':
st = os.stat(file)
print "stat : "
print dump(st)
# # get stats for an open file
fp = open(file)
st = os.fstat(fp.fileno())
print "fstat : "
print dump(st)
你在cmd中输入:
[root@rac1 python]# python st.py
stat :
- size : 23 bytes
- owner: 0 0
- created: Tue Nov 20 21:56:19 2012
- last accessed: Wed Nov 21 14:43:08 2012
- last modified: Tue Nov 20 21:56:19 2012
- mode: 0100644
- inode/dev: 17039538 2051
None
fstat :
- size : 23 bytes
- owner: 0 0
- created: Tue Nov 20 21:56:19 2012
- last accessed: Wed Nov 21 14:43:08 2012
- last modified: Tue Nov 20 21:56:19 2012
- mode: 0100644
- inode/dev: 17039538 2051
None
说明:"__name__ == '__main__'"是成立。
[root@rac1 python]# python
Python 2.5 (r25:51908, Jun 6 2012, 10:32:42)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-44)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> __name__ #当前程序的__name__
'__main__'
>>>
>>>
>>> import st
>>> st.__name__ #st 模块的__name__
'st'
>>>
无论怎样,st.py中的"__name__ == '__main__'"都不会成立的!
所以,下一行代码永远不会运行到!