http://andylin02.iteye.com/blog/933237
http://blog.chinaunix.net/uid-23500957-id-3781176.html
python __file__ 與argv[0]
在python下,獲取當前執行主腳本的方法有兩個:sys.argv[0]和__file__。
sys.argv[0]
獲取主執行文件路徑的最佳方法是用sys.argv[0],它可能是一個相對路徑,所以再取一下abspath是保險的做法,像這樣:
import os,sys
dirname, filename = os.path.split(os.path.abspath(sys.argv[0]))
print "running from", dirname
print "file is", filename
__file__
__file__ 是用來獲得模塊所在的路徑的,這可能得到的是一個相對路徑,比如在腳本test.py中寫入:
#!/usr/bin/env python
print __file__
按相對路徑./test.py來執行,則打印得到的是相對路徑,
按絕對路徑執行則得到的是絕對路徑。
而按用戶目錄來執行(~/practice/test.py),則得到的也是絕對路徑(~被展開)
所以爲了得到絕對路徑,我們需要 os.path.realpath(__file__)。
而在Python控制檯下,直接使用print __file__是會導致 name ‘__file__’ is not defined錯誤的,因爲這時沒有在任何一個腳本下執行,自然沒有 __file__的定義了。
__file__和argv[0]差異
在主執行文件中時,兩者沒什麼差異,不過要是在不同的文件下,就不同了,下面示例:
C:\junk\so>type \junk\so\scriptpath\script1.py
import sys, os
print "script: sys.argv[0] is", repr(sys.argv[0])
print "script: __file__ is", repr(__file__)
print "script: cwd is", repr(os.getcwd())
import whereutils
whereutils.show_where()
C:\junk\so>type \python26\lib\site-packages\whereutils.py
import sys, os
def show_where():
print "show_where: sys.argv[0] is", repr(sys.argv[0])
print "show_where: __file__ is", repr(__file__)
print "show_where: cwd is", repr(os.getcwd())
C:\junk\so>\python26\python scriptpath\script1.py
script: sys.argv[0] is 'scriptpath\\script1.py'
script: __file__ is 'scriptpath\\script1.py'
script: cwd is 'C:\\junk\\so'
show_where: sys.argv[0] is 'scriptpath\\script1.py'
show_where: __file__ is 'C:\\python26\\lib\\site-packages\\whereutils.pyc'
show_where: cwd is 'C:\\junk\\so'
所以一般來說,argv[0]要更可靠些。
python中__name__的使用
1. 如果模塊是被導入,__name__的值爲模塊名字
2. 如果模塊是被直接執行,__name__的值爲’__main__’
Py1.py
#!/usr/bin/env python
def test():
print '__name__ = ',__name__
if __name__ == '__main__':
test()
Py2.py
#!/usr/bin/env python
import Py1.py
def test():
print '__name__ = ',__name__
if __name__ == '__main__':
test()
print ‘Py1.py __name__ = ’,Py1.__name__
執行結果:
__name__=__main__
Py1.py __name__=Py1
通過結果可以知道,Py2.py直接執行,那麼內建變量__name__的值爲__main__,否則爲模塊的名字,通過這個特性可以在if語句裏面添加測試代碼,可以提高減少BUG,提高程序的健壯性。
if __name__ == '__main__':
test()