How to access files inside a Python egg file?

Viewed 39379

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?

6 Answers

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

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

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

Related