在Python中读取具有超时的文件 [英] Read file with timeout in 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 - C 用KeyboardInterrupt
...
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
来 test 进行读取.
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屋!