pickle.PicklingError:无法腌制<function func =“” at =“” 0x02b3c1b0 =“”>:找不到它是__main __。func

时间:2018-09-11 12:14:08

标签: python multiprocessing pickle python-multiprocessing

test.py和main.py在同一个文件夹中,我执行main.py,解释器报告以下错误。

Python环境:python2.7.15

如何解决此问题?

Google告诉我,此问题已在python3.4中修复,但我想在python 2.7中使用此样式,该怎么做 test.py

from multiprocessing import Process, Queue
def interaction(q):
    print '*'*50
    q.put('-'*50)
q = Queue()

p = Process(target=interaction, args=(q,))
p.start()
p.join()
print q.get()

main.py

if __name__ == '__main__':

    execfile('test.py')

错误:

Traceback (most recent call last):
  File "C:\sync360\code\python\oobe_test\multiprocessing_test\demorund\main.py", line 3, in <module>
    execfile('test.py')
  File "test.py", line 13, in <module>
    main()
  File "test.py", line 10, in main
    p.start()
  File "C:\Python27\lib\multiprocessing\process.py", line 130, in start
    self._popen = Popen(self)
  File "C:\Python27\lib\multiprocessing\forking.py", line 277, in __init__
    dump(process_obj, to_child, HIGHEST_PROTOCOL)
  File "C:\Python27\lib\multiprocessing\forking.py", line 199, in dump
    ForkingPickler(file, protocol).dump(obj)
  File "C:\Python27\lib\pickle.py", line 224, in dump
    self.save(obj)
  File "C:\Python27\lib\pickle.py", line 331, in save
    self.save_reduce(obj=obj, *rv)
  File "C:\Python27\lib\pickle.py", line 425, in save_reduce
    save(state)
  File "C:\Python27\lib\pickle.py", line 286, in save
    f(self, obj) # Call unbound method with explicit self
  File "C:\Python27\lib\pickle.py", line 655, in save_dict
    self._batch_setitems(obj.iteritems())
  File "C:\Python27\lib\pickle.py", line 687, in _batch_setitems
    save(v)
  File "C:\Python27\lib\pickle.py", line 286, in save
    f(self, obj) # Call unbound method with explicit self
  File "C:\Python27\lib\pickle.py", line 754, in save_global
    (obj, module, name))
pickle.PicklingError: Can't pickle <function func at 0x02B3C1B0>: it's not found as __main__.func
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "C:\Python27\lib\multiprocessing\forking.py", line 381, in main
    self = load(from_parent)
  File "C:\Python27\lib\pickle.py", line 1384, in load
    return Unpickler(file).load()
  File "C:\Python27\lib\pickle.py", line 864, in load
    dispatch[key](self)
  File "C:\Python27\lib\pickle.py", line 886, in load_eof
    raise EOFError
EOFError
[Finished in 0.3s with exit code 1]

1 个答案:

答案 0 :(得分:0)

我的直觉是使用execfile()导致了这一点,因为它使Python了解__main__是什么。

您可以导入test模块(顺便说一句,应将其重命名为更具描述性的模块)。