我正在使用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。
那么如何获得理想的结果?
答案 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}'