The Python Oracle

Permanently add a directory to PYTHONPATH?

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Book End

--

Chapters
00:00 Permanently Add A Directory To Pythonpath?
00:22 Answer 1 Score 605
00:36 Accepted Answer Score 158
01:18 Answer 3 Score 114
01:52 Answer 4 Score 32
02:16 Thank you

--

Full question
https://stackoverflow.com/questions/3402...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #windows #pythonpath

#avk47



ANSWER 1

Score 605


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

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



ACCEPTED ANSWER

Score 158


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 you're 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.

superuser.com 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 it's not really a programming question per se.




ANSWER 3

Score 114


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 doesn't 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 doesn't exist).

For example:

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

# create if it doesn't exist
mkdir -p "$SITEDIR"

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



ANSWER 4

Score 32


In case anyone is still confused - if you are on a Mac, do the following:

  1. Open up Terminal
  2. Type open .bash_profile
  3. In the text file that pops up, add this line at the end: export PYTHONPATH=$PYTHONPATH:foo/bar
  4. Save the file, restart the Terminal, and you're done