In a Python script, how to install PYTHONPATH?

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

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

+75
python linux unix environment-variables
Jun 24 '10 at 8:25
source share
4 answers

You do not set PYTHONPATH , you add entries to sys.path . This is a list of directories to look for for Python packages, so you can simply add your directories to this list.

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

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

You can also add directories using site.addsitedir , and this method will also take into account the .pth files that exist in the directories you pass in (This does not apply to directories specified in PYTHONPATH .)

+124
Jun 24 '10 at 8:28
source share

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. Better with

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

which is an array, your PYTHONPATH will be converted to the beginning of the interpreter.

+25
Jun 24 '10 at 8:29
source share

Sorry for the second question, but I think it might help someone:

If you put sys.path.append('dir/to/path') without checking, it is already added, you can create a long list in sys.path . For this, 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 

Sorry if I annoyed someone who reopened the question.

+9
May 12 '16 at 11:33
source share

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

 import sys sys.path += ["whatever"] 
+4
Jun 24 '10 at 8:29
source share



All Articles