简体   繁体   中英

Python: How do i get the name of the current archive?

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__))
'../..'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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