如何访问环境变量值
问题描述
我设置了一个我想在我的 Python 应用程序中访问的环境变量.我如何获得它的价值?
I set an environment variable that I want to access in my Python application. How do I get its value?
解决方案
通过os.environ
import os
print(os.environ['HOME'])
或者您可以使用以下命令查看所有环境变量的列表:
Or you can see a list of all the environment variables using:
os.environ
有时您可能需要查看完整列表!
As sometimes you might need to see a complete list!
# using get will return `None` if a key is not present rather than raise a `KeyError`
print(os.environ.get('KEY_THAT_MIGHT_EXIST'))
# os.getenv is equivalent, and can also give a default value instead of `None`
print(os.getenv('KEY_THAT_MIGHT_EXIST', default_value))
Windows 上的 Python 默认安装 位置是 C:Python
.如果您想在运行 python 时找出答案,可以这样做:
The Python default installation location on Windows is C:Python
. If you want to find out while running python you can do:
import sys
print(sys.prefix)
相关文章