在多个管道上选择

2024-09-30 01:30:11 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

我弄错了

^{pr2}$

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

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

根据文件,选择。选择需要int(文件描述符)或具有无参数函数fileno()的对象(使用Pipe()创建的连接对象已获得)。我甚至尝试过:

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

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

编辑

是的,目前我正在Windows上工作,但看起来我必须改变平台。。。谢谢你的回答。我有这样的想法,在Windows上那些文件描述符可能不起作用,但我不确定。现在我知道了。谢谢!在


Tags: 文件对象importself管道mydefmyclass
3条回答

您正在使用一个包含Connection对象的数组调用select(),该数组由multiprocessing使用。(顺便说一句,您在源代码中编写multiprocess,但我想应该是multiprocessing。)select(),但是不能处理这些问题。在

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

编辑:

如果您在windows上工作,select()不支持文件号(运气不好)。那我就忍不住了。除非您愿意使用多线程处理,并为每件事情提供一个线程,否则这在Windows上也应该有效。在

你在运行Windows吗?在

The docs say

File objects on Windows are not acceptable, but sockets are. On Windows, the underlying select() function is provided by the WinSock library, and does not handle file descriptors that don’t originate from WinSock.

老实说,我不知道从Windows上运行的标准库中进行轮询/选择的任何东西。可能Python for Windows Extensions提供了一个很好的WaitForMultipleObjects包装。在

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

pipe1.poll()
pipe1.writable
pipe1.readable

这不一样,但是像这样的代码可以做你想要的:

^{pr2}$

“readable”和“writable”将是包含可读或可写管道的列表。你可以扩展函数使它做更多你想做的事情,或者只是多次迭代函数。在

相关问题 更多 >

    热门问题