# How to check list of environment variable in python? [closed]

I have requirement to check list of environment variable in Linux. Based on environment variable, exit code will be different. how to optimize the below code?

def check_mandatory_envs():
if "ENVCONTEST_1" not in os.environ:
exit(125)
if "ENVCONTEST_2" not in os.environ:
exit(126)
if "ENVVIRTEST_3" not in os.environ
exit(127)
if "ENVVIRTEST_4" not in os.environ
exit(128)
if "ENVPATHTEST_5" not in os.environ
exit(129)
if "ENVPATHTEST_6" not in os.environ
exit(130)

• Where does exit(...) come from? Are you using something like from sys import exit at the beginning of your script? Nov 18 '19 at 15:22
• @AlexV exit is a builtin as far as I know.
Nov 18 '19 at 15:35
• @JAD It is, but there are noticeable differences between calling exit, sys.exit, and os.exit. Nov 18 '19 at 15:38

You can group the messages and corresponding exit codes into a dict, and then iterate over that one:

def check_mandatory_envs():
exit_codes = {
"ENVCONTEST_1" :125,
"ENVCONTEST_2" :126,
"ENVVIRTEST_3" :127,
"ENVVIRTEST_4" :128,
"ENVPATHTEST_5":129,
"ENVPATHTEST_6":130,
}
for variable, code in exit_codes.items():
if variable not in os.environ:
exit(code)


If the order of the iteration is important and you are on python before 3.6, you canuse a collections.OrderedDict or a list of tuples, without the .items() call

• Is there an advantage of using a dictionary here compared to, say, a tuple of tuples or something similar? Nov 18 '19 at 15:42
• Not really, there is no real downside either as far as I know. This also conveys that a certain variable has one exit code, and it throws a SyntaxError at compile time if you forgot an exit code or a comma, making input errors easier to find. Nov 18 '19 at 15:46