Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to include a python .egg library that is in a subdirectory (relative location)?

Tags:

python

egg

How do you import python .egg files that are stored in a relative location to the .py code?

For example,

My Application/
My Application/library1.egg
My Application/libs/library2.egg
My Application/test.py

How do you import and use library1 and library2 from within test.py, while leaving the .egg libraries in-place?

like image 469
Brian Jordan Avatar asked Jul 10 '09 08:07

Brian Jordan


People also ask

What is a .EGG Python?

An EGG file is a Zip-compressed package that stores a Python distribution. It contains all the source files for a Python install along with metadata about the distribution. EGG files are simply . ZIP files renamed with the . egg file extension.

How do I import a module from the outside directory?

Method 1: Using sys. The sys. path variable of the module sys contains the list of all directories in which python will search for a module to import. We can directly call this method to see the directories it contains. So for importing mod.py in main.py we will append the path of mod.py in sys.

How do I import an egg file?

egg files are simply renamed zip files. Open the egg with your zip program, or just rename the extension to . zip, and extract. great !


2 Answers

An .egg is just a .zip file that acts like a directory from which you can import stuff.

You can use the PYTHONPATH variable to add the .egg to your path, or append a directory to sys.path. Another option is to use a .pth file pointing to the eggs.

For more info see A Small Introduction to Python eggs, Python Eggs and All about eggs.

For example, if your library1.egg contains a package named foo, and you add library1.egg to PYTHONPATH, you can simply import foo

If you can't set PYTHONPATH, you can write:

import sys
sys.path.append("library1.egg")
import foo
like image 81
Eli Bendersky Avatar answered Sep 21 '22 18:09

Eli Bendersky


You can include each egg on the sys.path, or create a .pth file that mentions each egg.

If you have many eggs that you need in your system I'd recommend using something like buildout, that will make the setup easily replicatable. It will handle the eggs for you.

http://pypi.python.org/pypi/zc.buildout/

like image 41
Lennart Regebro Avatar answered Sep 20 '22 18:09

Lennart Regebro