With os.path.expandvars
I can expand environment variables in a string, but with the caveat: "Malformed variable names and references to non-existing variables are left unchanged" (emphasis mine). And besides, os.path.expandvars
expands escaped \$
too.
I would like to expand the variables in a bash-like fashion, at least in these two points. Compare:
import os.environ
import os.path
os.environ['MyVar'] = 'my_var'
if 'unknown' in os.environ:
del os.environ['unknown']
print(os.path.expandvars("$MyVar$unknown\$MyVar"))
which gives my_var$unknown\my_var
with:
unset unknown
MyVar=my_var
echo $MyVar$unknown\$MyVar
which gives my_var$MyVar
, and this is what I want.
Try this:
The regular expression should match any valid variable name, as per this answer, and every match will be substituted with the empty string.
Edit: if you don't want to replace escaped vars (i.e.
\$VAR
), use a negative lookbehind assertion in the regex:(which says the match should not be preceded by
\
).Edit 2: let's make this a function:
check the result:
the variable
$TERM
gets expanded to its value, the nonexisting variable$FOO
is expanded to the empty string, and\$BAR
is not touched.