将环境变量注入字符串路径

时间:2019-03-13 12:44:12

标签: python python-3.x

我有以下字符串:

some_string = "%envvar1%\location\execution.exe"

envvar1是一个环境变量,其值为“ c:\”,我想要一些如下功能:

some_string = "%envvar1%\location\execution.exe"
inject_env_variable(some_string)
print(some_string)
"c:\location\execution.exe"

使用正则表达式和os.environ创建这样的函数不会很困难,但是我想知道是否存在某种内置模块可以处理这些事情。

注意:由于所有搜索都与pythonpath有关:P

2 个答案:

答案 0 :(得分:2)

os.path.expandvars可能正是您想要的。 https://docs.python.org/3/library/os.path.html#os.path.expandvars

答案 1 :(得分:0)

import os


def inject_env_variable(s):
   return s.replace("%envvar1%", os.environ['envvar1'])

应该做到这一点

相关问题