Jen*_*ens 5 python environment-variables python-3.x
看起来好像Python的os.path.expandvars()函数是在调用进程环境上运行的。有没有办法将我自己的新变量添加到混合中而不污染过程环境?
我能想到的最好的办法是:
>>> env = os.environ
>>> env["FOO"] = "VAL"
>>> os.path.expandvars("variable FOO=$FOO")
'variable FOO=VAL'
>>> del env["FOO"]
Run Code Online (Sandbox Code Playgroud)
理想情况下,我想传递env一个像 的论证subprocess.Popen()。看来我得自己写一个这样的包装器?
小智 1
这可能看起来很愚蠢,但请尝试执行以下操作:
# Crete a new env and modify it
new_env = os.environ.copy()
new_env["FOO_VAR"] = "FOO_VALUE"
# Replace the env e use expandvars
tmp_env = os.environ
os.environ = new_env
print(os.path.expandvars("variable FOO=$FOO_VAR"))
# Return to the old env
os.environ = tmp_env
Run Code Online (Sandbox Code Playgroud)
顺便说一句,我最初使用正则表达式来识别 %(?.+)% 和 $\{?(?.+)\}?[/\\\n],但执行上述操作似乎更好。