【问题标题】:Python Environment variable within environment variable环境变量中的 Python 环境变量
【发布时间】:2014-09-30 02:07:22
【问题描述】:

我正在尝试通过 Python 设置环境变量:

os.environ["myRoot"]="/home/myName"
os.environ["subDir"]="$myRoot/subDir"

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

(大图:我正在读取环境变量的 json 文件,较低的引用较高的)

【问题讨论】:

    标签: python shell unix environment-variables


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:
      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
      

      [已编辑以修复会导致其无法工作的错字]

      【讨论】:

      • 我认为需要一个很好的解释,我猜 OP 的经验并不过分,使用with 打开文件或至少关闭它会更好;)
      • meh 我想你是对的......良好的做法和所有......仍然打开文件并从中读取然后垃圾收集......withclose用于读取文件不是很重要(但对于新编码员来说可能仍然是一个好习惯)...
      • 是的,在这个问题中不是那么重要,但绝对使用with 可以帮助避免以后的一些头痛。
      【解决方案3】:

      您可以使用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")
      

      我认为@johntellsall 的回答更适合您给出的具体示例,但我相信您会发现这对您的 json 工作很有用。

      编辑:我现在建议使用@johntellsall 的答案,因为 os.path.expandvars() 是明确设计用于路径的,因此将其用于任意字符串可能有效,但有点 hacky。

      【讨论】:

        最近更新 更多