Accessing Environment Variables in Python
Accessing environment variables in Python is a crucial task for interacting with the system's configuration and user-defined settings. In this article, we'll explore how to retrieve the value of an environment variable and list all available variables using Python's built-in capabilities.
Retrieving Environment Variable Value
To access the value of an environment variable, use the os.environ dictionary-like object:
import os print(os.environ['HOME'])
This prints the value of the HOME environment variable, which typically points to the user's home directory.
Getting All Environment Variables
To see a comprehensive list of all environment variables accessible to your Python program:
print(os.environ)
This will output a comprehensive dictionary of all available environment variables and their values.
Handling Missing or Null Values
By default, attempting to access a non-existent environment variable will raise a KeyError. To prevent this:
print(os.environ.get('KEY_THAT_MIGHT_EXIST'))
print(os.environ.get('KEY_THAT_MIGHT_EXIST', 'Default Value'))
print(os.getenv('KEY_THAT_MIGHT_EXIST', 'Default Value'))
The above is the detailed content of How Can I Access and Manage Environment Variables in Python?. For more information, please follow other related articles on the PHP Chinese website!