繁体   English   中英

Python:如何获取当前档案的名称?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM