This is generally not good practice. It's generally not necessary, because the path to the script is already added to sys.
APPENDING PATH- append() is a built-in function of sys module that can be used with path variable to add a specific path for interpreter to search. The following example shows how this can be done.
On each line of the file you put one directory name, so you can put a line in there with /path/to/the/ and it will add that directory to the path. You could also use the PYTHONPATH environment variable, which is like the system PATH variable but contains directories that will be added to sys.
This is what I use:
import os, sys
sys.path.append(os.path.join(os.path.dirname(__file__), "lib"))
I'm using:
import sys,os
sys.path.append(os.getcwd())
If you don't want to edit each file
PYTHONPATH
to your lib
or if you are willing to add a single line to each file, add a import statement at top e.g.
import import_my_lib
keep import_my_lib.py
in bin and import_my_lib
can correctly set the python path to whatever lib
you want
Create a wrapper module project/bin/lib
, which contains this:
import sys, os
sys.path.insert(0, os.path.join(
os.path.dirname(os.path.dirname(os.path.realpath(__file__))), 'lib'))
import mylib
del sys.path[0], sys, os
Then you can replace all the cruft at the top of your scripts with:
#!/usr/bin/python
from lib import mylib
Using python 3.4+
import sys
from pathlib import Path
# As PosixPath
sys.path.append(Path(__file__).parent / "lib")
# Or as str as explained in https://stackoverflow.com/a/32701221/11043825
sys.path.append(str(Path(__file__).parent / "lib"))
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