Python 如何访问环境变量值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4906977/
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
How to access environment variable values?
提问by Amit Yadav
I set an environment variable that I want to access in my Python application. How do I get its value?
我设置了一个我想在我的 Python 应用程序中访问的环境变量。我如何获得它的价值?
采纳答案by Rod
Environment variables are accessed through os.environ
通过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))
Python default installationon Windows is C:\Python. If you want to find out while running python you can do:
Windows 上的Python 默认安装是C:\Python. 如果你想在运行 python 时找出答案,你可以这样做:
import sys
print(sys.prefix)
回答by andrei1089
You can access to the environment variables using
您可以使用访问环境变量
import os
print os.environ
Try to see the content of PYTHONPATH or PYTHONHOME environment variables, maybe this will be helpful for your second question. However you should clarify it.
尝试查看 PYTHONPATH 或 PYTHONHOME 环境变量的内容,也许这对您的第二个问题有所帮助。不过你应该澄清一下。
回答by Jim Brissom
As for the environment variables:
至于环境变量:
import os
print os.environ["HOME"]
I'm afraid you'd have to flesh out your second point a little bit more before a decent answer is possible.
恐怕你得再充实一下你的第二点,才能得到一个像样的答案。
回答by Scott C Wilson
The original question (first part) was "how to check environment variables in Python."
最初的问题(第一部分)是“如何在 Python 中检查环境变量”。
Here's how to check if $FOO is set:
以下是检查是否设置了 $FOO 的方法:
try:
os.environ["FOO"]
except KeyError:
print "Please set the environment variable FOO"
sys.exit(1)
回答by lgriffiths
To check if the key exists (returns Trueor False)
检查密钥是否存在(返回True或False)
'HOME' in os.environ
You can also use get()when printing the key; useful if you want to use a default.
也可以get()在打印密钥时使用;如果您想使用默认值,则很有用。
print(os.environ.get('HOME', '/home/username/'))
where /home/username/is the default
/home/username/默认在哪里
回答by Renjith Thankachan
If you are planning to use the code in a production web application code,
using any web framework like Django/Flask, use projects like envparse, using it you can read the value as your defined type.
如果您计划在生产 Web 应用程序代码中
使用该代码,使用任何 Web 框架(如 Django/Flask),使用envparse 之类的项目,使用它您可以将值读取为您定义的类型。
from envparse import env
# will read WHITE_LIST=hello,world,hi to white_list = ["hello", "world", "hi"]
white_list = env.list("WHITE_LIST", default=[])
# Perfect for reading boolean
DEBUG = env.bool("DEBUG", default=False)
NOTE: kennethreitz's autoenvis a recommended tool for making project specific environment variables, please note that those who are using autoenvplease keep the .envfile private (inaccessible to public)
注意:kennethreitz 的autoenv是一个推荐的用于制作项目特定环境变量的工具,请注意使用的人autoenv请将.env文件保密(公众无法访问)
回答by Azorian
import os
for a in os.environ:
print('Var: ', a, 'Value: ', os.getenv(a))
print("all done")
That will print all of the environment variables along with their values.
这将打印所有环境变量及其值。
回答by britodfbr
Actually it can be done this away:
实际上它可以做到这一点:
import os
for item, value in os.environ.items():
print('{}: {}'.format(item, value))
Or simply:
或者干脆:
for i, j in os.environ.items():
print(i, j)
For view the value in the parameter:
查看参数中的值:
print(os.environ['HOME'])
Or:
或者:
print(os.environ.get('HOME')
To set the value:
要设置值:
os.environ['HOME'] = '/new/value'
回答by Peter Konneker
There's also a number of great libraries. Envsfor example will allow you to parse objects out of your environment variables, which is rad. For example:
还有许多很棒的图书馆。例如,Envs将允许您从环境变量中解析对象,即 rad。例如:
from envs import env
env('SECRET_KEY') # 'your_secret_key_here'
env('SERVER_NAMES',var_type='list') #['your', 'list', 'here']
回答by Leonardo
For django see (https://github.com/joke2k/django-environ)
对于 django,请参阅(https://github.com/joke2k/django-environ)
$ pip install django-environ
import environ
env = environ.Env(
# set casting, default value
DEBUG=(bool, False)
)
# reading .env file
environ.Env.read_env()
# False if not in os.environ
DEBUG = env('DEBUG')
# Raises django's ImproperlyConfigured exception if SECRET_KEY not in os.environ
SECRET_KEY = env('SECRET_KEY')

