在 Python 中超时读取文件 [英] Read file with timeout in Python

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

问题描述

在 Linux 中,有一个文件,/sys/kernel/debug/tracing/trace_pipe,顾名思义,它是一个管道.因此,假设我想使用 Python 从中读取前 50 个字节 - 我运行以下代码:

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()<br>
<open file '/sys/kernel/debug/tracing/trace_pipe', mode 'r' at 0xb7757e90>

我们可以看到打开文件的速度很快(如果我们有超级用户权限) - 然而,如果 trace_pipe 文件在那个时刻是空的,它会简单地阻塞(即使有内容,内容将被转储,直到没有更多内容,然后文件将再次阻塞).然后我必须按 Ctrl-CKeyboardInterrupt...

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...

如何让 Python 2.7 读取超时?

也就是说,我要指示Python尝试从这个文件中读取50个字节;如果一秒后不成功,则放弃并返回"?

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"?

推荐答案

使用

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).

如果您没有没有可以从该管道中读取信息,这并不能解决您的问题.在这种情况下,您应该使用 select 模块中的 select测试是否有内容要阅读.

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.

使用 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

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

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