Python:subprocess.popen:读取每行输出

时间:2014-01-29 03:44:41

标签: python subprocess stdout

我无法逐行读取子进程输出。子进程只是将文件的内容与另一个文件进行对比。输出应该是一个两列文件,打印到stdout就好了。但是当我尝试读取每一行时,它会读取每个字符,然后是\ n:

#!/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
如果我只是“打印输出”

,这将打印出来

使用for循环读取每一行时的实际输出:

a
b
c

1
2
3

d
e
f

...

有什么想法吗?感谢。

2 个答案:

答案 0 :(得分:8)

尝试以下方法:

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

而不是:

for line in output:

答案 1 :(得分:8)

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