为什么python子进程输出与shell不同?

时间:2012-06-15 09:58:34

标签: python shell process awk subprocess

我正在使用subprocess模块来确定进程是否正在运行。但是当查找过程不存在时,结果会有所不同。

例如,在shell中,如果进程python test.py不存在,则ps -ef|grep python|grep test|awk '{print $2}'的输出为空。但是在python中:

cmd="ps -ef|grep python|grep test|awk '{print $2}'"
vp=subprocess.Popen(cmd,stdout=subprocess.PIPE,shell=True)
r=vp.communicate()[0]

输出r不是None。它是执行cmd的shell的pid。

那么如何获得理想的结果?

1 个答案:

答案 0 :(得分:4)

当shell子进程正在运行时,它的参数对ps可见,因为它们作为命令行传递给sh

shell=True通过调用['/bin/sh', '-c', cmdstring]来发挥作用。

在shell中键入管道时,管道的每个部分都是单独调用的,因此在其参数中没有同时包含“python”和“test”的进程。

您的流程树如下所示:

python script.py
    /bin/sh -c "ps -ef|grep python|grep test|awk '{print $2}'"
        ps -ef
        grep python
        grep test
        awk '{print $2}'