【问题标题】:Python multiprocessing continuous processing with awaitPython多处理连续处理与等待
【发布时间】:2017-03-28 21:22:17
【问题描述】:

我正在使用基于事件的系统,该系统使用新的 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)

此代码不起作用,但我尝试了许多不同的方法,但似乎没有一个能够做我想做的事。

它不必是这种精确的形式,但是我如何将 await 和 coroutines 与需要多处理的程序混合?

【问题讨论】:

    标签: python selenium async-await multiprocessing python-3.5


    【解决方案1】:

    虽然从技术上讲,没有什么会限制您混合 asynciomultiprocessing,但我建议避免这样做。这会增加很多复杂性,因为您最终需要每个线程都有一个事件循环,并且来回传递信息会很棘手。只需使用其中一种。

    asyncio 提供用于在另一个线程中运行任务的函数 - 例如AbstractEventLoop.run_in_executor。看看这些答案

    或者,您也可以只使用 multiprocessing,因为 selenium 有一个阻塞(非异步)接口,但听起来您的某些代码已经在使用 asyncio,所以可能坚持以上。

    【讨论】:

    • 我无法避免混合,因为我需要 selenium(多处理),而且我使用的事件系统是严格异步的。但我会检查这些链接。看看我能不能让它们工作。
    • selenium 是阻塞的,但这并不意味着你需要多处理。只需将run_in_executor 用于阻塞位,并将其他所有内容保留在主线程/事件循环中。
    • 所以这些链接似乎有帮助。我应该将 run_in_executor 用于诸如“get”之类的单个昂贵调用,还是可以使用多个昂贵调用执行大型昂贵函数?会有区别吗?
    • @leftsync 这取决于您的通话结构。它们可以同时运行还是需要按顺序运行?你可以支持多少个线程?硒线程安全吗?
    猜你喜欢
    • 1970-01-01
    • 2014-01-21
    • 2020-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-20
    相关资源
    最近更新 更多