【问题标题】:Select on multiple pipes在多个管道上选择
【发布时间】:2014-01-24 00:42:17
【问题描述】:

我有多个管道(双向)。我需要的是等到这些管道中的任何一个出现任何对象。不幸的是,当我尝试做这样的事情时:

from multiprocess import Pipe
import select

class MyClass:
    def __init__(self, pipe1, pipe2):
        self.__my_pipes = [pipe1, pipe2]

    def run(self):
        while 1:
            ready, _, _ = select.select(self.__my_pipes, [], [])
            #and some stuff

我遇到了错误

OSError: [WinError 10038] an operation was attempted on something that is not a socket

MyClass 的构造函数是这样调用的:

pipe1, pipe2 = Pipe()
pipe3, pipe4 = Pipe()
obj = MyClass(pipe1, pipe3)

根据文档,select.select 需要整数(文件描述符)或具有无参数函数 fileno() 的对象(使用 Pipe() 创建的 Connection 对象具有)。我什至尝试过这样做:

w, r = os.pipe()
read, _, _ = select.select([w, r], [], [])

但错误是一样的。有什么想法吗?

编辑

是的,目前我正在使用 Windows,但看起来我必须更改平台...感谢您的回答。我有这样的想法,在 Windows 上,这些文件描述符可能不起作用,但我不确定。现在我明白了。谢谢!

【问题讨论】:

    标签: python python-3.x multiprocessing pipe


    【解决方案1】:

    可以使用管道自带的函数poll或者它的变量可读可写

    pipe1.poll()
    pipe1.writable
    pipe1.readable
    

    不一样,但这样的代码可以做你想做的事:

    def return_pipes(pipes):
        readable = []
        writable = []
        for pipe in pipes:
            if pipe.readable:
                readable.append(pipe)
            if pipe.writable:
                writable.append(pipe)
        return(readable,writable)
    
    readable,writable = return_pipes([pipe1,pipe2])
    

    “可读”和“可写”将是带有可读取或可写管道的列表。你可以扩展这个函数,让它做更多你想做的事情,或者只是对函数进行多次迭代。

    【讨论】:

      【解决方案2】:

      您是否在 Windows 上运行?

      The docs say:

      Windows 上的文件对象是不可接受的,但套接字是可接受的。在 Windows 上,底层的 select() 函数由 WinSock 库提供,并且不处理并非源自 WinSock 的文件描述符。

      老实说,我不知道如何从适用于 Windows 的标准库中进行轮询/选择。可能Python for Windows Extensions 提供了一个很好的WaitForMultipleObjects 包装器。

      【讨论】:

        【解决方案3】:

        您正在调用 select(),并使用包含 multiprocessing 使用的 Connection 对象的数组。 (顺便说一句,你在源代码中写了multiprocess,但我想应该是multiprocessing。)但是select() 无法处理这些。

        尝试改用pipe1.fileno() 等;这是一个文件编号(一个 int),select 完全可以处理这些。

        编辑:

        如果您在 Windows 上工作,select() 不支持文件编号(运气不好)。那时我无能为力。除非您愿意使用多线程并且每件事都有一个线程等待;这也应该适用于 Windows。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-09-24
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多