Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
147 views
in Technique[技术] by (71.8m points)

python - 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.

question from:https://stackoverflow.com/questions/18486469/how-to-print-contents-of-pythonpath

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...