如何使用python中的子进程捕获“ ps -ef | grep'字符串'”的完整输出?

时间:2018-10-05 10:07:31

标签: python subprocess

我有一个在主机上运行的进程,我想捕获该进程并在输出的最后一行中对字符串进行grep。 使用subprocess.Popen,我只能得到ps -ef | grep'string'输出的第一行

使用的命令:

cmd = "ps -ef|grep tmmain|grep -v grep"
subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE).communicate()[0]

我得到如上所述的NULL输出,因为ps -ef仅返回进程的第一行,而grep在其中找不到tmmain

$ ps -ef|grep tmmain|grep -v grep

oracle   27222  2232 19 Sep08 ?        5-06:35:21 /oracle/product/OEM/emnagent/agent_13.2.0.0.0/oracle_common/jdk/bin/java -Xmx140M -XX:MaxPermSize=96M -server -Djava.security.egd=file:///dev/./urandom -Dsun.lang.ClassLoader.allowArraySyntax=true -XX:-UseLargePages -XX:+UseLinuxPosixThreadCPUClocks -XX:+UseConcMarkSweepGC -XX:+CMSClassUnloadingEnabled -XX:+UseCompressedOops -Dwatchdog.pid=2232 -cp /oracle/product/OEM/emnagent/agent_13.2.0.0.0/jdbc/lib/ojdbc7.jar:/oracle/product/OEM/emnagent/agent_13.2.0.0.0/ucp/lib/ucp.jar:/oracle/product/OEM/emnagent/agent_13.2.0.0.0/oracle_common/modules/jsch-0.1.53.jar:/oracle/product/OEM/emnagent/agent_13.2.0.0.0/oracle_common/modules/com.oracle.http_client.http_client_12.1.3.jar:/oracle/product/OEM/emnagent/agent_13.2.0.0.0/oracle_common/modules/oracle.xdk_12.1.3/xmlparserv2.jar:/oracle/product/OEM/emnagent/agent_13.2.0.0.0/oracle_common/modules/oracle.dms_12.1.3/dms.jar:/oracle/product/OEM/emnagent/agent_13.2.0.0.0/oracle_common/modules/oracle.odl_12.1.3/ojdl.jar:/oracle/product/OEM/emnagent/agent_13.2.0.0.0/oracle_common/modules/oracle.odl_12.1.3/ojdl2.jar:/oracle/product/OEM/emnagent/agent_13.2.0.0.0/lib/optic.jar:/oracle/product/OEM/emnagent/agent_13.2.0.0.0/sysman/jlib/log4j-core.jar:/oracle/product/OEM/emnagent/agent_13.2.0.0.0/jlib/gcagent_core.jar:/oracle/product/OEM/emnagent/agent_13.2.0.0.0/sysman/jlib/emagentSDK-intg.jar:/oracle/product/OEM/emnagent/agent_13.2.0.0.0/sysman/jlib/emagentSDK.jar oracle.sysman.gcagent.tmmain.TMMain

这是我正在运行的实际过程。

如何捕获完整的输出和grep?

谢谢, 南

1 个答案:

答案 0 :(得分:0)

您应该使用此:

cmd = "ps -ef|grep tmmain|grep -v grep" 
subprocess.check_output(cmd,shell=True)

例如:

root@thanh:/home/thanh/myproject/flask# python3
Python 3.5.3 (default, Jan 19 2017, 14:11:04) 
[GCC 6.3.0 20170118] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import subprocess
>>> cmd = "ps aux| grep python"
>>> subprocess.check_output(cmd,shell=True)
b'thanh     2573  0.0  0.0 363384  3584 ?        Sl   08:49   0:00 /usr/bin/python3 /usr/bin/libertined --cache-output\nroot      8093  1.5  0.2  45444 11256 pts/1    S+   17:15   0:00 python3\nroot      8094  0.0  0.0   4496   744 pts/1    S+   17:15   0:00 /bin/sh -c ps aux| grep python\nroot      8096  0.0  0.0  22868   912 pts/1    S+   17:15   0:00 grep python\n'
>>>