Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

Is SYS path append good practice?

This is generally not good practice. It's generally not necessary, because the path to the script is already added to sys.

How do I add path to SYS path?

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.

How do you append a path in Python?

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

  • 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


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"))