python - 如何在 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?
谢谢,南
解决方案
你应该使用这个:
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'
>>>
推荐阅读
- javascript - 在 vue JS 中使用索引从数组中删除一个项目会返回一个意外的结果
- python - 如何在熊猫中为列名分配上级名称(通用标题)
- google-cloud-platform - 数据流设置控制器服务帐户
- java - 文件下载百分比达到 74%
- xamarin - 列表项的任何属性更改时列表视图不刷新
- angular6 - 如何将表格行数据传递给弹出模式?
- android - Android Rotate Animation 没有完全旋转
- haskell - 使用 where/let 子句 Haskell 创建一个列表
- excel - Laravel 导出 Excel 不返回 excel 文件
- c++11 - 如何在其他函数中更新 void** 的值,并将其保存到另一个函数中?