I have a shared python library that I use in multiple projects, so the structure looks like this:
Project1
main.py <--- (One of the projects that uses the library)
...
sharedlib
__init__.py
ps_lib.py
another.py
Now in each project's main.py I use the following hack to make it work:
import os
import sys
sys.path.insert(0, os.path.abspath('..'))
import sharedlib.ps_lib
...
Is there a way to do it without using this hack? Or is there a better way to organize the projects structure?
I think the best way would be to make
sharedlib
a real package. That means changing the structure a bit:And using something like this in the
setup.py
(taken partially from Python-packaging "Minimal Structure"):Then install it with
python setup.py develop
orpip install -e .
when in the root folder of thesharedlib
package.That way (using the
develop
or-e
option) changes to the contents ofsharedlib/sharedlib/*
files will be visible without re-installing thesharedlib
package - although you may need to restart the interpreter if you're working in an interactive interpreter. That's because the interpreter caches already imported packages.From the
setuptools
documentation:(emphasis mine)
The most important thing is that you can
import sharedlib
everywhere now - no need to insert thesharedlib
package in thePATH
orPYTHONPATH
anymore because Python (or at least the Python where you installed it) now treatssharedlib
like any other installed package.The way we do it is to use bash entry-scripts for the python scripts. Our directory structure would look similar to the following:
Our lib folder then contains all of our sub-projects
and then when we want to execute a python script, we'll execute it via a bash script within the bin directory
and if we cat one of our entry scripts
A great way to organize projects is described at this post In my opinion if is a shared lib you must consider using it as a real lib (included in the virtualenv) or add an folder "lib" to each project.