How to access files inside a Python egg file?
Asked Answered
W

6

24

This might be a weird requirement but it's what I've run into. I Googled but yield nothing.

I'm coding an application who's using a lot of constant attributes / values recorded in an XML file (they'll not change so a static file), things work fine until I generated an egg file for it.

When the logic reaches the XML accessing part, I got one complaint like this: /home/Workspace/my_proj/dist/mps-1.2.0_M2-py2.6.egg/mps/par/client/syntax/syntax.xml

Actually I've bundled the XML file in the path above but seems Python doesn't know how to access it.

The code to access the XML is as...

file_handler = open(path_to_the_file)
lines = file_handler.read().splitlines()

Any idea?

Waly answered 7/9, 2010 at 2:19 Comment(1)
If you've still got this problem, check my answer here as well: stackoverflow.com/questions/12735852/…Martinelli
C
22

egg files are zipfiles, so you must access "stuff" inside them with the zipfile module of the Python standard libraries, not with the built-in open function!

Caernarvonshire answered 7/9, 2010 at 2:23 Comment(2)
I read the doc for zipfile module and surely it could do the job. Thank you ~Waly
you can even install them using, sudo easy_install your_eggfileWeidner
K
12

If you want to access the contents inside the .egg file you can simply rename it and change extension from .egg to .zip and than unzip it. Which will create a folder and the contents will be same as they were when it was a .egg file

for example brewer2mpl-1.4.1-py3.6.egg
After Renaming brewer2mpl-1.4.1-py3.6.zip

Now if we open it, it'll get easily unzipped and the content will be put in a folder with same name in the same directory. (tested on macOS Sierra)

Kelvin answered 25/3, 2017 at 5:6 Comment(0)
E
2

The less command on *nix systems can peek inside zip files. Therefore less some.egg will list the contents of a .egg file too.

Effable answered 8/1, 2021 at 9:48 Comment(0)
R
1

Just run unzip file.egg


You can install unzip on Debian/Ubuntu with

sudo apt install unzip

or on macOS by installing Homebrew then

brew install unzip
Rance answered 23/2, 2018 at 11:45 Comment(0)
C
0

Access file from inside egg file

Yes, It is possible to read the files from inside egg file.

Egg file: mps-1.2.0_M2-py2.6.egg structure for module level example:

mps-1.2.0_M2-py2.6.egg image

In driverfile.py:

import xml.etree.ElementTree
import mps.par.client as syntaxpath
import os
path = os.path.dirname(syntaxpath.__file__)
element = xml.etree.ElementTree.parse(path+'\\syntax\\syntax.xml').getroot()
print(element)

Read xml file from inside an eggfile:

PYTHONPATH=mps-1.2.0_M2-py2.6.egg python driverfile.py

Clasp answered 3/5, 2018 at 9:40 Comment(0)
S
0

i think by default eggs packing file under python won't add your xml inside to the pack

Sidedress answered 26/4, 2019 at 3:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.