简体   繁体   English

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

[英]Why is the python subprocess output different from the shell?

I am using the subprocess module to find out if a process is running. 我正在使用subprocess进程模块来查明进程是否正在运行。 But the result is different when the process to find does not exist. 但是当查找过程不存在时,结果会有所不同。

For example, in the shell, if the process python test.py does not exist, the output of ps -ef|grep python|grep test|awk '{print $2}' is empty. 例如,在shell中,如果进程python test.py不存在,则ps -ef|grep python|grep test|awk '{print $2}'为空。 But in python: 但是在python中:

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

The output r is not None. 输出r不是None。 It is the pid of the shell executing cmd . 它是执行cmd的shell的pid。

So how to get the desired result? 那么如何获得理想的结果呢?

While the shell subprocess is running, its arguments are visible to ps since they are passed as a command line to sh . 当shell子进程正在运行时,它的参数对ps是可见的,因为它们作为命令行传递给sh

shell=True works by invoking ['/bin/sh', '-c', cmdstring] . shell=True通过调用['/bin/sh', '-c', cmdstring]

When you type a pipeline in the shell, each part of the pipeline is invoked separately so there is no process with both "python" and "test" in its arguments. 在shell中键入管道时,管道的每个部分都是单独调用的,因此在其参数中没有同时包含“python”和“test”的进程。

Your process tree looks like this: 您的进程树如下所示:

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

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

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