另一种方法是使用 loop.run_in_executor() 函数。 这是在低级异步 API 中,首先需要访问事件循环,例如通过 asyncio.get_running_loop() 函数。 loop.run_in_executor() 函数接受一个执行器和一个要执行的函数。 如果没有为执行器提供,则使用默认执行器,即 ThreadPoolExecutor。 loop.run_in_executor() 函数返...
deflong_blocking_function(): print(time.time()) time.sleep(2) returnTrue asyncdefrun(): loop=asyncio.get_event_loop() # 新建线程池 pool=ThreadPoolExecutor() # 任务列表 tasks=[loop.run_in_executor(pool, long_blocking_function), loop.run_in_executor(pool, long_blocking_function)] # 等待...
In[37]:defa():...:time.sleep(1)...:return'A'...:In[38]:asyncdefc():...:loop=asyncio.get_running_loop()...:returnawaitloop.run_in_executor(None,a)...:In[39]:asyncio.run(c())Out[39]:'A' 上面使用run_in_executor可以将同步函数a以协程的方式执行,我们看下源码 defrun_in_exe...
这意味着它不包含在asyncio.run()中被取消的“活跃任务”集合中,因此在asyncio.run()中调用的run_until_complete()不用等待执行器任务完成。在asyncio.run()中调用内部loop.close()会引发RuntimeError。 在写这本书的时候,Python 3.8中的loop.close()并不等待所有执行器作业完成,这就是为什么从run_in_executor(...
底层函数返回Future对象的一个例子是:loop.run_in_executor 执行asyncio程序 1 asyncio.run(coro, * , debug=False) 这个函数运行coro参数指定的协程,负责管理asyncio事件循环,终止异步生成器。 在同一个线程中,当已经有asyncio事件循环在执行时,不能调用此函数。
asyncio.run(main()) print(f'Done in {time.time() - start_time} seconds') # Output: Done in 0.2990539073944092 seconds 该异步版本无需等待。在获取一个页面的同时,它会开始获取下一个页面,从而大大缩短了总等待时间。 并发读取文件(I/O 任务) ...
loop = asyncio.get_running_loop() fut = loop.create_future() await fut asyncio.run(main()) 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 示例2:增加一个任务,2s 后把 future 对象终止 import asyncio async def set_result(fut): await asyncio.sleep(2) ...
任务在由get_running_loop()返回的事件循环(loop)中执行。如果当前线程中没有正在运行的事件循环,将会引发RuntimeError异常: importasyncioasyncdefcoro_1():print("do somthing")task=asyncio.create_task(coro_1()) 因为当前线程中没有正运行的事件循环,所以引发异常: ...
get_running_loop()) asyncio.run(main()) 执行结果如下: <_WindowsSelectorEventLoop running=True closed=False debug=False> something is running 此函数已经被引入到Python3.7。在Python早期版本中,可以使用底层函数asyncio.ensure_future()代替。 async def coro(): ... # In Python 3.7+ task = ...
defsync_task():print("Starting a slow sync task...")time.sleep(5)# 模拟长时间任务print("Finished the slow task.")asyncdefasync_wrapper():loop=asyncio.get_running_loop()awaitloop.run_in_executor(None,sync_task)asyncdefmain():awaitasyncio.gather(async_wrapper(),# 想象一下其他异步任务)asy...