Expanding Environment variable in string using python
Question:
I have a string containing an environment variable, e.g.
my_path = '$HOME/dir/dir2'
I want parse the string, looking up the variable and replacing it in the string:
print "HOME =",os.environ['HOME']
my_expanded_path = parse_string(my_path)
print "PATH =", my_expanded_path
So I should see the output:
HOME = /home/user1
PATH = /home/user1/dir/dir2
Is there an elegant way to do that in Python?
Answers:
Use : os.path.expandvars
You could use a Template
:
from string import Template
import os
t = Template("$HOME/dir/dir2")
result = t.substitute(os.environ)
import string, os
my_path = '$HOME/dir/dir2'
print string.Template(my_path).substitute(os.environ)
I have a string containing an environment variable, e.g.
my_path = '$HOME/dir/dir2'
I want parse the string, looking up the variable and replacing it in the string:
print "HOME =",os.environ['HOME']
my_expanded_path = parse_string(my_path)
print "PATH =", my_expanded_path
So I should see the output:
HOME = /home/user1
PATH = /home/user1/dir/dir2
Is there an elegant way to do that in Python?
Use : os.path.expandvars
You could use a Template
:
from string import Template
import os
t = Template("$HOME/dir/dir2")
result = t.substitute(os.environ)
import string, os
my_path = '$HOME/dir/dir2'
print string.Template(my_path).substitute(os.environ)