只需将其添加为注释,以便更好地格式化:
@Alfe 在我的情况下的回答:
$ sudo python -c 'import os, select;
f=open("/sys/kernel/debug/tracing/trace_pipe","r"); print f;
rrdy, wrdy, xrdy = select.select([f], [], [], 1); print rrdy, wrdy, xrdy ;
timeout= "timed out" if (rrdy==[]) else "" ;
print timeout;
print os.read(f.fileno(), 50) if timeout=="" else "";
f.close() '
如果文件中有内容,我会得到如下响应:
<open file '/sys/kernel/debug/tracing/trace_pipe', mode 'r' at 0xb76f0e90>
[<open file '/sys/kernel/debug/tracing/trace_pipe', mode 'r' at 0xb76f0e90>] [] []
Xorg-1033 [001] 12570.075859: <user s
如果文件中没有任何内容,我会得到:
<open file '/sys/kernel/debug/tracing/trace_pipe', mode 'r' at 0xb7831e90>
[] [] []
timed out
请注意,select 文档并未明确指出 timeout 参数以秒为单位 - 但浮点值(例如 0.5)也可以使用。
@GabiMe 的回答:
$ sudo python -c 'import os;
filno = os.open("/sys/kernel/debug/tracing/trace_pipe", os.O_RDONLY|os.O_NONBLOCK);
f=os.fdopen(filno, "r"); print f;
print "A", f.read(50);
print "B", os.read(f.fileno(), 50);
f.close() '
如果文件中有内容,我会得到如下响应:
<open file '<fdopen>', mode 'r' at 0xb77b6e90>
A bash-13777 [000] 13694.404519: sys_exi
B Timer-31065 [001] 13694.404830: sys_exi
如果文件中没有任何内容,我会得到:
<open file '<fdopen>', mode 'r' at 0xb77c1e90>
A
Traceback (most recent call last):
File "<string>", line 1, in <module>
IOError: [Errno 11] Resource temporarily unavailable
...所以必须在try 块中运行它,以捕获IOError,如果文件中没有任何内容...(os.read 和f.read 都会引发此异常)