继承多进程时发生断言错误。进程

2024-09-27 21:23:27 发布

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

我需要一个单独的过程,在初始化时打开一些文件,最后轻轻地关闭它们。为此,我从Process继承了一个类。下面是一个简单的演示:

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'

问题是:如何以适当的方式继承流程?也许我的想法是错误的

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

附言:Ubuntu 20.04,Anaconda3和Python 3.7.6


Tags: inpyselfnoneinitlinegroupmp
1条回答
网友
1楼 · 发布于 2024-09-27 21:23:27

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

在本例中^{}转换为super(Proxy, self),已经将超级对象绑定到Proxy-实例。您可以对超级对象调用方法,就像对方法一样,不显式地传递self

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

相关问题 更多 >

    热门问题