继承时断言错误multiprocessing.Process

Assertion error when inheriting multiprocessing.Process

我需要一个单独的进程来在初始化时打开一些文件并在结束时轻轻地关闭它们。为此,我从Process继承了一个class。这是一个最小的演示:

from multiprocessing import Process
from multiprocessing.process import BaseProcess

class Proxy(Process):
    def __init__(self):
        super().__init__(self)
    def run(self):
        pass

if __name__ == "__main__":
    proxy = Proxy()
    proxy.start()
    proxy.join()

使用这段代码我得到一个断言异常:

Traceback (most recent call last):
  File "mp_proxy.py", line 11, in <module>
    proxy = Proxy()
  File "mp_proxy.py", line 6, in __init__
    super().__init__(self)
  File "/home/user/opt/anaconda3/lib/python3.7/multiprocessing/process.py", line 74, in __init__
    assert group is None, 'group argument must be None for now'
AssertionError: group argument must be None for now

如果将 Process 替换为 BaseProcess,也会发生同样的情况。接下来我在 process.py 中添加了一个调试打印到 BaseProcess.__init__ 函数,只是为了查看 group 变量,然后我得到了一些不同的东西:

multiprocessing.process : Traceback (most recent call last):
  File "mp_proxy.py", line 11, in <module>
    proxy = Proxy()
  File "mp_proxy.py", line 6, in __init__
    super().__init__(self)
  File "/home/user/opt/anaconda3/lib/python3.7/multiprocessing/process.py", line 74, in __init__
    print(__name__, ":", group)
  File "/home/user/opt/anaconda3/lib/python3.7/multiprocessing/process.py", line 254, in __repr__
    elif self._closed:
AttributeError: 'Proxy' object has no attribute '_closed'

问题是:如何正确继承Process?可能是我拿的概念错了?

早些时候,在另一个 post 'Error group argument must be None for now in multiprocessing.pool' 中描述了类似的错误,但是我没有看到问题的解决方案。据我了解,该行为高度依赖于 Python 子版本。一点都不酷

P.S.: Ubuntu 20.04, Anaconda 3 与 Python 3.7.6.

应该是super().__init__()而不是super().__init__(self)

super() 在这种情况下转换为 super(Proxy, self),已经将超级对象绑定到您的 Proxy-实例。您 在超级对象上调用 方法,就像您总是使用方法一样, 没有 显式传递 self.

groupBaseProcess.__init__(self, group=None, target=None...) 中的第二个参数,在您的代码中调用 super().__init__(self),您将其设置为 self,因此 AssertionError.