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

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

4

3 回答 3

0

也许传递grepcommunicate()-function 不像你想象的那样工作。您可以通过直接从文件中提取来简化您的过程,如下所示:

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
于 2013-03-26T09:43:29.020 回答
0

你在这里所做的本质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
于 2013-03-26T09:52:13.440 回答
0

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

[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
于 2013-03-26T22:15:40.277 回答