Expand system variables Unix style
Low maintenance activity. Last release 15 months ago, commits in 0 of the last 26 weeks. Weaker on commit activity and recent releases.
pip install expandvarsexpandvars
Expand system variables Unix style
Inspiration
This module is inspired by GNU bash's variable expansion features. It can be used as an alternative to Python's os.path.expandvars function.
A good use case is reading config files with the flexibility of reading values from environment variables using advanced features like returning a default value if some variable is not defined. For example:
[default]
my_secret_access_code = "${ACCESS_CODE:-default_access_code}"
my_important_variable = "${IMPORTANT_VARIABLE:?}"
my_updated_path = "$PATH:$HOME/.bin"
my_process_id = "$$"
my_nested_variable = "${!NESTED}"
NOTE: Although this module copies most of the common behaviours of bash, it doesn't follow bash strictly. For example, it doesn't work with arrays.
Installation
Pip
pip install expandvars
Conda
conda install -c conda-forge expandvars
Usage
from expandvars import expandvars
print(expandvars("$PATH:${HOME:?}/bin:${SOME_UNDEFINED_PATH:-/default/path}"))
# /bin:/sbin:/usr/bin:/usr/sbin:/home/you/bin:/default/path
Examples
For now, refer to the test cases to see how it behaves.
TIPs
nounset=True
If you want to enable strict parsing by default, (similar to set -u / set -o nounset in bash), pass nounset=True.
# All the variables must be defined.
expandvars("$VAR1:${VAR2}:$VAR3", nounset=True)
# Raises UnboundVariable error.
NOTE: Another way is to use the
${VAR?}or${VAR:?}syntax. See the examples in tests.