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...
The exact equivalent of your
if/elif
for known variables (but for environment variables) would be:Since
os.environ
is adict
anddict.get
has a signature ofdict.get(key, [default])
wheredefault
defaults toNone
you can take advantage of this and getNone
back for key(s) that don't exist (which evaluateFalse
ly).