【发布时间】:2013-08-14 01:29:51
【问题描述】:
有没有办法在 Python 中获取当前存档名称?
类似
EggArchive.egg
库
---SomePythonFile.py
是否从 SomePython.py 中获取 .egg 名称?
【问题讨论】:
-
您的意思是,您想发现发行版名称,还是完整的 egg 文件名?你有发行版名称吗?
有没有办法在 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__))
'../..'
【讨论】:
library.egg,它本身有一个模块my_mod 2.在其他地方你有一个脚本my_script.py 3.在my_script.py你import my_mod来自library.egg。 4.你想知道library.egg相对于my_script.py在哪里?
my_script.py 在鸡蛋内时如何运行?