You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python multiprocessing Manager使用报错:FileNotFoundError原因解析

问题分析:multiprocessing Manager 引发的 FileNotFoundError

问题复现

错误代码实现

from multiprocessing import Manager

class Queue:
    def __init__(self):
        self.manager = Manager()
        self.ls = self.manager.list()
        
    def clear(self):
        with Manager() as manager:
            self.ls = manager.list()

    @property
    def queue(self):
        return list(self.ls)

触发错误的测试代码

q = Queue()
q.clear()
print(q.queue)

报错信息

File "C:\Users\test.py", line 17, in queue
    return list(self.ls)
  File "<string>", line 2, in __len__
  File "E:\anaconda3\lib\multiprocessing\managers.py", line 806, in _callmethod
    self._connect()
  File "E:\anaconda3\lib\multiprocessing\managers.py", line 793, in _connect
    conn = self._Client(self._token.address, authkey=self._authkey)
  File "E:\anaconda3\lib\multiprocessing\connection.py", line 505, in Client
    c = PipeClient(address)
  File "E:\anaconda3\lib\multiprocessing\connection.py", line 707, in PipeClient
    _winapi.WaitNamedPipe(address, 1000)
FileNotFoundError: [WinError 2] The system cannot find the file specified

修正后的正常代码

仅修改clear方法:

def clear(self):
    self.ls = self.manager.list()

错误原因

  • with Manager() as manager是上下文管理器用法,代码块执行完毕后会自动终止当前Manager进程,并销毁该进程创建的所有共享对象的通信链路。
  • 当clear方法执行结束,with块退出,新创建的manager进程被关闭,此时self.ls指向的共享列表失去了背后的进程支持。
  • 后续调用q.queue尝试将self.ls转为普通列表时,需要连接对应的Manager进程,但该进程已经被销毁,系统找不到对应的通信管道,因此抛出FileNotFoundError。
  • 修正后的代码使用的是__init__方法中初始化的self.manager,这个Manager进程会伴随Queue实例的整个生命周期,新创建的共享列表能正常与进程通信,因此不会报错。

内容的提问来源于stack exchange,提问作者K.XGai

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 14:52:45