29

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?

0

3 Answers 3

36

Use : os.path.expandvars

Sign up to request clarification or add additional context in comments.

3 Comments

strange that it's in os.path, considering environment variables are used for more than file-system path elements. I guess I could use os.path.expandvars('%username%') instead of getpass.getuser().
Note that os.path.expandvars will not expand and leave intact expressions using variables that are not set.
It's in os.path because it's main purpose is to expand environment variables that point to directories. For all other purposes you should use os.environ instead.
14
import string, os
my_path = '$HOME/dir/dir2'
print string.Template(my_path).substitute(os.environ)

Comments

7

You could use a Template:

from string import Template
import os

t = Template("$HOME/dir/dir2")
result = t.substitute(os.environ)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.