user966588
user966588

Reputation:

how to print contents of PYTHONPATH

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.

Upvotes: 49

Views: 123869

Answers (2)

Jon Clements
Jon Clements

Reputation: 142176

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)

Upvotes: 9

Maxime Lorant
Maxime Lorant

Reputation: 36161

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

Upvotes: 71

Related Questions