【问题标题】:Python anonymous pipe set timeoutPython匿名管道设置超时
【发布时间】:2012-07-30 19:52:33
【问题描述】:

我觉得这不可能;但是有没有办法在 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() 方法)

【问题讨论】:

    标签: python linux ipc pipe


    【解决方案1】:

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

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

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

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

    【讨论】:

    • 也许我遗漏了一些简单的东西,但select 会告诉我何时有活动(我计划使用的东西)——但不会帮助我弄清楚管道中有多少数据.因此,没有正确大小的read() 只会等到 EOF。我希望有一种方法来创建超时,如果我读取的字节数多于管道中的字节数,我就无法永远阻塞。任何人都知道multiprocesssubprocess 模块如何在不深入研究代码的情况下管理它? (可能有帮助的冒险)
    • read() 将返回管道中的当前数据量。在缓冲区满之前它不会阻塞,除非你再次调用它。
    • 哦。您可能应该在管道上使用 os.read() ,而不是对其进行 fdopen 。将其视为文件对象会使您受制于 Python 缓冲的奇思妙想。
    • 不幸的是,它不会返回缓冲区中的所有内容。我试过了,帮助页面上写着read([size]) -> read at most size bytes, returned as a string. If the size argument is negative or omitted, read until EOF is reached. Notice that when in non-blocking mode, less data than what was requested may be returned, even if no size parameter was given.
    • 啊! os.read() 有帮助!谢谢(为此效果创建一个答案,以便我可以选择它 - 即使它没有回答所提出的问题:p)
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-07-04
      • 1970-01-01
      • 1970-01-01
      • 2011-06-16
      • 2012-11-25
      • 1970-01-01
      • 2023-03-26
      相关资源
      最近更新 更多