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]要更可靠些。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM