[英]Python: How do i get the name of the current archive?
有什么方法可以在Python中獲取當前的存檔名稱嗎?
就像是
EggArchive.egg
解放
---SomePythonFile.py
從SomePython.py,總有沒有獲取.egg名稱?
變量__file__
包含當前python文件的路徑。 因此,如果您有一個結構:
.
`- your.egg
`-your_module.py
在your_module.py
您有一個函數:
def func():
print(__file__)
代碼:
import sys
sys.path.append('/path/to/your.egg')
from your_module import func
func()
將打印出:
/path/to/your.egg/your_module.py
因此,基本上可以操縱__file__
,如果你知道你比較模塊內部變量egg
文件並獲得完整路徑egg
。
要在egg文件中的腳本中獲取egg的相對路徑,您必須執行以下操作:
def rel_to_egg(f):
my_dir = os.path.dirname(os.path.abspath(f))
current = my_dir
while not current.endswith('.egg'):
current = os.path.dirname(current)
return os.path.relpath(current, my_dir)
現在讓我們說__file__ == '/test/my.egg/some/dir/my_script.py'
:
>>> print(rel_to_egg(__file__))
'../..'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.