簡體   English   中英

如何獲取python程序的完整路徑,包括程序中的文件名?

[英]How to get full path to python program including filename within the program?

我有一個python程序,我想從程序內部獲取程序的路徑,但要包含文件名本身。 我的文件名為PyWrapper.py。 現在我正在這樣做:

import sys,os
pathname = os.path.dirname(sys.argv[0])
fullpath = os.path.abspath(pathname)
print fullpath

輸出為:

 /home/mrpickles/Desktop/HANSTUFF/securesdk/src/

這是保存文件的目錄的路徑,但是我希望它輸出:

/home/mrpickles/Desktop/HANSTUFF/securesk/src/PyWrapper.py/

這是路徑,包括文件名本身。 這可能嗎? 謝謝。

print __file__

應該管用。

__file__返回執行文件的路徑

看看__file__ 這將為您提供一個文件名,其中代碼實際上

另外,還有另一個選擇:

import __main__ as main
print(main.__file__)

這為您提供了正在運行的腳本的文件名(類似於argv所做的事情)。

當代碼由另一個腳本導入時,區別就發揮了作用。

萬一您想在同一目錄中找到其他文件的絕對路徑,而不僅是您當前正在運行的文件,可以使用以下通用方法:

import sys,os

pathname = os.path.dirname(sys.argv[0])
fullpath = os.path.abspath(pathname)

for root, dirs, files in os.walk(fullpath):
    for name in files:
        name = str(name)
        name = os.path.realpath(os.path.join(root,name))
        print name

正如其他人所提到的,您可以利用__file__屬性。 您可以使用__file__屬性返回與當前加載的Python模塊相關的幾個不同路徑(從另一個StackOverflow答案復制):

在Python中加載模塊后, 文件將設置為其名稱。 然后,可以將其與其他功能一起使用,以查找文件所在的目錄。

# The parent directory of the directory where program resides.
print os.path.join(os.path.dirname(__file__), '..')

# The canonicalised (?) directory where the program resides.
print os.path.dirname(os.path.realpath(__file__))

# The absolute path of the directory where the program resides.
print os.path.abspath(os.path.dirname(__file__))

請記住要警惕要加載的模塊來自何處。 它可能會影響__file__屬性的內容(從Python 3 Data Model文檔復制):

__file__是從中加載模塊的文件的路徑名(如果它是從文件加載的)。 某些類型的模塊 (例如靜態鏈接到解釋器的C模塊) 可能缺少 __file__屬性。 對於從共享庫動態加載的擴展模塊,它是共享庫文件的路徑名。

嘗試使用__file__ 只要模塊是從文件運行的,即不是在編輯器中的代碼, __file__就是模塊的絕對路徑!

print __file__

或用於命令行。

def get_my_name():
    if __name__ == '__main__':
        return os.path.abspath(os.path.join(os.curdir, __file__))
    else:
        return __file__.replace('.pyc', '.py')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM