문제

Is there any way to get the current archive name in Python?

Something like

EggArchive.egg

Lib
---SomePythonFile.py

From SomePython.py, is there anyway to fetch the .egg name?

도움이 되었습니까?

해결책

The variable __file__ contains the path to the current python file. So If you have a structure:

.
`- your.egg
   `-your_module.py

And in your_module.py you have a function:

def func():
    print(__file__)

The the code:

import sys
sys.path.append('/path/to/your.egg')
from your_module import func
func()

Will print out:

/path/to/your.egg/your_module.py

So basically you can manipulate the __file__ variable if you know where relatively your module is inside the egg file and get the full path to the egg.

To get the relative path to the egg in the script that's in the egg file you'll have to do:

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)

Now let's say __file__ == '/test/my.egg/some/dir/my_script.py':

>>> print(rel_to_egg(__file__))
'../..'
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top