I suggest not to rely on the raw PYTHONPATH because it can vary depending on the OS.
Instead of the PYTHONPATH value in the os.environ dict, use sys.path from the sys module. This is preferrrable, because it is platform independent:
import sys
print(sys.path)
The value of sys.path is initialized from the environment variable PYTHONPATH, plus an installation-dependent default (depending on your OS). For more info see
https://docs.python.org/2/library/sys.html#sys.path
https://docs.python.org/3/library/sys.html#sys.path
Answer from Maxime Lorant on Stack OverflowI suggest not to rely on the raw PYTHONPATH because it can vary depending on the OS.
Instead of the PYTHONPATH value in the os.environ dict, use sys.path from the sys module. This is preferrrable, because it is platform independent:
import sys
print(sys.path)
The value of sys.path is initialized from the environment variable PYTHONPATH, plus an installation-dependent default (depending on your OS). For more info see
https://docs.python.org/2/library/sys.html#sys.path
https://docs.python.org/3/library/sys.html#sys.path
If PYTHONPATH hasn't been set then that's expected, maybe default it to an empty string:
import os
print(os.environ.get('PYTHONPATH', ''))
You may also be after:
import sys
print(sys.path)
You would probably also want this:
import sys
print(sys.path)
Or as a one liner from the terminal:
python -c "import sys; print('\n'.join(sys.path))"
Caveat: If you have multiple versions of Python installed you should use a corresponding command python2 or python3.
sys.path might include items that aren't specifically in your PYTHONPATH environment variable. To query the variable directly, use:
import os
try:
user_paths = os.environ['PYTHONPATH'].split(os.pathsep)
except KeyError:
user_paths = []
How do I add PYTHONPATH inside a Python script?
Is PYTHONPATH required to import installed packages?
How do I set multiple directories in PYTHONPATH?
What is sys.path? And exactly, in which directory I can find it and what does it do?