I have a python app, that I’m developing. There is a need to use another library, that resides in different directory.
The file layout looks like this:
dir X has two project dirs:
- current-project
- xLibrary
I’d like to use xLibrary in currentProject. I’ve been trying writting code as if all the sources resided in the same directory and calling my projects main script with:
PYTHONPATH=.:../xLibrary ./current-project.py
but this does not work. I’d like to use its code base without installing the library globaly or copying it to my project’s directory. Is it possible? Or if not, how should I deal with this problem.
It’s generally a good programming practice to isolate packages into actual packages and treat them as such. If you’re sure you’d like to continue with that approach though you can modify the search path from within python via:
To avoid embedding absolute paths, you can use
os.path.abspath(__file__)to obtain the absolute path to the currently executing .py file and follow up with a fewos.path.dirname()calls to construct the proper relative path for inclusion tosys.pathA slightly altered approach that would allow you to get the best of both worlds would be to add an
__init__.pyfile toxLibrary‘s directory then add the path containing ‘xLibrary’ tosys.pathinstead. Subsequent Python code could then import everything “properly” viafrom xLibrary import my_modulerather than justimport my_modulewhich could be confusing to people accustomed to the standard package directory layout.