In Python script, how do I set PYTHONPATH?

PythonLinuxUnixEnvironment Variables

Python Problem Overview


I know how to set it in my /etc/profile and in my environment variables.

But what if I want to set it during a script? Is it import os, sys? How do I do it?

Python Solutions


Solution 1 - Python

You don't set PYTHONPATH, you add entries to sys.path. It's a list of directories that should be searched for Python packages, so you can just append your directories to that list.

sys.path.append('/path/to/whatever')

In fact, sys.path is initialized by splitting the value of PYTHONPATH on the path separator character (: on Linux-like systems, ; on Windows).

You can also add directories using site.addsitedir, and that method will also take into account .pth files existing within the directories you pass. (That would not be the case with directories you specify in PYTHONPATH.)

Solution 2 - Python

You can get and set environment variables via os.environ:

import os
user_home = os.environ["HOME"]

os.environ["PYTHONPATH"] = "..."

But since your interpreter is already running, this will have no effect. You're better off using

import sys
sys.path.append("...")

which is the array that your PYTHONPATH will be transformed into on interpreter startup.

Solution 3 - Python

If you put sys.path.append('dir/to/path') without check it is already added, you could generate a long list in sys.path. For that, I recommend this:

import sys
import os # if you want this directory

try:
    sys.path.index('/dir/path') # Or os.getcwd() for this directory
except ValueError:
    sys.path.append('/dir/path') # Or os.getcwd() for this directory

Solution 4 - Python

PYTHONPATH ends up in sys.path, which you can modify at runtime.

import sys
sys.path += ["whatever"]

Solution 5 - Python

you can set PYTHONPATH, by os.environ['PATHPYTHON']=/some/path, then you need to call os.system('python') to restart the python shell to make the newly added path effective.

Solution 6 - Python

I linux this works too:

import sys
sys.path.extend(["/path/to/dotpy/file/"])

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTIMEXView Question on Stackoverflow
Solution 1 - PythonDavid ZView Answer on Stackoverflow
Solution 2 - PythonmikuView Answer on Stackoverflow
Solution 3 - PythonFrancisco Manuel Garca BotellaView Answer on Stackoverflow
Solution 4 - PythonunbeliView Answer on Stackoverflow
Solution 5 - Pythontesla1060View Answer on Stackoverflow
Solution 6 - PythonlashgarView Answer on Stackoverflow