我想在Windows上通过Manager()。Queue()发送在动态加载imp的模块中定义的数据。这可能吗?这是一个最小的测试用例来展示我的意思:
import imp
import sys
from multiprocessing import Manager
if __name__ == '__main__':
s = """
def payload():
print("It works!")
"""
mod = imp.new_module('testcase')
exec s in mod.__dict__
sys.modules['testcase'] = mod
payload = mod.payload
payload() # It works!
m = Manager()
queue = m.Queue()
queue.put(payload) # AttributeError: 'module' object has no attribute 'payload'
注意:使用imp.new_module + exec只是为了将测试用例放在一个文件中。使用imp.load_source时会引发相同的AttributeError。
注意2:此测试用例在此之前发生错误时会遗漏所有池/工作程序代码。
以下是运行上述脚本时带有完整回溯的输出:
It works!
Traceback (most recent call last):
File "testcase.py", line 23, in <module>
queue.put(payload) # AttributeError: 'module' object has no attribute 'payload'
File "<string>", line 2, in put
File "c:\Users\Andrew\dev\python\lib\multiprocessing\managers.py", line 774, in _callmethod
raise convert_to_error(kind, result)
multiprocessing.managers.RemoteError:
---------------------------------------------------------------------------
Traceback (most recent call last):
File "c:\Users\Andrew\dev\python\lib\multiprocessing\managers.py", line 240, in serve_client
request = recv()
AttributeError: 'module' object has no attribute 'payload'
---------------------------------------------------------------------------
谢谢!