How to Get Environment Variables in Python: Distinction between os.environ and os.getenv

When creating web applications or scripts, directly writing sensitive information like database passwords or API keys in the source code is a major security risk. It is recommended to save such information as “Environment Variables” managed by the OS and read them when the program runs.

This article explains two basic ways to get environment variables using Python’s standard os module and how to distinguish between them.


目次

Preparation for Getting Environment Variables

To handle environment variables in Python, import the standard library os module.

import os

The os.environ object holds the current environment variables in a format similar to a dictionary (dict).


1. os.environ['KEY']: Getting Mandatory Items

This method uses brackets [] to specify the environment variable name (key), just like specifying a key in a dictionary.

  • Feature: If the specified environment variable does not exist, a KeyError occurs, and the program stops.
  • Usage: Suitable for getting mandatory environment variables (e.g., “Database connection password”) without which the program cannot operate.
import os

print("--- Database Connection Process ---")

try:
    # Get mandatory environment variable 'DB_PASSWORD'
    # If not set, an error occurs here, interrupting the connection process
    db_pass = os.environ["DB_PASSWORD"]
    
    print(f"Password acquired: {db_pass}")
    print("Connecting to database...")

except KeyError:
    print("Error: Environment variable 'DB_PASSWORD' is not set.")

Output (When environment variable is not set):

--- Database Connection Process ---
Error: Environment variable 'DB_PASSWORD' is not set.

2. os.environ.get('KEY'): Getting Optional Items

This method retrieves values similarly to the dictionary .get() method (the os.getenv() function works the same way).

  • Feature: If the specified environment variable does not exist, no error occurs, and None is returned. You can also specify a default value as the second argument.
  • Usage: Suitable for getting optional environment variables (e.g., “Debug mode setting”) where the program can run even if they are not set.
import os

# Get debug mode setting
# If env var 'DEBUG_MODE' is missing, use 'False' as default
debug_setting = os.environ.get("DEBUG_MODE", "False")

print(f"Debug Mode Setting: {debug_setting}")

if debug_setting == "True":
    print("Outputting detailed logs (Debugging)")
else:
    print("Outputting standard logs only (Production)")

Output (When environment variable is not set):

Debug Mode Setting: False
Outputting standard logs only (Production)

This allows the program to keep running with a safe default value (in this case, False) even if you forget to set the environment variable.


Summary

When getting environment variables in Python, use the appropriate method depending on the importance of the variable.

  • os.environ['KEY']: For Mandatory variables. Use this to stop the program with a KeyError if the variable does not exist.
  • os.environ.get('KEY', default): For Optional variables. Use this to apply a default value and continue the program if the variable does not exist.

Environment variables are a crucial mechanism for ensuring security and changing behavior between development and production environments.

よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次