尝试通过运行 Tkinter 的发送进程在进程之间的管道发送任何内容时出现管道损坏错误

rba*_*dar 3 python tkinter pipe multiprocessing python-multiprocessing

我正在使用Pipe模块ProcessmultiprocessingPython 3.8)。我的初始程序如下所示:

from multiprocessing import Process, Pipe


class Process1(object):
    def __init__(self, pipe_out):
        self.pipe_out = pipe_out

        self.run()

    def run(self):
        try:
            while True:
                print("Sending message to process 2")
                self.pipe_out.send(["hello"])
        except KeyboardInterrupt:
            pass


class Process2(object):
    def __init__(self, pipe_in):
        self.pipe_in = pipe_in

        self.run()

    def run(self):
        try:
            while self.pipe_in.poll():
                request = self.pipe_in.recv()
                method = request[0]
                args = request[1:]

                try:
                    getattr(self, method + "_callback")(*args)
                except AttributeError as ae:
                    print("Unknown callback received from pipe", str(ae))

            print("Process 2 done with receiving")
        except KeyboardInterrupt:
            pass

    def hello_callback(self):
        print("Process 1 said hello")


class Controller(object):
    def __init__(self):
        pipe_proc1_out, pipe_proc2_in = Pipe()

        self.proc1 = Process(
            target=Process1,
            args=(pipe_proc1_out, )
        )

        self.proc2 = Process(
            target=Process2,
            args=(pipe_proc2_in, )
        )

    def run(self):
        try:
            self.proc1.start()
            self.proc2.start()

            while True:
                continue
        except KeyboardInterrupt:
            print("Quitting processes...")
            self.proc1.join(1)
            if self.proc1.is_alive():
                self.proc1.terminate()

            self.proc2.join(1)
            if self.proc2.is_alive():
                self.proc2.terminate()

            print("Finished")


def pipes():
    c = Controller()
    c.run()


if __name__ == "__main__":
    pipes()
Run Code Online (Sandbox Code Playgroud)

我有一个Controller实例一直运行直到收到键盘中断。它还处理两个进程Process1Process2前者不断发送,后者不断接收。

上面的代码是一个更大的项目的框架,涉及复杂的 GUI (PySide)、图像处理 (OpenCV) 和游戏引擎 (Panda3D)。所以我尝试添加 Tkinter 作为 GUI 示例:

from multiprocessing import Process, Pipe
import tkinter as tk


class Process1(tk.Frame):
    def __init__(self, pipe_out):
        self.pipe_out = pipe_out

        self.setup_gui()
        self.run()

    def setup_gui(self):
        self.app = tk.Tk()
        lb1 = tk.Label(self.app, text="Message:")
        lb1.pack()
        self.ent1 = tk.Entry(self.app)
        self.ent1.pack()
        btn1 = tk.Button(self.app, text="Say hello to other process",
                         command=self.btn1_clicked)
        btn1.pack()

    def btn1_clicked(self):
        msg = self.ent1.get()
        self.pipe_out.send(["hello", msg])

    def run(self):
        try:
            self.app.mainloop()
        except KeyboardInterrupt:
            pass


class Process2(object):
    def __init__(self, pipe_in):
        self.pipe_in = pipe_in

        self.run()

    def run(self):
        try:
            while self.pipe_in.poll():
                request = self.pipe_in.recv()
                method = request[0]
                args = request[1:]

                try:
                    getattr(self, method + "_callback")(*args)
                except AttributeError as ae:
                    print("Unknown callback received from pipe", str(ae))

            print("Process 2 done with receiving")
        except KeyboardInterrupt:
            pass

    def hello_callback(self, msg):
        print("Process 1 say\"" + msg + "\"")


class Controller(object):
    def __init__(self):
        pipe_proc1_out, pipe_proc2_in = Pipe()

        self.proc1 = Process(
            target=Process1,
            args=(pipe_proc1_out, )
        )

        self.proc2 = Process(
            target=Process2,
            args=(pipe_proc2_in, )
        )

    def run(self):
        try:
            self.proc1.start()
            self.proc2.start()

            while True:
                continue
        except KeyboardInterrupt:
            print("Quitting processes...")
            self.proc1.join(1)
            if self.proc1.is_alive():
                self.proc1.terminate()

            self.proc2.join(1)
            if self.proc2.is_alive():
                self.proc2.terminate()

            print("Finished")


def pipes():
    c = Controller()
    c.run()


if __name__ == "__main__":
    pipes()
Run Code Online (Sandbox Code Playgroud)

请注意,当前只有当“父”进程通过键盘中断时才能关闭 Tkinter 窗口。

每当我单击按钮并调用按钮的命令时,我的程序就会进入错误状态并显示以下消息:

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\USER\Anaconda3\envs\THS\lib\tkinter\__init__.py", line 1705, in __call__
    return self.func(*args)
  File "C:\Users\USER\PycharmProjects\PythonPlayground\pipes_advanced.py", line 26, in btn1_clicked
    self.pipe_out.send(["hello", 1, 2])
  File "C:\Users\USER\Anaconda3\envs\THS\lib\multiprocessing\connection.py", line 206, in send
    self._send_bytes(_ForkingPickler.dumps(obj))
  File "C:\Users\USER\Anaconda3\envs\THS\lib\multiprocessing\connection.py", line 280, in _send_bytes
    ov, err = _winapi.WriteFile(self._handle, buf, overlapped=True)
BrokenPipeError: [WinError 232] The pipe is being closed
Run Code Online (Sandbox Code Playgroud)

起初我认为问题在于我从通话中收到的值Entry.get()(我的 Tkinter 技能很生疏)。我打印msg并从小部件中获取了文本。

我尝试的下一步是将一个常量字符串作为我通过管道发送的参数的值:

def btn1_clicked(self):
    self.pipe_out.send(["hello", "world"])
Run Code Online (Sandbox Code Playgroud)

出现了同样的错误。捕获异常BrokenPipeError并没有真正给我带来任何好处(除非我想在管道损坏时处理这种情况,我猜)。

如果我对程序的第一个版本(没有 Tkinter)执行相同的操作,它就会起作用。这让我相信我的问题来自于我集成 Tkinter 的方式。

Mat*_*iss 5

您遇到的问题是您轮询管道,但文档说:

轮询([超时])

返回是否有数据可供读取。
如果未指定超时,则它将立即返回。

在第一个示例中它可以工作,因为启动时Process1您立即将数据发送到管道:

    def run(self):
        try:
            while True:
                print("Sending message to process 2")
                self.pipe_out.send(["hello"])
        except KeyboardInterrupt:
            pass
Run Code Online (Sandbox Code Playgroud)

并且您不断地执行此操作,因此.poll将返回True并且循环Process2将继续。

由于tkinter没有任何内容立即发送到管道,它会等待用户单击按钮,当任何一种情况发生时,已经Process2调用poll并立即返回False,甚至没有启动该循环。如果您注意到的话,它几乎也会立即在终端中打印:

“进程2完成接收”

要解决这个问题,最简单的似乎是使用

while self.pipe_in.poll(None):
Run Code Online (Sandbox Code Playgroud)

根据文档意味着

“如果超时为无,则使用无限超时。”

对于用户界面之类的东西,这似乎是最合适的(至少从用户的角度来看(或者我认为是这样))所以基本上你的run方法Process2应该如下所示:

    def run(self):
        try:
            while self.pipe_in.poll(None):
                request = self.pipe_in.recv()
                method = request[0]
                args = request[1:]

                try:
                    getattr(self, method + "_callback")(*args)
                except AttributeError as ae:
                    print("Unknown callback received from pipe", str(ae))

            print("Process 2 done with receiving")
        except (KeyboardInterrupt, EOFError):
            pass
Run Code Online (Sandbox Code Playgroud)

也与问题无关,但似乎没有必要从tk.Framein继承Process1(或objectin Process2(除非你真的需要使其与 Python2 兼容)),你几乎可以从 继承tk.Tk,这应该更容易实际使用它主窗口self将是Tk实例