源shell脚本并从os.environ访问导出的变量 [英] Source shell script and access exported variables from os.environ

查看:78
本文介绍了源shell脚本并从os.environ访问导出的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个shell脚本,其中设置了某些参数,例如:
k.sh:

I have a shell script where certain parameters are being set like:
k.sh:

export var="value"
export val2="value2"

然后我有一个python脚本,我在其中调用shell脚本并想使用这些环境变量.
ex1.py:

Then I have a python script where i am calling the shell script and want to use these enviornment variables
ex1.py:

import subprocess
import os
subprocess.call("source k.sh",shell=True)
print os.environ["var"]

但是我收到了 KeyError
如何在我的Python脚本中使用这些shell变量?

But I am getting a KeyError
How can I use these shell variables in my Python script?

推荐答案

如果要设置环境然后运行Python脚本,请设置环境并使用 runner 运行Python脚本.:

If you want to set the environment and then run a Python script, well, set the environment and run the Python script using runner:

跑步者:

#! /bin/bash
. k.sh
exec ex1.py

就是这样.

ex1.py :

#import subprocess
import os
#subprocess.call("source k.sh",shell=True)
print os.environ["var"]

这篇关于源shell脚本并从os.environ访问导出的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆