[英]Elegant way to check if any of long list of variables is not None, and return the one that isn't?
I have 8 variables being loaded in from environment variables. 我有8个变量是从环境变量中加载的。 If any of these are none, I'd like to bail and
sys.exit
- but I'd also like to alert the user to which variable was missing. 如果这些都不是,我想保释和
sys.exit
但我也想提醒用户缺少哪个变量。
There are a few ways of doing this. 有几种方法可以做到这一点。 Assume the
a = os.environ.get('a')
code is prewritten, through h
假设
a = os.environ.get('a')
代码是通过h
预先编写的
The most verbose way that works is: 最详细的工作方式是:
if a is None:
print("A is required")
sys.exit(1)
if b is None:
print("B is required")
sys.exit(1)
if c is None:
print("C is required")
sys.exit(1)
...
so on until the check for h
The cleanest way is: 最干净的方法是:
if not any([a,b,c,d,e,f,g,h]):
print("? is required")
sys.exit(1)
or even: 甚至:
if None in [a,b,c,d,e,f,g,h]:
print("? is required")
sys.exit(1)
Is it possible to actually get the variable name from one of the more python checks (the latter two) and print it out to the user? 是否有可能实际上从更多的python检查之一(后两个)中获取变量名并将其输出给用户?
I could get the index of the variable by doing [a,b,c,d,e,f,g,h].index(None)
but I'm not sure how to go from the index to the variable name. 我可以做得到变量的指数
[a,b,c,d,e,f,g,h].index(None)
,但我不知道如何从索引到的变量名称。
Perform the check when you're retrieving the environment variables in the first place: 首先检索环境变量时执行检查:
def needenv(name):
val = os.environ.get(name)
if val is None:
sys.exit('{} is required.'.format(name))
return val
a = needenv('a')
b = needenv('b')
...
You can loop through the env's: 您可以遍历环境:
required_vars = ['a', 'b']
for name in required_vars:
if not name in os.environ:
sys.exit('{} is required.'.format(name))
I would read them into a dictionary, you can then use all() to check everything is fine and can also report what is missing (it might be more than one of them). 我会将它们读入字典,然后可以使用all()检查一切是否正常,还可以报告缺少的内容(可能不止一个)。
env_dict[‘a’] = os.environ.get(‘a’) # etc.
if not all(v for k,v in env_dict.items()):
missing = [k for k,v in env_dict.items() if v is None]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.