简体   繁体   English

如何确定os.popen是否在同一shell中运行linux命令?

[英]How can I find out if os.popen is running the linux command in same shell?

I've the below python function that I use to run the linux command. 我具有以下用于运行linux命令的python函数。 I'm running a script which creates some environment variable and then I'm porting all those variable into on script again by running the linux command using the function below; 我正在运行一个创建一些环境变量的脚本,然后使用下面的函数运行linux命令,将所有这些变量再次移植到脚本中。 however it seems that the environment variables of the first command is not getting recorded using second command. 但是,似乎没有使用第二条命令记录第一条命令的环境变量。 I was wondering is it because the os.popen runs command in different shell every time I call it? 我想知道这是因为os.popen每次调用时都在不同的shell中运行命令吗? If so how can I modify my code or which function to use to have everything running in the same 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))

os.popen() is deprecated. 不推荐使用os.popen() In its place we have subprocess.Popen() and perhaps even better for your use case, subprocess.check_output() . 取而代之的是subprocess.Popen() ,或者对于您的用例来说甚至更好的是subprocess.check_output() These new methods take an optional env argument which is a dict of environment variable names and values. 这些新方法采用一个可选的env参数,该参数是环境变量名称和值的决定。 You can pass anything you need in there. 您可以在那里传递任何您需要的东西。

Or, if you really want to set the variables outside and have them "stick" in subprocesses, you can export them in the shell ( export myvarname ) before running Python. 或者,如果您真的想在外部设置变量并使它们“粘贴”在子export myvarname在运行Python之前export它们export到shell中( export myvarname )。

popen(3) (在Python os.popen中 )从未运行相同的 shell,而是派生了一个新的shell。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM