In Python, you can use os
the module's getenv
or environ
method to read environment variables. Here is how the two methods are used:
-
Use
os.getenv
: This method returns the value of the specified environment variable, or returns if the environment variable does not existNone
.import os var = os.getenv('VAR_NAME')
-
Use
os.environ
: This method returns a dictionary representing environment variables, which you can manipulate like a dictionary. If the environment variable you are trying to access does not exist, it will raise oneKeyError
.import os var = os.environ['VAR_NAME']
In both methods above, 'VAR_NAME' needs to be replaced with the actual environment variable name you want to read.
If you need to read environment variables in your Python program, I recommend using it os.getenv
, because it will not raise an error if the variable does not exist, but return it None
. This makes it easier to run your program without setting a specific environment variable, just provide a default value. For example:
import os
var = os.getenv('VAR_NAME', 'default_value')
Here, if the 'VAR_NAME' environment variable does not exist, var
it will be assigned the value 'default_value'.