Jac*_*nor 5 python python-asyncio
我想编写一个使用 asyncio 管理子进程的库。我不想强迫我的调用者自己异步,所以我更愿意先得到一个new_event_loop,做一个run_until_complete,然后close它。理想情况下,我希望在不与调用者可能正在执行的任何其他异步操作发生冲突的情况下执行此操作。
我的问题是等待子进程不起作用,除非你调用set_event_loop,它附加了内部观察者。但当然,如果我这样做,我可能会与调用者中的其他事件循环发生冲突。一种解决方法是缓存调用者的当前循环(如果有),然后set_event_loop在我完成恢复调用者的状态后再调用一次。这几乎有效。但是如果调用者不是 asyncio 用户,调用的副作用get_event_loop是我现在创建了一个以前不存在的全局循环,如果程序退出而不调用close该循环,Python 将打印一个可怕的警告。
我能想到的唯一元解决方法是执行atexit.register关闭全局循环的回调。这不会与调用者冲突,因为 close 调用多次是安全的,除非调用者做了一些疯狂的事情,比如在退出期间尝试启动全局循环。所以它仍然不完美。
有没有完美的解决方案?
您想要实现的目标看起来非常像ProcessPoolExecutor(在并发.futures中)。
异步调用者:
@coroutine
def in_process(callback, *args, executor=ProcessPoolExecutor()):
loop = get_event_loop()
result = yield from loop.run_in_executor(executor, callback, *args)
return result
Run Code Online (Sandbox Code Playgroud)
同步调用者:
with ProcessPoolExecutor() as executor:
future = executor.submit(callback, *args)
result = future.result()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
363 次 |
| 最近记录: |