Python匿名管道设置超时

时间:2012-07-30 19:52:33

标签: python linux ipc pipe

我感觉不可能;但有没有办法在Linux上的Python / C中的匿名管道上设置读取超时?

有没有比设置和捕获SIGALRM更好的选择?

>>> import os
>>> output, input = os.pipe()
>>> outputfd = os.fdopen(output, 'r')
>>> dir(outputfd)
['__class__', '__delattr__', '__doc__', '__enter__', '__exit__', '__format__', '__getattribute__', '__hash__', '__init__', '__iter__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'close', 'closed', 'encoding', 'errors', 'fileno', 'flush', 'isatty', 'mode', 'name', 'newlines', 'next', 'read', 'readinto', 'readline', 'readlines', 'seek', 'softspace', 'tell', 'truncate', 'write', 'writelines', 'xreadlines']
>>> 

(没有settimeout()方法)

2 个答案:

答案 0 :(得分:4)

您应该尝试使用select模块,它允许您提供超时。将文件对象添加到选择集,然后检查返回对象以查看它是否已更改:

r, w, x = select.select([output], [], [], timeout)

然后检查r以查看对象是否可读。这可以扩展到您想要监视的任意数量的对象。如果对象在r中,则执行read:output.read()

此外,您可能希望使用os.read而不是fdopen,因为它不会受到Python文件缓冲的影响。

答案 1 :(得分:0)

这不是直接设置,但您可以在文件描述符上使用select来等待输入。它是一个内置模块,支持Unix上的所有文件描述符,但只支持OpenVMS和Windows上的套接字(来自select上的pydoc页面)。

相关问题