python 获取键盘输入、同时有超时的功能_在Python中读取具有超时的文件

Within Linux, there is a file, /sys/kernel/debug/tracing/trace_pipe, which as the name says, is a pipe. So, let's say I want to read the first 50 bytes from it using Python - and I run the following code:

$sudo python -c 'f=open("/sys/kernel/debug/tracing/trace_pipe","r"); print f; print f.read(50); f.close()

We can see that opening the file goes fast ( if we have the superuser permissions ) - however, if the trace_pipe file is empty at that moment, it will simply block ( and even if there is content, the content will be dumped until there is no more, and then again the file will block ). Then I have to press Ctrl-C to interrupt the Python script with a KeyboardInterrupt...

How can I have Python 2.7 do a read with timeout?

That is, I want to instruct Python to "try read 50 bytes from this file; if you don't succeed after one second, give up and return"?

解决方案

Use

os.read(f.fileno(), 50)

instead. That does not wait until the specified amount of bytes has been read but returns when it has read anything (at most the specified amount of bytes).

This does not solve your issue in case you've got nothing to read from that pipe. In that case you should use select from the module select to test whether there is something to read.

EDIT:

Testing for empty input with select:

import select

r, w, e = select.select([ f ], [], [], 0)

if f in r:

print os.read(f.fileno(), 50)

else:

print "nothing available!" # or just ignore that case

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值