Python子进程读取 [英] Python subprocess reading

查看:47
本文介绍了Python子进程读取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有这个代码

<块引用>

p = subprocess.Popen('tail -f/var/log/syslog', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)对于 p.stdout.readlines() 中的行:印刷线,时间.睡眠(1)

即使我向 syslog 添加内容,脚本也会挂起并且不写任何行.

为什么?

解决方案

readlines() 不会返回,直到进程出现 eof,这不会发生,因为 tail 在没有中断的情况下永远不会结束.

您可以将循环更改为:

虽然为真:打印(p.stdout.readline())

除非您希望每行之间有一个额外的 1 秒间隔,否则不需要睡眠,因为 readline 会阻塞,使用最少的资源,直到有完整的行可用.

Having this code

p = subprocess.Popen('tail -f /var/log/syslog', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

for line in p.stdout.readlines():
    print line,
    time.sleep(1)

The script hangs and does not write any lines even if I add something to syslog.

Why?

解决方案

readlines() will not return until there is an eof on the process, which there won't be as tail never finishes without an interrupt.

You could change your loop to:

while True:
    print(p.stdout.readline())

Unless you want an additional 1s gap between each line., there is no need for a sleep as readline will block, using minimal resources, until there is a full line available.

这篇关于Python子进程读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆