如何检查 stdin 是否有一些数据? [英] How do I check if stdin has some data?

查看:46
本文介绍了如何检查 stdin 是否有一些数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Python 中,如何检查 sys.stdin 是否有数据?

In Python, how do you check if sys.stdin has data or not?

我发现 os.isatty(0) 不仅可以检查 stdin 是否连接到 TTY 设备,还可以检查是否有可用数据.

I found that os.isatty(0) can not only check if stdin is connected to a TTY device, but also if there is data available.

但是如果有人使用诸如

sys.stdin = cStringIO.StringIO("ddd")

然后使用os.isatty(0),它仍然返回True.我需要做什么来检查 stdin 是否有数据?

and after that uses os.isatty(0), it still returns True. What do I need to do to check if stdin has data?

推荐答案

在 Unix 系统上,您可以执行以下操作:

On Unix systems you can do the following:

import sys
import select

if select.select([sys.stdin,],[],[],0.0)[0]:
    print "Have data!"
else:
    print "No data"

在 Windows 上,select 模块只能与套接字一起使用,因此您需要使用替代机制.

On Windows the select module may only be used with sockets though so you'd need to use an alternative mechanism.

这篇关于如何检查 stdin 是否有一些数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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