python – Permanently add a directory to PYTHONPATH?

python – Permanently add a directory to PYTHONPATH?

If youre using bash (on a Mac or GNU/Linux distro), add this to your ~/.bashrc

export PYTHONPATH=${PYTHONPATH}:/my/other/path

You need to add your new directory to the environment variable PYTHONPATH, separated by a colon from previous contents thereof. In any form of Unix, you can do that in a startup script appropriate to whatever shell youre using (.profile or whatever, depending on your favorite shell) with a command which, again, depends on the shell in question; in Windows, you can do it through the system GUI for the purpose. may be a better place to ask further, i.e. for more details if you need specifics about how to enrich an environment variable in your chosen platform and shell, since its not really a programming question per se.

python – Permanently add a directory to PYTHONPATH?

Instead of manipulating PYTHONPATH you can also create a path configuration file. First find out in which directory Python searches for this information:

python -m site --user-site

For some reason this doesnt seem to work in Python 2.7. There you can use:

python -c import site; site._script() --user-site

Then create a .pth file in that directory containing the path you want to add (create the directory if it doesnt exist).

For example:

# find directory
SITEDIR=$(python -m site --user-site)

# create if it doesnt exist
mkdir -p $SITEDIR

# create new .pth file with our path
echo $HOME/foo/bar > $SITEDIR/somelib.pth

Leave a Reply

Your email address will not be published. Required fields are marked *