程序与python,但得到一个错误_pickle.PicklingError

时间:2017-01-17 02:27:07

标签: python python-3.x

我写了下面的代码:

import random, time, queue
from multiprocessing.managers import BaseManager

task_queue = queue.Queue()
result_queue = queue.Queue()

class QueueManager(BaseManager):
    pass

QueueManager.register('get_task_queue', callable=lambda: task_queue)
QueueManager.register('get_result_queue', callable=lambda: result_queue)

manager = QueueManager(address=('', 5000), authkey=b'abd')

manager.start()

task = manager.get_task_queue()
result = manager.get_result_queue()

for i in range(10):
    n = random.randint(0, 10000)
    print('Put task %d...' % n)
    task.put(n)

print('Try get result...')
for i in range(10):
    r = result.get(timeout=10)
    print('Result: %s' % r)

manager.shutdown()
print('master exit.')

但是当它运行时,我收到此错误:

Traceback (most recent call last):
  File "D:/PycharmProjects/test/task_master.py", line 23, in <module>
    manager.start()
  File "C:\Users\tang_ke\AppData\Local\Programs\Python\Python35-32\lib\multiprocessing\managers.py", line 479, in start
    self._process.start()
  File "C:\Users\tang_ke\AppData\Local\Programs\Python\Python35-32\lib\multiprocessing\process.py", line 105, in start
    self._popen = self._Popen(self)
  File "C:\Users\tang_ke\AppData\Local\Programs\Python\Python35-32\lib\multiprocessing\context.py", line 313, in _Popen
    return Popen(process_obj)
  File "C:\Users\tang_ke\AppData\Local\Programs\Python\Python35-32\lib\multiprocessing\popen_spawn_win32.py", line 66, in __init__
    reduction.dump(process_obj, to_child)
  File "C:\Users\tang_ke\AppData\Local\Programs\Python\Python35-32\lib\multiprocessing\reduction.py", line 59, in dump
    ForkingPickler(file, protocol).dump(obj)
_pickle.PicklingError: Can't pickle <function <lambda> at 0x03A67C48>: attribute lookup <lambda> on __main__ failed

Process finished with exit code 1

1 个答案:

答案 0 :(得分:2)

我在网站上得到了答案:讨论 - 廖雪峰的官方网站

第1步: 不要在“QueueManager.register”中使用“lambda”,你必须替换一个函数,例如:

def return_task_queue():
    global task_queue
    return task_queue

QueueManager.register('get_task_queue', callable=return_task_queue)

第2步: 您必须在创建“QueueManager”时添加IPAddress,例如:

QueueManager(address=('127.0.0.1', 5000), authkey=b'abc')

第3步: 你必须把所有关于queuemanager和task的函数放到一个函数中......例如:

def test():
    QueueManager.register('get_task_queue', callable=return_task_queue)
    QueueManager.register('get_result_queue', callable=return_result_queue)
    manager = QueueManager(address=('127.0.0.1', 5000), authkey=b'abc')
    manager.start()
    ....

你必须在MAIN功能中使用“test”功能,例如:

if __name__  == '__main__':
    test()