In Python script, how do I set PYTHONPATH?

166,439

Solution 1

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

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

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

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

import sys
sys.path += ["whatever"]
Share:
166,439
TIMEX
Author by

TIMEX

Updated on May 15, 2020

Comments

  • TIMEX
    TIMEX about 4 years

    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?

  • Dror
    Dror over 9 years
    Is there a reason to prefer this answer over the one from @DavidZ ?
  • wecsam
    wecsam almost 7 years
    It has been many years since this answer was posted, but I still want to add that if you want to make sure that Python checks the new directory before all of the others when importing, you should put the new directory first in the list, as in sys.path.insert(0, '/path/to/whatever').
  • PartialOrder
    PartialOrder almost 7 years
    Nice. Very Pythonic.
  • Schütze
    Schütze over 5 years
    How can I empty the PythonPath? I don't want to append. I want to empty it and put what I only want inside. Is there a way to do this?
  • tripleee
    tripleee over 5 years
    If nothing else, it's less verbose.
  • tripleee
    tripleee over 5 years
    os.system() doesn't "restart the python shell", it starts a new interactive Python instance. When you return from that, you're back in the calling script.
  • Thayz
    Thayz over 5 years
    Did you try re-initialising it by calling sys.path.__init__()? This should empty python path. Hope this helps.
  • user7610
    user7610 about 4 years
    @francisco-manuel-garca-botella Answering old questions is very welcome on this site! Nothing to be sorry for.
  • markgalassi
    markgalassi almost 4 years
    I disagree that this is pythonic, and I would suggest that it is not a good programming approach. Excception handling is very expensive when the exception happens, so you don't want to use it to replace an "if" statement where it's quite possible that you will use the else. A simple if 'mypath' in sys.path ... else ... would be my advice.
  • rayryeng
    rayryeng over 3 years
    Using extend with the path as a single element in a list is no different than using append with the actual path itself. This answer does not provide any further usefulness than the current accepted answer.
  • Breno
    Breno about 2 years
    Is it "ok" to run sys.path.insert(0, os.getcwd())?