How to evaluate environment variables into a string in Python?
Question:
I have a string representing a path. Because this application is used on Windows, OSX and Linux, we’ve defined environment variables to properly map volumes from the different file systems. The result is:
"$C/test/testing"
What I want to do is evaluate the environment variables in the string so that they’re replaced by their respective volume names. Is there a specific command I’m missing, or do I have to take os.environ.keys()
and manually replace the strings?
Answers:
Use os.path.expandvars to expand the environment variables in the string, for example:
>>> os.path.expandvars('$C/test/testing')
'/stackoverflow/test/testing'
In Python 3 you can do:
'{VAR}'.format(**os.environ))
for example
>>> 'hello from {PWD}'.format(**os.environ))
hello from /Users/william
The os.path.expandvars
solution will not expand variables that aren’t set.
If you want unset variables to be expanded to empty values (like the shell does), you can use string.Template
, example:
import os
from string import Template
from collections import defaultdict
def expand_posix_vars(posix_expr, context):
env = defaultdict(lambda: '')
env.update(context)
return Template(posix_expr).substitute(env)
conf_str = "${PREFIX}something"
assert "something" == expand_posix_vars(conf_str, {})
assert "hellosomething" == expand_posix_vars(conf_str, {"PREFIX": "hello"})
I have a string representing a path. Because this application is used on Windows, OSX and Linux, we’ve defined environment variables to properly map volumes from the different file systems. The result is:
"$C/test/testing"
What I want to do is evaluate the environment variables in the string so that they’re replaced by their respective volume names. Is there a specific command I’m missing, or do I have to take os.environ.keys()
and manually replace the strings?
Use os.path.expandvars to expand the environment variables in the string, for example:
>>> os.path.expandvars('$C/test/testing')
'/stackoverflow/test/testing'
In Python 3 you can do:
'{VAR}'.format(**os.environ))
for example
>>> 'hello from {PWD}'.format(**os.environ))
hello from /Users/william
The os.path.expandvars
solution will not expand variables that aren’t set.
If you want unset variables to be expanded to empty values (like the shell does), you can use string.Template
, example:
import os
from string import Template
from collections import defaultdict
def expand_posix_vars(posix_expr, context):
env = defaultdict(lambda: '')
env.update(context)
return Template(posix_expr).substitute(env)
conf_str = "${PREFIX}something"
assert "something" == expand_posix_vars(conf_str, {})
assert "hellosomething" == expand_posix_vars(conf_str, {"PREFIX": "hello"})