指令中有管道,如何获取标准输出?
翻了半天 python 3 的 Standard Library,看得云里雾里,硬是没找到好办法。{:yxh131:}
比如执行这条指令:ps ax | grep kworker | wc -l到底要如何才能获取输出?
我试了output = subprocess.check_output('ps ax | grep kworker', Shell = True)据说这个比较高大上,可以替代以前所有的类似接口。但是半天没弄明白,为什么返回值一直是 0。后来才意识到,传进去的指令只能是带参数形式,不支持管道。
那么问题来了,这种带管道的指令输出,到底要如何才能获得? import subprocess
p = subprocess.Popen('ps ax | grep kworker', stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True)
while True:
code = p.poll()
buff = p.stdout.readline()
if buff:
print buff
if code != None and buff == '':
break 回复 2# reyleon
经测可行。谢谢!
python 咋就这么复杂,实在是用不惯啊。{:yxh123:}
python subprocess在管道上面 不是那么用的哦..
页:
[1]