James Harr James Harr - 2 years ago 105
Python Question

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

I have a directory full of scripts (let's say

). I also have a library located in
and want the scripts to automatically load it. This is what I normally use at the top of each script:

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:

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 Source

If you don't want to edit each file

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download