Reputation: 4662
I need to check one or another environment variable.
With casual variables - I can use:
if var1:
print('Var1 found')
elif var2:
print('Var2 found')
else:
print('Neither Var1 nor Var2 not found')
How can I do same for environment variables?
I can't use if/else
, because of if variable not found - os.environ
will raize KeyError
:
File "C:\Python27\lib\os.py", line 425, in __getitem__
return self.data[key.upper()]
KeyError: 'BAMBOO_WORKING_DIRECTORY'
If I'll do two try/except
, like:
try:
r = os.environ['Var1']
except KeyError as error:
print('Var1 not found')
try:
r = os.environ['Var2']
except KeyError as error:
print('Var2 not found')
So, it will check both of them. But I need Var1
or Var2
.
Add if/else
after first try/except, to check if r:
an call second try/except
if not? Will looks disgusting...
Upvotes: 1
Views: 279
Reputation: 19050
The exact equivalent of your if/elif
for known variables (but for environment variables) would be:
from os import environ
if environ.get("VAR1"):
print('VAR1 found')
elif environ.get("VAR2"):
print('VAR2 found')
else:
print('Neither VAR1 nor VAR2 not found')
Since os.environ
is a dict
and dict.get
has a signature of dict.get(key, [default])
where default
defaults to None
you can take advantage of this and get None
back for key(s) that don't exist (which evaluate False
ly).
Upvotes: 1
Reputation: 77073
os.environ
is a dict, so you can use the .get
call on it with default value.
If you use the two .get calls in conjunction, then this will get you the first variable, if it is present (because of python short circuiting), else it will get you the second one.
So essentially, the code is simplified to:
r = os.environ.get('Var1', "") or os.environ.get('Var2', "")
In this case, there is no need of a try - except block.
Chain this slightly longer, and you can get the expression which will give the default value as well:
>>> r = os.environ.get('Var1', "") or os.environ.get('Var2', "") or (
"Neither Var1 nor Var2 not found")
Upvotes: 4
Reputation: 1639
You can nest your try
statements
try:
r = os.environ['Var1']
try:
r = os.environ['Var2']
except KeyError as error:
print('Var2 not found')
except KeyError as error:
print('Var1 not found')
Upvotes: 0
Reputation: 369444
How about using a for
loop?
for varname in ['Var1', 'Var2']:
try:
r = os.environ['Var1']
break
except KeyError as error:
print('{} not found'.format(varname))
Upvotes: 1