Python Paths

Python searches for the modules and packages in the predefined directories on the operating system. It creates a list of those places and keeps them in a list.

import sys
sys.path

for i in sys.path:
    print (i)

Output

/Users/naren/Documents/courses/Programming_languages_for_bioinformatics/python_paths
/Users/naren/opt/anaconda3/lib/python37.zip
/Users/naren/opt/anaconda3/lib/python3.7
/Users/naren/opt/anaconda3/lib/python3.7/lib-dynload

/Users/naren/opt/anaconda3/lib/python3.7/site-packages
/Users/naren/opt/anaconda3/lib/python3.7/site-packages/aeosa
/Users/naren/opt/anaconda3/lib/python3.7/site-packages/IPython/extensions
/Users/naren/.ipython

sys.path is simply a list which could be modified in the usuall way a list is modified (e.g. sys.path.append(), sys.path.extend())


PYTHONPATH

PYTHONPATH is an environment variable that could be set before runing python script. PYTHONPATH contains a semicolon separated list of directories that will be searched for modules when import is issued. The list get appended to the sys.path list


Setting PYTHONPATH

# on mac and linux
export PYTHONPATH='/some/extra/path'

# on windows
set PYTHONPATH='/some/extra/path'

The directories defined by PYTHONPATH will be appended to sys.path list


Checking PYTHONPATH

os.environ is a dictionary that stores the environmental variables as a key-value pairs.

import os

# Will report an error if PYTHONPATH is not set 
os.environ['PYTHONPATH']

# printing all the directories set by pythonpath
for i in os.environ['PYTHONPATH'].split(os.pathsep):
    print (i)


# listing all environmental variables

for k,v in os.environ.items():
    print ( "%20s is set to %s" % (k,v) )
    

PYTHONHOME

PYTHONHOME is a evrironmental variable that is related to PYTHONPATH. If PYTHONHOME is set it defines where the standard python libraries are sitting and supplements PYTHONPATH.


SITE MODULE

The site module may be used to modify the paths to sys.path

import site
import sys

site.addsitedir('/my/new/dir')
sys.path
Next