我无法按行读取我的子过程输出。子进程只是简单地将文件的内容映射到另一个文件。输出应该是一个两列文件,输出到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
...
任何想法?谢谢。
这样做。谢谢!很快就会接受。 – corneria