使用 python.multiprocessing,如何在当前进程中创建代理以传递给其他进程?
我正在使用 Python 中的multiprocessing
库。我可以看到如何定义从函数返回的对象应该创建代理,但我希望将当前进程中的对象转换为代理,以便我可以将它们作为参数传递。
例如,运行以下脚本:
from multiprocessing import current_process
from multiprocessing.managers import BaseManager
class ProxyTest(object):
def call_a(self):
print 'A called in %s' % current_process()
def call_b(self, proxy_test):
print 'B called in %s' % current_process()
proxy_test.call_a()
class MyManager(BaseManager):
pass
MyManager.register('proxy_test', ProxyTest)
if __name__ == '__main__':
manager = MyManager()
manager.start()
pt1 = ProxyTest()
pt2 = manager.proxy_test()
pt1.call_a()
pt2.call_a()
pt1.call_b(pt2)
pt2.call_b(pt1)
...我得到以下输出...
A called in <_MainProcess(MainProcess, started)>
A called in <Process(MyManager-1, started)>
B called in <_MainProcess(MainProcess, started)>
A called in <Process(MyManager-1, started)>
B called in <Process(MyManager-1, started)>
A called in <Process(MyManager-1, started)>
...但我希望输出的最后一行来自 _MainProcess
。
我可以创建另一个进程并从那里运行它,但我试图将需要在进程之间传递的数据量保持在最低限度。 Manager
对象的文档提到了 serve_forever
方法,但它似乎不受支持。有什么想法吗? 有谁知道吗?
I'm using the multiprocessing
library in Python. I can see how to define that objects returned from functions should have proxies created, but I'd like to have objects in the current process turned into proxies so I can pass them as parameters.
For example, running the following script:
from multiprocessing import current_process
from multiprocessing.managers import BaseManager
class ProxyTest(object):
def call_a(self):
print 'A called in %s' % current_process()
def call_b(self, proxy_test):
print 'B called in %s' % current_process()
proxy_test.call_a()
class MyManager(BaseManager):
pass
MyManager.register('proxy_test', ProxyTest)
if __name__ == '__main__':
manager = MyManager()
manager.start()
pt1 = ProxyTest()
pt2 = manager.proxy_test()
pt1.call_a()
pt2.call_a()
pt1.call_b(pt2)
pt2.call_b(pt1)
... I get the following output ...
A called in <_MainProcess(MainProcess, started)>
A called in <Process(MyManager-1, started)>
B called in <_MainProcess(MainProcess, started)>
A called in <Process(MyManager-1, started)>
B called in <Process(MyManager-1, started)>
A called in <Process(MyManager-1, started)>
... but I want that final line of output coming from _MainProcess
.
I could just create another Process and run it from there, but I'm trying to keep the amount of data that needs to be passed between processes to a minimum. The documentation for the Manager
object mentioned a serve_forever
method, but it doesn't seem to be supported. Any ideas?
Does anyone know?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
为什么说不支持serve_forever?
应该有效。
请参阅managers.BaseManager.get_server 官方示例文档。
Why do you say serve_forever is not supported?
should work.
See managers.BaseManager.get_server doc for official examples.