正则表达式捕获时打印出子进程 [英] Printing out subprocess when regex captures

查看:28
本文介绍了正则表达式捕获时打印出子进程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 python 中运行一个 bash 命令:

I am running a bash command in python with:

proc = subprocess.Popen(cmd)
proc.wait()

这个 cmd 打印输出.但是我不希望它打印,除非它被某些正则表达式捕获.不知道怎么做,因为这是我第一次使用 subprocess

This cmd prints an output. However I dont want it to print unless it is captured by some regex. Not sure how to do this as this is my first time using subprocess

推荐答案

您也可以将输出直接通过管道传送到 grep 等.:

You could do also pipe the output directly to grep etc..:

from subprocess import PIPE, Popen

p = Popen(["ps"], stdout=PIPE)
p2 = Popen(["grep", "chrome"],stdin=p.stdout, stdout=PIPE,universal_newlines=True)
p.stdout.close()

out,err = p2.communicate()
print(out)

 421 ?        00:00:03 chrome
 767 ?        00:00:02 chrome
 843 ?        00:00:04 chrome
 2788 ?        00:52:16 chrome
 2819 ?        00:00:00 chrome-sandbox
 2820 ?        00:00:00 chrome
 2827 ?        00:00:00 chrome-sandbox

这篇关于正则表达式捕获时打印出子进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆