標籤:
@python __file__ 與argv[0]
在python下,擷取當前執行主指令碼的方法有兩個:sys.argv[0]和__file__。
sys.argv[0]
擷取主執行檔案路徑的最佳方法是用sys.argv[0],它可能是一個相對路徑,所以再取一下abspath是保險的做法,像這樣:
import os,sysdirname, filename = os.path.split(os.path.abspath(sys.argv[0]))print "running from", dirnameprint "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.pyimport sys, osprint "script: sys.argv[0] is", repr(sys.argv[0])print "script: __file__ is", repr(__file__)print "script: cwd is", repr(os.getcwd())import whereutilswhereutils.show_where() C:\junk\so>type \python26\lib\site-packages\whereutils.pyimport sys, osdef 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.pyscript: 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‘
此外還有os.getcwd(),獲得檔案夾 的絕對路徑
根據不同的用途選擇不同的函數
python __file__ 與argv[0]