如何判断os.popen是否在同一个shell中运行linux命令?

时间:2014-10-15 12:52:44

标签: python linux shell environment-variables popen

我用下面运行linux命令的python函数。我正在运行一个创建一些环境变量的脚本,然后通过使用下面的函数运行linux命令,将所有这些变量再次移植到脚本中;但是,似乎第一个命令的环境变量没有使用第二个命令记录。我想知道是因为每次调用它时os.popen运行命令都在不同的shell中吗?如果是这样,我如何修改我的代码或使用哪个函数让所有东西在同一个shell中运行?

def execute(cmd):
    '''Module to execute linux command'''
    try:
        proc = os.popen(cmd)
        out = proc.read().strip()
        return out
    except Exception,err:
        print "Exception occurred : %s"%str(err)
        raise(str(err))

2 个答案:

答案 0 :(得分:1)

os.popen()已弃用。取而代之的是subprocess.Popen(),甚至可能更适合您的用例subprocess.check_output()。这些新方法采用可选的env参数,该参数是环境变量名称和值的字典。你可以在那里传递你需要的任何东西。

或者,如果你真的想在外面设置变量并让它们“粘贴”在子进程中,你可以在运行Python之前在shell(export)中export myvarname

答案 1 :(得分:0)

popen(3)(以及在Python os.popen中)从不运行相同的 shell,但要求新的。