Python 检查环境变量是否存在的好做法是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40697845/
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
What is a good practice to check if an environmental variable exists or not?
提问by Kshitij Saraogi
I want to check my environment for the existence of a variable, say "FOO"
, in Python. For this purpose, I am using the os
standard library. After reading the library's documentation, I have figured out 2 ways to achieve my goal:
我想检查我的环境中是否存在变量,例如"FOO"
,在 Python 中。为此,我使用了os
标准库。阅读图书馆的文档后,我想出了两种方法来实现我的目标:
Method 1:
方法一:
if "FOO" in os.environ:
pass
Method 2:
方法二:
if os.getenv("FOO") is not None:
pass
I would like to know which method, if either, is a good/preferred conditional and why.
我想知道哪种方法是好的/首选条件以及为什么。
回答by Dimitris Fasarakis Hilliard
Use the first; it directly tries to check if something is defined in environ
. Though the second form works equally well, it's lacking semantically since you get a value back if it exists and onlyuse it for a comparison.
使用第一个;它直接尝试检查是否在environ
. 虽然第二种形式同样有效,但它在语义上缺乏,因为如果它存在,你会得到一个值,并且只将它用于比较。
You're trying to see if something is present inenviron
, why would you getjust to compare it and then toss it away?
你想看看是否有存在的environ
,为什么你会得到只是为了进行比较,然后折腾它扔掉?
That's exactly what getenv
does:
这正是getenv
它的作用:
Get an environment variable, return
None
if it doesn't exist. The optional second argument can specify an alternate default.
获取环境变量,
None
如果不存在则返回。可选的第二个参数可以指定备用默认值。
(this also means your check could just be if getenv("FOO")
)
(这也意味着您的支票可能只是if getenv("FOO")
)
you don't want to get it, you want to check for it's existence.
你不想得到它,你想检查它的存在。
Either way, getenv
is just a wrapper around environ.get
but you don't see people checking for membership in mappings with:
无论哪种方式,getenv
都只是一个包装器,environ.get
但您不会看到人们使用以下方式检查映射中的成员资格:
from os import environ
if environ.get('Foo') is not None:
To summarize, use:
总而言之,请使用:
if "FOO" in os.environ:
pass
if you justwant to check for existence, while, use getenv("FOO")
if you actually want to do something with the value you might get.
如果你只是想检查是否存在,而getenv("FOO")
如果你真的想用你可能得到的值做一些事情,请使用。
回答by hugovdberg
There is a case for either solution, depending on what you want to do conditional on the existence of the environment variable.
两种解决方案都有一个案例,这取决于您希望以环境变量的存在为条件做什么。
Case 1
情况1
When you want to take different actions purely based on the existence of the environment variable, without caring for its value, the first solution is the best practice. It succinctly describes what you test for: is 'FOO' in the list of environment variables.
当你想纯粹根据环境变量的存在来采取不同的行动,而不关心它的价值时,第一种解决方案是最佳实践。它简洁地描述了您测试的内容:环境变量列表中的“FOO”。
if 'KITTEN_ALLERGY' in os.environ:
buy_puppy()
else:
buy_kitten()
Case 2
案例二
When you want to set a default value if the value is not defined in the environment variables the second solution is actually useful, though not in the form you wrote it:
如果您想设置一个默认值,如果该值未在环境变量中定义,则第二个解决方案实际上很有用,尽管不是您编写的形式:
server = os.getenv('MY_CAT_STREAMS', 'youtube.com')
or perhaps
也许
server = os.environ.get('MY_CAT_STREAMS', 'youtube.com')
Note that if you have several options for your application you might want to look into ChainMap
, which allows to merge multiple dicts based on keys. There is an example of this in the ChainMap
documentation:
请注意,如果您的应用程序有多个选项,您可能需要查看ChainMap
,它允许基于键合并多个字典。ChainMap
文档中有一个例子:
[...]
combined = ChainMap(command_line_args, os.environ, defaults)
回答by Levon
To be on the safe side use
为了安全使用
os.getenv('FOO') or 'bar'
A corner case with the above answers is when the environment variable is set but is empty
上述答案的一个极端情况是环境变量已设置但为空
For this special case you get
对于这种特殊情况,您会得到
print(os.getenv('FOO', 'bar'))
# prints new line - though you expected `bar`
or
或者
if "FOO" in os.environ:
print("FOO is here")
# prints FOO is here - however its not
To avoid this just use or
为避免这种情况,只需使用 or
os.getenv('FOO') or 'bar'
Then you get
然后你得到
print(os.getenv('FOO') or 'bar')
# bar
When do we have empty environment variables?
我们什么时候有空的环境变量?
You forgot to set the value in the .env
file
您忘记在.env
文件中设置值
# .env
FOO=
or exported as
或导出为
$ export FOO=
or forgot to set it in settings.py
或者忘记设置 settings.py
# settings.py
os.environ['FOO'] = ''
Update:if in doubt, check out these one-liners
更新:如果有疑问,请查看这些单线
>>> import os; os.environ['FOO'] = ''; print(os.getenv('FOO', 'bar'))
$ FOO= python -c "import os; print(os.getenv('FOO', 'bar'))"
回答by vhamon
In case you want to check if multiple env variables are not set, you can do the following:
如果要检查是否未设置多个 env 变量,可以执行以下操作:
import os
MANDATORY_ENV_VARS = ["FOO", "BAR"]
for var in MANDATORY_ENV_VARS:
if var not in os.environ:
raise EnvironmentError("Failed because {} is not set.".format(var))
回答by sveer
My comment might not be relevant to the tags given. However, I was lead to this page from my search. I was looking for similar check in R and I came up the following with the help of @hugovdbeg post. I hope it would be helpful for someone who is looking for similar solution in R
我的评论可能与给定的标签无关。但是,我从搜索中转到了此页面。我在 R 中寻找类似的检查,我在@hugovdbeg 帖子的帮助下提出了以下内容。我希望这对在 R 中寻找类似解决方案的人有所帮助
'USERNAME' %in% names(Sys.getenv())