解决Python多线程报错:AttributeError: Can't pickle local object

顾星河
顾星河
发布时间:2026-10-13 | 4人浏览过
原创

本文分析Python多线程编程中常见的AttributeError: Can't pickle local object错误。该错误通常由在类属性中初始化不可序列化的对象(如HTTPDigestAuth)引起。通过修改代码,将认证逻辑移至方法内部而非实例属性,可有效解决序列化失败问题,确保多线程池正常运行。

Python多线程序列化错误排查

报错信息如下所示:

Traceback (most recent call last): File “D:/flaskProject/test.py”, line 35, in test pool.apply(self.out, args=(i,)) File “Python37-32\lib\multiprocessing\pool.py", line 261, in apply return self.apply_async(func, args, kwds).get() File "\lib\multiprocessing\pool.py”, line 657, in get raise self._value File “\Python37-32\lib\multiprocessing\pool.py", line 431, in _handle_tasks put(task) File "\Python37-32\lib\multiprocessing\connection.py”, line 206, in send self._send_bytes(_ForkingPickler.dumps(obj)) File “*\Python37-32\lib\multiprocessing\reduction.py”, line 51, in dumps cls(buf, protocol).dump(obj) TypeError: can't pickle _thread._local objects

原始类的构造函数代码如下:


class threadtest:

def __init__(self, ipList, user, password):
 self.ipList = ipList
 self.httpAuth = HTTPDigestAuth(user, password)
 return

def out(self, i):
 url = "http://" + i + "/name"
 response = requests.get(url, self.httpAuth)
 print(response.text)
 return

def test(self):
 pool = Pool(processes=2)
 for i in self.ipList:
 pool.apply(self.out, args=(i,))
 pool.close()
 pool.join()
 return

if name == ‘main':
ipList = [‘192.168.2.1', ‘192.168.2.2', ‘192.168.2.3', ‘192.168.2.4', ‘192.168.2.5', ]
a = threadtest(ipList, ‘admin', ‘admin')
a.test()

错误原因与修复方案

问题原因分析:

在类的初始化过程中,使用了其他类返回的句柄对属性进行初始化,导致该属性无法被序列化。具体而言,HTTPDigestAuth的返回值不具备可序列化特性,因此无法作为cls(buf, protocol).dump(obj)的参数进行序列化操作。

将原代码中的self.httpAuth = HTTPDigestAuth(httpUser, httpPassword)修改为以下形式:

self.httpUser self.httpPassword

同时,需要将函数HTTPDigestAuth的调用移至类的方法内部执行。

修改后的代码如下:


class threadtest:

def __init__(self, ipList, user, password):
 self.ipList = ipList
 self.user = user
 self.password = password
 return

def out(self, i):
 url = "http://" + i + "/name"
 response = requests.get(url, HTTPDigestAuth(self.user, self.password))
 print(response.text)
 return

def test(self):
 pool = Pool(processes=2)
 for i in self.ipList:
 pool.apply(self.out, args=(i,))
 pool.close()
 pool.join()
 return

if name == ‘main':
ipList = [‘192.168.2.1', ‘192.168.2.2', ‘192.168.2.3', ‘192.168.2.4', ‘192.168.2.5', ]
a = threadtest(ipList, ‘admin', ‘admin')
a.test()

以上为解决Python多线程中AttributeError: Can't pickle local object错误的完整方案,希望对大家有所帮助。

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表