首页 > 解决方案 > 如何在 python 中使用子进程捕获“ps -ef|grep 'string'”的完整输出?

问题描述

我有一个在主机上运行的进程,我想捕获该进程并 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?

谢谢,南

标签: pythonsubprocess

解决方案


你应该使用这个:

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'
>>> 

推荐阅读