Home >Backend Development >Python Tutorial >How Do I Access and Manage Environment Variables in Python?
Accessing Environment Variables in Python
To access environment variables in Python, utilize the os.environ object, which represents a mapping of environment variable names to their values. By default, accessing the variable within the mapping prompts the interpreter to search the Python dictionary for its value.
Retrieving a Single Variable
To retrieve the value of a specific environment variable, use the following syntax:
import os print(os.environ['HOME'])
Replace 'HOME' with the name of the variable you want to access.
Displaying All Variables
To list all the environment variables, print the os.environ object as a dictionary:
print(os.environ)
Handling Missing Variables
Attempting to access a non-existent environment variable will trigger a KeyError. To avoid this:
os.environ.get()
Returns 'None' if the variable doesn't exist:
print(os.environ.get('KEY_THAT_MIGHT_EXIST'))
with Default Value
Returns 'default_value' if the variable doesn't exist:
print(os.environ.get('KEY_THAT_MIGHT_EXIST', default_value))
os.getenv()
Similar to os.environ.get(), but with the option to supply a default value:
print(os.getenv('KEY_THAT_MIGHT_EXIST', default_value))
The above is the detailed content of How Do I Access and Manage Environment Variables in Python?. For more information, please follow other related articles on the PHP Chinese website!