使用子进程来获取通过头-1输出的grep输出 [英] Using subprocess to get output of grep piped through head -1

查看:164
本文介绍了使用子进程来获取通过头-1输出的grep输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  grep -nsome phrase{some file路径} |头-1 

我想将这个输出传递给python。到目前为止,我尝试过的是:

pre $ subprocess.Popen('grep -nsome phrase{some file path} | head -1',shell = True,stdout = subprocess.PIPE)

大量的消息说:

 grep:writing output:Broken pipe

我对子流程模块不是很熟悉,我希望得到如何获得的建议此输出以及我目前做错的事情。

解决方案

该文档向您展示如何使用Popen替换外壳管道



< $ {pre $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $'$'一些文件路径}'],stdout = PIPE)
p2 = Popen(['head','-1'],stdin = p1.stdout,stdout = PIPE)
p1.stdout.close )#允许p1接收一个SIGPIPE p2退出。
out,err = output = p2.communicate()


The gist of what I'm trying to do is this:

grep -n "some phrase" {some file path} | head -1

I would like to pass the output of this into python. What I've tried so far is:

p = subprocess.Popen('grep -n "some phrase" {some file path} | head -1',shell=True,stdout=subprocess.PIPE)

I get back a lot of messages saying

"grep: writing output: Broken pipe"

I'm not very familiar with the subprocess module, I would like advice as to how to get this output, and what I am currently doing wrong.

解决方案

The docs show you how to replace shell piping using Popen:

from subprocess import PIPE, Popen


p1 = Popen(['grep', '-n', 'some phrase', '{some file path}'],stdout=PIPE)
p2 = Popen(['head', '-1'], stdin=p1.stdout, stdout=PIPE)
p1.stdout.close()  # Allow p1 to receive a SIGPIPE if p2 exits.
out,err = output = p2.communicate()

这篇关于使用子进程来获取通过头-1输出的grep输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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