Multiple Try Except when the value may not be present

281 views Asked by At

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...

4

There are 4 answers

0
James Mills On BEST ANSWER

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 Falsely).

0
Anshul Goyal On

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")
0
falsetru On

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))
0
Jorick Spitzen On

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')