python - Python 中等效的 Linux shell 源命令

标签 python shell

将 shell 脚本转换为 python 并尝试找到执行以下操作的最佳方法。我需要这个,因为它包含我需要读取的环境变量。

if [ -e "/etc/rc.platform" ];
then
    . "/etc/rc.platform"
fi

我已转换“if”,但不确定如何处理 . “/etc/rc.platform”作为源是一个 shell 命令。到目前为止我有以下内容

if os.path.isfile("/etc/rc.platform"):
    print "exists" <just to verify the if if working>
    <what goes here to replace "source /etc/rc.platform"?>

我查看了 subprocess 和 execfile 但没有成功。

Python脚本需要访问rc.platform设置的环境变量

最佳答案

一个有点黑客的解决方案是解析 env 输出:

newenv = {}
for line in os.popen('. /etc/rc.platform >&/dev/null; env'):
    try:
        k,v = line.strip().split('=',1)
    except:
        continue  # bad line format, skip it
    newenv[k] = v
os.environ.update(newenv)

编辑:修复了分割参数,感谢@l4mpi

关于python - Python 中等效的 Linux shell 源命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15276285/

相关文章:

python - 结合python中2个类的函数

python - Web3py send_raw_transaction ValueError : {'message' : 'invalid remainder' , 'code' : -32000}

python - 如何在Python中的列表中存储多个字符串?

c - 在linux中使用execv使用 './'命令

c++ - 从 shell 扩展程序将项目插入到桌面右键单击菜单

python - 反向 Django 管理 URL

python : is it ok to threads read/write simultaneously to same TCP socket?

linux - 在脚本内使用没有密码的 sudo

shell - 如何在shell脚本中保留$@中的双引号?

bash - 如何通过终端关闭 Chrome 浏览器选项卡?