如何在 python3 中使用 pathos 而不是 multiprocessing 模块实现非守护进程?
更具体地说,我指的是: Python Process Pool non-daemonic?
这篇文章的答案是通过多处理模块实现非守护进程。不幸的是,这个模块不允许在其他对象中腌制 lambda 函数,但 pathos 在 Python 2 中可以:
#import multiprocessing
#import multiprocessing.pool
import pathos
#class NoDaemonProcess(multiprocessing.Process):
class NoDaemonProcess(pathos.multiprocessing.Pool.Process):
def _get_daemon(self):
return False
def _set_daemon(self, value):
pass
daemon = property(_get_daemon, _set_daemon)
#class NoDaemonPool(multiprocessing.pool.Pool):
class NoDaemonPool(pathos.multiprocessing.Pool):
Process = NoDaemonProcess
def myproc(args):
i, max_workers = args
#pool = multiprocessing.Pool(max_workers)
pool = pathos.pools.ProcessPool(max_workers)
l_args = [j for j in range(i)]
mysubproc = lambda x : x
print("myproc", l_args, pool.map(mysubproc, l_args))
return i
max_workers = [2, 1]
executor = NoDaemonPool(max_workers[0])
#executor = pathos.multiprocessing.Pool(max_workers[0])
l_args = [(i, max_workers[1]) for i in range(10)]
print(executor.map(myproc, l_args))
输出:
('myproc', [], [])
('myproc', [0, 1], [0, 1])
('myproc', [0], [0])
('myproc', [0, 1, 2], [0, 1, 2])
('myproc', [0, 1, 2, 3], [0, 1, 2, 3])
('myproc', [0, 1, 2, 3, 4, 5], [0, 1, 2, 3, 4, 5])
('myproc', [0, 1, 2, 3, 4], [0, 1, 2, 3, 4])
('myproc', [0, 1, 2, 3, 4, 5, 6], [0, 1, 2, 3, 4, 5, 6])
('myproc', [0, 1, 2, 3, 4, 5, 6, 7], [0, 1, 2, 3, 4, 5, 6, 7])
('myproc', [0, 1, 2, 3, 4, 5, 6, 7, 8], [0, 1, 2, 3, 4, 5, 6, 7, 8])
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
在 Python 3 中,pathos 模块相对于 Python 2 发生了变化,例如 pathos.multiprocessing.Pool.Process 不再是一个类,而是一个函数,因此不能再将它用于继承(见上文)。- 我缺少任何悲伤的文档吗?
如何使上述代码在 Python 3 中的 pathos 中工作?
作为上述特定示例的一种解决方法,可以简单地回退到多处理 NoDaemonPool 实现,并为守护程序子进程使用 pathos:
import multiprocessing
import multiprocessing.pool
import pathos
class NoDaemonProcess(multiprocessing.Process):
#class NoDaemonProcess(pathos.multiprocessing.Pool.Process):
def _get_daemon(self):
return False
def _set_daemon(self, value):
pass
daemon = property(_get_daemon, _set_daemon)
class NoDaemonPool(multiprocessing.pool.Pool):
#class NoDaemonPool(pathos.multiprocessing.Pool):
Process = NoDaemonProcess
def myproc(args):
i, max_workers = args
#pool = multiprocessing.Pool(max_workers)
pool = pathos.pools.ProcessPool(max_workers)
l_args = [j for j in range(i)]
mysubproc = lambda x : x
print("myproc", l_args, pool.map(mysubproc, l_args))
return i
max_workers = [2, 1]
executor = NoDaemonPool(max_workers[0])
#executor = pathos.multiprocessing.Pool(max_workers[0])
l_args = [(i, max_workers[1]) for i in range(10)]
print(executor.map(myproc, l_args))
然而,这种变通方法不是一个解决方案,因为 (i) 它同时导入了 pathos 和 multiprocessing,更重要的是 (ii) 它不能腌制,例如,如果 myproc 被定义为
myproc = lambda x : x
非常感谢,最好的,塞巴斯蒂安