美文网首页
Python与 Linux 系统变量的交互

Python与 Linux 系统变量的交互

作者: hqyang | 来源:发表于2017-04-17 10:20 被阅读84次

    问题来源

    python 下执行先 source first.sh ,再执行 second.sh

    first.sh 内容

    export abc=def
    # echo abc=bef >>/etc/profile

    second.sh 内容

    echo $abc
    # 希望输出 def

    python 代码

    scrpitPopen=subprocess.Popen('source first.sh',executable="/bin/bash",shell=True)
    scrpitPopen.communicate()
    scrpitPopen=subprocess.Popen('source second.sh',executable="/bin/bash",shell=True)
    scrpitPopen.communicate()

    原本我以为通过第一句话export abc=def就可以了,结果不如所愿, 原因如下

    在shell中执行程序时,shell会提供一组环境变量。export可新增,修改或删除环境变量,供后续执行的程序使用。export的效力仅及于该次登陆操作。

    然后我就想到了第二行话,echo abc=bef >>/etc/profile,然后执行source /etc/profile, 结果还是不行,查资料的结果是,平时在 shell 操作的时候, shell 登录时会载入系统变量,但是Popen不会, Popen 有一个参数 env= 用来添加环境变量.

    最后解决办法也简单,把 source /etc/profile 这句话 加到 second.sh 第一行即可.

    相关文章

      网友评论

          本文标题:Python与 Linux 系统变量的交互

          本文链接:https://www.haomeiwen.com/subject/hjazattx.html