Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if an environment variable exists and is set to True [closed]

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?

like image 813
Jason Avatar asked Jun 12 '17 17:06

Jason


People also ask

How to check if an environment variable is set in Linux?

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

How to check if a variable exists and is true?

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.

How to check if environment variable is set in AutoCAD?

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

How to check if multiple env variables are not set?

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.


Video Answer


2 Answers

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

like image 57
victor Avatar answered Sep 30 '22 07:09

victor


You can use:

env.get("abc", False)

False is the default value if "abc" is not in env.

like image 45
Bubble Bubble Bubble Gut Avatar answered Sep 30 '22 06:09

Bubble Bubble Bubble Gut