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>
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"?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…