我無法按行讀取我的子過程輸出。子進程只是簡單地將文件的內容映射到另一個文件。輸出應該是一個兩列文件,輸出到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