python __file__ 與argv[0]

來源:互聯網
上載者:User

標籤:

@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]

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.