how to print contents of PYTHONPATH

Question:

I have set path using

sys.path.insert(1, mypath)

Then, I tried to print contents of PYTHONPATH variable using os.environ as below

print(os.environ['PYTHONPATH'])

but I am getting error as

    raise KeyError(key)
KeyError: 'PYTHONPATH'

How can we print contents of PYTHONPATH variable.

Asked By: user966588

||

Answers:

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)
Answered By: Jon Clements

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

Answered By: Maxime Lorant
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.