envsubst Python Library

0.1.5 · active · verified Thu Apr 16

The `envsubst` library for Python provides functionality to substitute environment variables in a string, mimicking the behavior of the GNU `envsubst` command-line utility. It supports `$VAR` and `${VAR}` style variable expansions, including the use of default values like `${VAR:-default}`. The current version is 0.1.5, with its last release in October 2019, indicating a maintenance-only or inactive development cadence.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to import and use the `envsubst` function to replace environment variables in a string. It covers both basic substitution and using default values when a variable is unset or empty. The example explicitly sets and cleans up environment variables for reproducible results.

import os
from envsubst import envsubst

# Example 1: Basic substitution
os.environ['MY_APP_NAME'] = 'MyAwesomeApp'
template_string = "The application name is: ${MY_APP_NAME}."
result = envsubst(template_string)
print(f"Basic substitution: {result}")
# Expected: "The application name is: MyAwesomeApp."

# Example 2: Substitution with default value (if variable is unset or empty)
# Clear the variable to demonstrate default
if 'FEATURE_FLAG' in os.environ:
    del os.environ['FEATURE_FLAG']
template_with_default = "Feature status: ${FEATURE_FLAG:-disabled}."
result_default = envsubst(template_with_default)
print(f"With default (unset): {result_default}")
# Expected: "Feature status: disabled."

os.environ['FEATURE_FLAG'] = 'enabled'
result_default_set = envsubst(template_with_default)
print(f"With default (set): {result_default_set}")
# Expected: "Feature status: enabled."

# Clean up environment variables used (good practice for scripts)
del os.environ['MY_APP_NAME']
if 'FEATURE_FLAG' in os.environ:
    del os.environ['FEATURE_FLAG']

view raw JSON →