"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Access and management methods of Python environment variables

Access and management methods of Python environment variables

Posted on 2025-05-03
Browse:221

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))
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3