168

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?

5 Answers 5

277

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.

import sys

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

Sign up to request clarification or add additional context in comments.

3 Comments

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').
Is it "ok" to run sys.path.insert(0, os.getcwd())?
@Breno: The danger of inserting the . (CWD) into the import path is that if you run your program in an untrusted directory, it can import things from there and execute them.
59

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.

Comments

31

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

5 Comments

Nice. Very Pythonic.
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?
Did you try re-initialising it by calling sys.path.__init__()? This should empty python path. Hope this helps.
@francisco-manuel-garca-botella Answering old questions is very welcome on this site! Nothing to be sorry for.
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.
9

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

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

2 Comments

Is there a reason to prefer this answer over the one from @DavidZ ?
If nothing else, it's less verbose.
-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.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.