Expand Environment Variables Unix Style
The `expandvars` Python library provides functionality to expand system environment variables within strings, similar to how Unix shells do. It supports both `$VAR` and `${VAR}` syntaxes, including default values and escape sequences. The current version is 1.1.2, with releases occurring periodically to address bugs and add features.
Warnings
- gotcha Prior to version 1.1.2, `expandvars` could incorrectly handle expansions involving unset variables, potentially leading to incorrect string parsing or unexpected output, especially when default values were used or mixed with other expansions.
- gotcha Before v1.1.1, the library's escaping behavior for `$` characters was fixed, and there was no explicit option to force the `${var}` syntax. If your strings contain literal `$` signs that were implicitly handled, or if you prefer strict `${var}` syntax, the new `disable_escape` and `force_braces` parameters might change or clarify behavior you previously relied on.
- gotcha Unlike some Unix shells, `expandvars` does not interpret `$$` as the process ID (PID). Instead, `\$` is the explicit escape sequence for a literal dollar sign. Be careful not to confuse this with shell behavior if you expect `$$` to expand to a PID.
Install
-
pip install expandvars
Imports
- expandvars
from expandvars import expandvars
Quickstart
import os
from expandvars import expandvars
# Set environment variables for demonstration (use os.environ.get for robustness)
os.environ['API_KEY'] = os.environ.get('API_KEY', 'your_default_api_key')
os.environ['SERVICE_URL'] = 'https://example.com/api'
# Basic variable expansion
config_string = "My service at ${SERVICE_URL} requires key: $API_KEY"
expanded_config = expandvars(config_string)
print(f"Original: {config_string}")
print(f"Expanded: {expanded_config}")
# Example with a default value for an unset variable
missing_var_string = "Optional setting: ${OPTIONAL_VAR:-default_value}"
expanded_missing = expandvars(missing_var_string)
print(f"Original: {missing_var_string}")
print(f"Expanded: {expanded_missing}")
# Example with escaping a dollar sign
escaped_string = expandvars("Literal dollar sign: \$VAR")
print(f"Escaped: {escaped_string}")