frn*_*nhr 4 python bash environment-variables
标题基本概括了所有内容..
假设我有一个bash脚本:
#!/bin/bash
# do some magic here, perhaps fetch something with wget, and then:
if [ "$VAR1" = "foo" ]; then
export CASEVARA=1
fi
export CASEVARB=2
# and potentially many other vars...
Run Code Online (Sandbox Code Playgroud)
如何从python运行此脚本并检查设置的env变量.理想情况下,我想将它们"反向继承"到运行Python的主环境中.
这样我就可以访问它们了
import os
# run the bash script somehow
print os.environ['CASEVARA']
Run Code Online (Sandbox Code Playgroud)
当然!它只需要一些黑客:
variables = subprocess.Popen(
["bash", "-c", "trap 'env' exit; source \"$1\" > /dev/null 2>&1",
"_", "yourscript"],
shell=False, stdout=subprocess.PIPE).communicate()[0]
Run Code Online (Sandbox Code Playgroud)
这将运行您未修改的脚本,并foo=bar 在不同的行上为您提供表单中的所有导出变量.
在支持的操作系统(如GNU)上,您可以trap 'env -0' exit获取\0分离的变量,以支持多行值.
| 归档时间: |
|
| 查看次数: |
2253 次 |
| 最近记录: |