I'm looking for a way to emulate symlinks for Python imports. I'd like to be able to unzip the following folder structure in-place without duplicating files:
root
├─ python_lib
│ └─ my_utils
│ ├─ __init__.py
│ └─ etc.py
├─ app1
├─ app2
└─ app3
├─ lib
│ ├─ __init__.py
│ └─ my_utils.py
└─ run.py
app3/run.py
contains this:
from lib.my_utils import etc
etc.pancakes()
I'd like the code to use the etc
located in python_lib/my_utils/
. Is there anything I can put in app3/lib/my_utils.py
so that Python >= 3.1 will transparently import the python_lib/my_utils/
folder (using relative paths and ..
), and subpackages will also work?
The way that url_for() works is instead of redirecting based on the string representation of a route, you provide the function name of the route you want to redirect to. So if we update the code to the snippet here, we get the same result but using url_for() instead of redirect().
append() Function. This is the easiest way to import a Python module by adding the module path to the path variable. The path variable contains the directories Python interpreter looks in for finding modules that were imported in the source files.
You will have to execute something before app3/run.py
reaches the import statement.
import python_lib
import sys
sys.modules['lib'] = python_lib
# ...
from lib import etc
print etc.__file__
print dir(etc)
You should add this path into sys.path
. For example:
lib_path = os.path.abspath( os.path.split( os.getcwd()+"/"+sys.argv[0] )[0]+"/../_lib/my_utils/" )
sys.path.append(lib_path)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With