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

James Harr picture James Harr · Dec 29, 2011 · Viewed 155.2k times · Source

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.

Answer

jterrace picture jterrace · Dec 29, 2011

This is what I use:

import os, sys
sys.path.append(os.path.join(os.path.dirname(__file__), "lib"))