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

时间:2013-03-26 09:01:17

标签: python subprocess

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 via subprocess打印整个文件。怎么了?

Q2: 如何通过communic()发送的输入被添加到 初始命令('cat test.txt')? 在#2之后,初始命令将通过“|”后的通信输入字符串追加和shell命令类似于cat test.txt | grep #pyName

3 个答案:

答案 0 :(得分:0)

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中做你想做的事可能会更聪明。如果文件位于文件中,以下内容将打印您的行。

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

答案 1 :(得分:0)

你在这里做的基本上是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

答案 2 :(得分:0)

@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