2014-01-29 32 views
7

我无法按行读取我的子过程输出。子进程只是简单地将文件的内容映射到另一个文件。输出应该是一个两列文件,输出到stdout就好了。但是,当我尝试读取每一行,它读取每个CHAR其次是\ N:Python:subprocess.popen:读取输出的每一行

#!/usr/bin/python  

import sys 
import getopt 
import os 
import subprocess 
from subprocess import Popen, PIPE, STDOUT 

inputfile = '' 
target = '' 

try: 
     opts, args = getopt.getopt(sys.argv[1:],"s:t:",['servers=', 'target=']) 
except getopt.GetoptError: 
     print 'getopt failure: exit' 
     sys.exit() 

for opt, arg in opts: 
     if opt in ("-s", "--servers"): 
       inputfile = arg 
     if opt in ("-t", "--target"): 
       boxwin = arg 

p1 = subprocess.Popen(["grep -f " + inputfile + " " + target + " | awk '{print $2, $1}'"], stdout=subprocess.PIPE, shell=True) 

output, error = p1.communicate() 

print output # this prints normally 

for line in output: 
     print line # this prints each char of output followed by \n??? 

预计输出逐行读取后:

abc 123 
def 456 
ghi 789 

^^这将打印,如果我只是“打印输出“

使用循环读取每个行,当实际输出:

a 
b 
c 

1 
2 
3 

d 
e 
f 

...

任何想法?谢谢。

回答

7

尝试以下操作:

for line in output.split(os.linesep): 

代替:

for line in output: 
+0

这样做。谢谢!很快就会接受。 – corneria

7

for c in s:在同一时间从一个字符串s读取一个字符(如它应该)。从字符串获取行的列表,而不是,您可以使用.splitlines() method

lines = output.splitlines() 

你不需要调用.communicate()由线读取输出线:

p = subprocess.Popen(cmd, stdout=PIPE) 
for line in p.stdout: 
    # do something with a line 

您可以修改代码以不同方式处理buffering或启用universal newlines support

+1

感谢您的提示。从我的脚本中删除约5行代码。 – corneria

相关问题