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


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

问题:

Q1:文件上的Shell grep命令只打印匹配的行,而通过子进程的grep命令打印整个文件。什么错了吗?

第二季:如何将通过communication()发送的输入添加到初始命令('cat test.txt')?

#2之后,初始命令是否会被通信输入字符串附加在"|"之后,shell命令会像cat test.txt | grep #pyName一样吗?

@prasath如果你正在寻找一个例子来使用communication (),

[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

也许将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.txtn', '')

用python做你想做的事情可能会聪明得多。如果你的行在文件中,下面的命令将打印出来。

In [1]: with open("test.txt") as f:
   ...:     for line in f:
   ...:         if "#pyName" in line:
   ...:            print line
   ...:            break
   ...:         
#pyName: test.txt

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

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

最新更新