[英]Python: subprocess.popen: read each line of output
我無法逐行讀取子進程輸出。 子進程只是將文件的內容與另一個文件進行對比。 輸出應該是一個兩列文件,打印到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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.