Sobes.tech
Junior — Middle

How can environment variable values be extracted in Python?

sobes.tech AI

Answer from AI

In Python, the os module is used to obtain environment variable values.

Example:

import os

# Get the value of the environment variable 'HOME'
home_dir = os.getenv('HOME')
print(f"Home directory: {home_dir}")

# Or through the os.environ dictionary
path = os.environ.get('PATH')
print(f"PATH: {path}")

If the variable is not set, os.getenv will return None, or you can specify a default value: os.getenv('VAR', 'default'). This is convenient for configuring applications through environment variables.