2013-03-26 17 views
1
[email protected]:/home/ubuntuUser$ cat test.txt 
This is a test file 
used to validate file handling programs 
#pyName: test.txt 
this is the last line 
[email protected]:/home/ubuntuUser$ cat test.txt | grep "#pyName" 
#pyName: test.txt 
[email protected]:/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 >>> 

問題:爲什麼grep會返回子進程stdin中的所有輸出?

Q1:在文件打印只匹配行 外殼grep命令,同時通過子打印grep的整個文件。怎麼了?

Q2: 如何通過communications()發送的輸入添加到 初始命令('cat test.txt')? #2之後,初始命令是否會在「|」之後通過輸入字符串進行通信,和shell命令獲取像cat test.txt | grep #pyName

回答

0

@prasath,如果你正在尋找一個例子來使用通信()

[[email protected]_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 


[[email protected]_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 


[[email protected]_dev]#./communicate.py 
Enter a value: 
Got 10 
+0

謝謝Ignatious。這解釋了溝通工作的方式。太好了。因此,如果intial命令正在等待stdin輸入,則通過通信發送的命令會將其發送到該命令的stdin。再次感謝! – Prasath 2013-03-26 23:32:02

0

也許將grep傳遞給communicate()-函數不會如您所設想的那樣工作。您可以通過直接從文件grepping簡化流程如下:

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', '') 

這可能是一個聰明很多,做你想做的蟒蛇做什麼。如果它在文件中,以下內容將打印您的行。

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

Thanks!然而,我正在尋找一個例子來使用溝通(「做點什麼」) – Prasath 2013-03-26 16:03:06

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

謝謝。 「cat text.txt Prasath 2013-03-26 16:08:47

+0

@Prasath:我想你誤解了我的觀點。 'cat georg 2013-03-26 17:44:21

相關問題