So, I want to check and verify if a given variable "abc" exists and that it's true. If the variable exist and is False, then I want it to go to else. Here is how I got it to work in python:
env = os.environ.copy()
if "abc" in env and env['abc'] == "True":
print "Works"
else:
print "Doesn't work"
Is there a better way to do it?
If the variable is set, its value is displayed in the shell window. 1. Select Start > All Programs > Accessories > Command Prompt. 2. In the command window that opens, enter echo %VARIABLE%. Replace VARIABLE with the name of the environment variable you set earlier. For example, to check if MARI_CACHE is set, enter echo %MARI_CACHE%.
There are numerous ways to check if a variable exists and is true. We are going to use one of the easiest solutions which involve the usage of the try-catch block and ternary (?) operator. The ternary operator is also known as the conditional operator which acts similar to the if-else statement.
Select Start > All Programs > Accessories > Command Prompt. 2. In the command window that opens, enter echo %VARIABLE%. Replace VARIABLE with the name of the environment variable you set earlier. For example, to check if MARI_CACHE is set, enter echo %MARI_CACHE%.
In case you want to check if multiple env variables are not set, you can do the following: import os MANDATORY_ENV_VARS = ["FOO", "BAR"] for var in MANDATORY_ENV_VARS: if var not in os.environ: raise EnvironmentError ("Failed because {} is not set.".format (var)) I'd recommend the following solution.
You can check to see if the variable is in the dictionaries returned by globals() and locals(). (Thank you to Aaron for reminding me to add the full code)
For a local variable:
if locals().get('abc'):
print(abc)
For a global variable:
if globals().get('abc'):
print(abc)
For an environment variable:
if os.environ.get('abc')=='True':
#abc is set to True
More information here:
https://docs.python.org/3/library/functions.html#locals https://docs.python.org/3/library/functions.html#globals
You can use:
env.get("abc", False)
False is the default value if "abc" is not in env.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With