Python:如何窥视pty对象以避免阻塞? [英] Python: How to peek into a pty object to avoid blocking?

查看:139
本文介绍了Python:如何窥视pty对象以避免阻塞?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用pty读取非阻塞这样的进程的标准输出:

I am using pty to read non blocking the stdout of a process like this:

import os
import pty
import subprocess

master, slave = pty.openpty()

p = subprocess.Popen(cmd, stdout = slave)

stdout = os.fdopen(master)
while True:
    if p.poll() != None:
        break

    print stdout.readline() 

stdout.close()

一切正常,除了while-loop偶尔会阻塞.这是由于行print stdout.readline()正在等待从stdout中读取内容的事实.但是,如果程序已经终止,那么我在那里的小脚本将永远挂起.

Everything works fine except that the while-loop occasionally blocks. This is due to the fact that the line print stdout.readline() is waiting for something to be read from stdout. But if the program already terminated, my little script up there will hang forever.

我的问题是:是否可以窥视stdout对象并检查是否有可读取的数据?如果不是这种情况,则应继续执行while-loop,在该地方将发现进程实际上已经终止并中断了循环.

My question is: Is there a way to peek into the stdout object and check if there is data available to be read? If this is not the case it should continue through the while-loop where it will discover that the process actually already terminated and break the loop.

推荐答案

是的,请使用选择模块的投票:

import select
q = select.poll()
q.register(stdout,select.POLLIN)

并在一段时间内使用:

l = q.poll(0)
if not l:
    pass # no input
else:
    pass # there is some input

这篇关于Python:如何窥视pty对象以避免阻塞?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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