Home > Backend Development > Python Tutorial > How Do I Access and Manage Environment Variables in Python?

How Do I Access and Manage Environment Variables in Python?

DDD
Release: 2024-12-27 03:01:10
Original
737 people have browsed it

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'])
Copy after login

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)
Copy after login

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'))
Copy after login

with Default Value

Returns 'default_value' if the variable doesn't exist:

print(os.environ.get('KEY_THAT_MIGHT_EXIST', default_value))
Copy after login

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))
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template