为什么grep在子进程stdin中返回所有输出?

2024-10-02 12:29:50 发布

您现在位置:Python中文网/ 问答频道 /正文

ubuntu@ubuntu:/home/ubuntuUser$ cat test.txt 
This is a test file
used to validate file handling programs
#pyName: test.txt
this is the last line
ubuntu@ubuntu:/home/ubuntuUser$ cat test.txt | grep "#pyName"
#pyName: test.txt
ubuntu@ubuntu:/home/ubuntuUser$ "

#1  >>> a = subprocess.Popen(['cat test.txt'], 
                             stdin=subprocess.PIPE,
                             stdout=subprocess.PIPE, 
                             stderr=subprocess.PIPE, 
                             shell=True)
#2  >>> o, e = a.communicate(input='grep #pyName')
#3  >>> print o
#3  This is a test file
#3  used to validate file handling programs
#3  #pyName: test.txt
#3  this is the last line
#3  
#3  >>> 

问题:

问题1: 文件上的shell grep命令只打印匹配的行,而grep via子进程打印整个文件。怎么了?在

问题2: 如何将通过communicate()发送的输入添加到 初始命令('cat测试.txt')? 在#2之后,在“|”和shell命令变得像cat test.txt | grep #pyName之后,初始命令是否会被来自communicate的输入字符串追加?在


Tags: test命令txthomeisubuntushellgrep
3条回答

你在这里做的基本上是cat test.txt < grep ...,这显然不是你想要的。要设置管道,需要启动两个进程,并将第一个进程的stdout连接到第二个进程的stdin:

cat = subprocess.Popen(['cat', 'text.txt'], stdout=subprocess.PIPE)
grep = subprocess.Popen(['grep', '#pyName'], stdin=cat.stdout, stdout=subprocess.PIPE)
out, _ = grep.communicate()
print out

也许将grep传递给communicate()-函数并不像您假设的那样工作。可以通过直接从文件中重新映射来简化过程,如下所示:

In [14]: a = subprocess.Popen(['grep "#pyName" test.txt'], stdin = subprocess.PIPE, stdout = subprocess.PIPE, stderr=subprocess.PIPE, shell = True)

In [15]: a.communicate()
Out[15]: ('#pyName: test.txt\n', '')

用python做你想做的事情可能会更聪明。如果您的行在文件中,下面将打印它。在

^{pr2}$

@prasath如果您正在寻找使用communicate()的示例

[root@ichristo_dev]# cat process.py    A program that reads stdin for input
#! /usr/bin/python

inp = 0  
while(int(inp) != 10):  
    print "Enter a value: "  
    inp = raw_input()  
    print "Got", inp  


[root@ichristo_dev]# cat communicate.py
#! /usr/bin/python

from subprocess import Popen, PIPE  

p = Popen("./process.py", stdin=PIPE, stdout=PIPE, stderr=PIPE, shell=True)  
o, e = p.communicate("10")  
print o  


[root@ichristo_dev]#./communicate.py  
Enter a value:   
Got 10

相关问题 更多 >

    热门问题