环境变量中的Python环境变量

时间:2014-08-07 00:05:42

标签: python shell unix environment-variables

我正在尝试通过 Python

设置环境变量
os.environ["myRoot"]="/home/myName"
os.environ["subDir"]="$myRoot/subDir"

我希望subDir环境变量保持/home/myname/subDir,但它保存字符串'$myRoot/subDir'。我如何获得此功能?

(更大的图片:我正在读一个环境变量的json文件,下面的那些参考更高的那些)

3 个答案:

答案 0 :(得分:1)

使用os.environ获取值,os.path正确地将斜杠放在正确的位置:

os.environ["myRoot"]="/home/myName" 
os.environ["subDir"] = os.path.join(os.environ['myRoot'], "subDir")

答案 1 :(得分:1)

您可以使用os.path.expandvars扩展环境变量,如下所示:

>>> import os
>>> print os.path.expandvars("My home directory is $HOME")
My home director is /home/Majaha
>>> 

对于您的示例,您可能会这样做:

os.environ["myRoot"]="/home/myName"
os.environ["subDir"]=os.path.expandvars("$myRoot/subDir")

我认为shavenwarthog的回答对于你给出的具体例子来说更好,但是我并不怀疑你会发现这对你的json工作有用。

答案 2 :(得分:0)

def fix_text(txt,data):
    '''txt is the string to fix, data is the dictionary with the variable names/values'''
    def fixer(m): #takes a regex match 
         match = m.groups()[0] #since theres only one thats all we worry about
         #return a replacement or the variable name if its not in the dictionary
         return data.get(match,"$%s"%match) 
    return re.sub("$([a-zA-Z]+)",fixer,txt) #regular expression to match a "$" followed by 1 or more letters

with open("some.json") as f: #open the json file to read
    file_text= f.read()
data = json.loads(file_text) #load it into a json object
#try to ensure you evaluate them in the order you found them
keys = sorted(data.keys() ,key=file_text.index) 
#create a new dictionary by mapping our ordered keys above to "fixed" strings that support simple variables
data2= dict(map(lambda k:(k,fixer(data[k],data)),keys)
#sanity check
print data2

[编辑以解决导致其无效的拼写错误]