如何打印 PYTHONPATH 的内容

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18486469/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 10:52:21  来源:igfitidea点击:

how to print contents of PYTHONPATH

python

提问by

I have set path using

我已经使用设置路径

sys.path.insert(1, mypath)

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

然后,我尝试使用 os.environ 打印 PYTHONPATH 变量的内容,如下所示

print(os.environ['PYTHONPATH'])

but I am getting error as

但我收到错误

    raise KeyError(key)
KeyError: 'PYTHONPATH'

How can we print contents of PYTHONPATH variable.

我们如何打印 PYTHONPATH 变量的内容。

采纳答案by Maxime Lorant

I suggest not to rely on the raw PYTHONPATH because it can vary depending on the OS.

我建议不要依赖原始 PYTHONPATH,因为它会因操作系统而异。

Instead of the PYTHONPATH value in the os.environdict, use sys.pathfrom the sysmodule. This is preferrrable, because it is platform independent:

相反,在该PYTHONPATH值的os.environ字典,使用sys.pathsys模块。这是可取的,因为它是独立于平台的:

import sys
print(sys.path)

The value of sys.pathis initialized from the environment variable PYTHONPATH, plus an installation-dependent default (depending on your OS). For more info see

的值sys.path从环境变量 PYTHONPATH 初始化,加上依赖于安装的默认值(取决于您的操作系统)。有关更多信息,请参阅

https://docs.python.org/2/library/sys.html#sys.path

https://docs.python.org/2/library/sys.html#sys.path

https://docs.python.org/3/library/sys.html#sys.path

https://docs.python.org/3/library/sys.html#sys.path

回答by Jon Clements

If PYTHONPATHhasn't been set then that's expected, maybe default it to an empty string:

如果PYTHONPATH尚未设置,则是预期的,可能将其默认为空字符串:

import os
print(os.environ.get('PYTHONPATH', ''))

You may also be after:

您可能还在追求:

import sys
print(sys.path)