1

I have 8 variables being loaded in from environment variables. 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.

There are a few ways of doing this. Assume the a = os.environ.get('a') code is prewritten, through 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?

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.

martineau
  • 119,623
  • 25
  • 170
  • 301
JonLuca
  • 850
  • 6
  • 25
  • 1
    Very related: https://stackoverflow.com/questions/36117583/pythonic-way-to-avoid-if-x-return-x-statements – timgeb Sep 26 '18 at 21:10
  • You could use the value returned from `index()` to get the variable name by also creating a parallel list of them i.e. `var_names = list('abcdef')`. – martineau Sep 26 '18 at 21:22

3 Answers3

4

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')
...
user2357112
  • 260,549
  • 28
  • 431
  • 505
1

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))
Andy
  • 450
  • 2
  • 8
0

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

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]
T Burgis
  • 1,395
  • 7
  • 9