Search code examples
pythonpython-import

Python: Best way to add to sys.path relative to the current running script


I have a directory full of scripts (let's say project/bin). I also have a library located in project/lib and want the scripts to automatically load it. This is what I normally use at the top of each script:

#!/usr/bin/python
from os.path import dirname, realpath, sep, pardir
import sys
sys.path.append(dirname(realpath(__file__)) + sep + pardir + sep + "lib")

# ... now the real code
import mylib

This is kind of cumbersome, ugly, and has to be pasted at the beginning of every file. Is there a better way to do this?

Really what I'm hoping for is something as smooth as this:

#!/usr/bin/python
import sys.path
from os.path import pardir, sep
sys.path.append_relative(pardir + sep + "lib")

import mylib

Or even better, something that wouldn't break when my editor (or someone else who has commit access) decides to reorder the imports as part of its clean-up process:

#!/usr/bin/python --relpath_append ../lib
import mylib

That wouldn't port directly to non-posix platforms, but it would keep things clean.


Solution

  • If you don't want to edit each file

    • Install you library like a normal python libray
      or
    • Set 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