我无法逐行读取子进程输出.子进程只是将文件的内容与另一个文件进行对比.输出应该是一个两列文件,打印到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
...
有任何想法吗?谢谢.
请尝试以下方法:
for line in output.split(os.linesep):
代替:
for line in output:
for c in s:
从字符串中读取一个字符s
(应该如此).要从字符串中获取行列表,可以使用.splitlines()
方法:
lines = output.splitlines()
您无需调用.communicate()
逐行读取输出:
p = subprocess.Popen(cmd, stdout=PIPE) for line in p.stdout: # do something with a line
您可以修改代码以不同方式处理缓冲或启用通用换行支持.