158

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?

TIMEX
  • 259,804
  • 351
  • 777
  • 1,080

6 Answers6

259

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

AJM
  • 1,317
  • 2
  • 15
  • 30
David Z
  • 128,184
  • 27
  • 255
  • 279
  • 28
    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')`. – wecsam Jun 15 '17 at 16:22
  • 4
    Is it "ok" to run `sys.path.insert(0, os.getcwd())`? – Breno Apr 17 '22 at 15:37
53

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.

declension
  • 4,110
  • 22
  • 25
miku
  • 181,842
  • 47
  • 306
  • 310
28

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
user7610
  • 25,267
  • 15
  • 124
  • 150
  • 2
    Nice. Very Pythonic. – PartialOrder Jul 17 '17 at 19:00
  • 1
    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? – Schütze Dec 19 '18 at 10:13
  • Did you try re-initialising it by calling sys.path.__init__()? This should empty python path. Hope this helps. – Thayz Jan 03 '19 at 12:17
  • @francisco-manuel-garca-botella Answering old questions is very welcome on this site! Nothing to be sorry for. – user7610 May 14 '20 at 10:12
  • 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. – markgalassi Jul 15 '20 at 23:02
7

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

import sys
sys.path += ["whatever"]
unbeli
  • 29,501
  • 5
  • 55
  • 57
-4

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.

tesla1060
  • 2,621
  • 6
  • 31
  • 43
  • 3
    `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. – tripleee Dec 19 '18 at 11:26
-4

I linux this works too:

import sys
sys.path.extend(["/path/to/dotpy/file/"])
lashgar
  • 5,184
  • 3
  • 37
  • 45
  • 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. – rayryeng Oct 27 '20 at 05:10