我正在使用基于事件的系统,该系统使用新的 Python 3.5 协程和等待。我注册事件,这些事件由系统调用。
@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)
这段代码不起作用,但我尝试了很多不同的方法,但似乎都无法做到我想要的。
它不一定是这种精确的形式,但我如何将等待和协程与需要多处理的程序混合在一起?
最佳答案
虽然从技术上讲没有什么会限制您混合 asyncio
和 multiprocessing
,但我建议避免这样做。这会增加很多复杂性,因为您最终需要每个线程一个事件循环,并且来回传递信息将很棘手。只需使用其中之一即可。
asyncio
提供在另一个线程中运行任务的函数 - 例如 AbstractEventLoop.run_in_executor
。看看这些答案
- https://stackoverflow.com/a/33025287/66349 (在协程中调用 Selenium)
- https://stackoverflow.com/a/28492261/66349
或者,您可以只使用multiprocessing
,因为selenium具有阻塞(非异步)接口(interface),但是听起来您的某些代码已经在使用asyncio
,所以也许坚持与上述。
关于Python多处理连续处理与await,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43080185/