使用python在字符串中扩展Environment变量

时间:2021-07-26 00:03:42

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?

在Python中有一种优雅的方式吗?

thanks!

谢谢!

Conor

康纳尔

3 个解决方案

#1


23  

Use : os.path.expandvars

使用:os.path.expandvars

#2


8  

import string, os
my_path = '$HOME/dir/dir2'
print string.Template(my_path).substitute(os.environ)

#3


2  

You could use a Template:

你可以使用一个模板:

from string import Template
import os

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

#1


23  

Use : os.path.expandvars

使用:os.path.expandvars

#2


8  

import string, os
my_path = '$HOME/dir/dir2'
print string.Template(my_path).substitute(os.environ)

#3


2  

You could use a Template:

你可以使用一个模板:

from string import Template
import os

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