cor*_*ria 9 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???
Run Code Online (Sandbox Code Playgroud)
逐行读取后的预期输出:
abc 123
def 456
ghi 789
Run Code Online (Sandbox Code Playgroud)
如果我只是"打印输出",这将打印
使用for循环读取每一行时的实际输出:
a
b
c
1
2
3
d
e
f
Run Code Online (Sandbox Code Playgroud)
...
有任何想法吗?谢谢.
请尝试以下方法:
for line in output.split(os.linesep):
Run Code Online (Sandbox Code Playgroud)
代替:
for line in output:
Run Code Online (Sandbox Code Playgroud)
for c in s:从字符串中读取一个字符s(应该如此).要从字符串中获取行列表,可以使用.splitlines()方法:
lines = output.splitlines()
Run Code Online (Sandbox Code Playgroud)
您无需调用.communicate()逐行读取输出:
p = subprocess.Popen(cmd, stdout=PIPE)
for line in p.stdout:
# do something with a line
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15551 次 |
| 最近记录: |