我正在使用基于事件的系统,运用了新版 Python 3.5 中的协程和 await。我注册事件,并由系统调用这些事件。
@event
aysnc def handleevent(args):
# handle the event
我需要初始化一些类来处理工作(耗时)。然后调用实例方法,也很耗时(它们实际上使用Selenium浏览某些网站)。
理想情况下,我希望有以下代码:
# supposedly since this is multiprocessing this is a different driver per process
driver = None
def init():
# do the heavy initialization here
global driver
driver = webdriver.Chrome()
def longworkmethod():
## need to return some data
return driver.dolongwork()
class Drivers:
""" A class to handle async and multiprocessing"""
def __init__(self, numberOfDrivers):
self.pool = multiprocessing.Pool(processes=numberOfDrivers, initializer=init)
async def dowork(self, args):
return self.pool.apply_async(longworkmethod, args=args)
### my main python class
drivers = Drivers(5)
@event
aysnc def handleevent(args):
await drivers.dowork(args)
@event
aysnc def quit(args):
## do cleanup on drivers
sys.exit(0)
这段代码不起作用,但我已经尝试了很多不同的方法,都无法实现我想要的功能。
它不一定要是这个确切的形式,但如果程序需要多进程,我该如何混合使用 await 和协程?