完整官网asyncio协程学习

简介: 完整官网asyncio协程学习

代码有点多,我都注释过了,该文章仅协程部分,python官网入门教程的化请看我github:python3.9入门教程

群:970353786

代码有点多,不懂可群问我,下面是协程方面的代码demo:

"""
作者:杨涵x
时间:2021/4/30
"""
# import asyncio
# async def main():
#     print('Hello ...')
#     await asyncio.sleep(1)
#     print('... World!')
# asyncio.run(main())
'''等待 1 秒后打印 "hello",然后 再次 等待 2 秒后打印 "world"'''
# import asyncio
# import time
#
# async def say_after(delay, what):
#     await asyncio.sleep(delay)
#     print(what)
# async def main():
#     print(f"started at {time.strftime('%X')}")
#     await say_after(1, 'hello')
#     await say_after(2, 'world')
#     print(f"finished at {time.strftime('%X')}")
# asyncio.run(main())
'''asyncio.create_task() 函数用来并发运行作为 asyncio 任务 的多个协程。'''
# async def main():
#     task1 = asyncio.create_task(
#         say_after(1, 'hello'))
#     task2 = asyncio.create_task(
#         say_after(2, 'world'))
#     print(f"started at {time.strftime('%X')}")
#     # Wait until both tasks are completed (should take
#     # around 2 seconds.)
#     await task1
#     await task2
#
#     print(f"finished at {time.strftime('%X')}")
# asyncio.run(main())
'''Python 协程属于 可等待 对象,因此可以在其他协程中被等待'''
# import asyncio
#
# async def nested():
#     return 42
#
# async def main():
#     # Nothing happens if we just call "nested()".
#     # A coroutine object is created but not awaited,
#     # so it *won't run at all*.
#     # Let's do it differently now and await it:
#     print(await nested())  # will print "42".
#
# asyncio.run(main())
'''
协程函数: 定义形式为 async def 的函数;
协程对象: 调用 协程函数 所返回的对象。
'''
'''当一个协程通过 asyncio.create_task() 等函数被封装为一个 任务,该协程会被自动调度执行'''
# import asyncio
#
# async def nested():
#     return 42
#
# async def main():
#     # Schedule nested() to run soon concurrently
#     # with "main()".
#     task = asyncio.create_task(nested())
#
#     # "task" can now be used to cancel "nested()", or
#     # can simply be awaited to wait until it is complete:
#     await task
# asyncio.run(main())
'''运行 asyncio 程序'''
'''asyncio.run(coro, *, debug=False)¶'''
# import asyncio
# async def main():
#     await asyncio.sleep(1)
#     print('hello')
#
# asyncio.run(main())
'''创建任务'''
'''asyncio.create_task(coro, *, name=None)¶'''
# import asyncio
# async def coro():
#     return 2021
# task = asyncio.create_task(coro())#python3.7+
# This works in all Python versions but is less readable
# task = asyncio.ensure_future(coro())#before python3.7
'''休眠'''
''' asyncio.sleep(delay, result=None, *, loop=None)¶'''
'''以下协程示例运行 5 秒,每秒显示一次当前日期'''
# import asyncio
# import datetime
#
# async def display_date():
#     loop = asyncio.get_running_loop()
#     end_time = loop.time() + 5.0
#     while True:
#         print(datetime.datetime.now())
#         if (loop.time() + 1.0) >= end_time:
#             break
#         await asyncio.sleep(1)
#
# asyncio.run(display_date())
'''并发运行任务'''
''' asyncio.gather(*aws, loop=None, return_exceptions=False)¶'''
# import asyncio
#
# async def factorial(name, number):
#     f = 1
#     for i in range(2, number + 1):
#         print(f"Task {name}: Compute factorial({i})...")
#         await asyncio.sleep(1)
#         f *= i
#     print(f"Task {name}: factorial({number}) = {f}")
#
# async def main():
#     # Schedule three calls *concurrently*:
#     await asyncio.gather(
#         factorial("A", 2),
#         factorial("B", 3),
#         factorial("C", 4),
#     )
#
# asyncio.run(main())
'''屏蔽取消操作'''
'''asyncio.shield(aw, *, loop=None)保护一个 可等待对象 防止其被 取消'''
# res = await shield(something())#demo
'''如果希望完全忽略取消操作 (不推荐) 则 shield() 函数需要配合一个 try/except 代码段'''
# try:
#     res = await shield(something())
# except CancelledError:
#     res = None
'''超时'''
'''asyncio.wait_for(aw, timeout, *, loop=None)¶'''
# import asyncio
# async def eternity():
#     # Sleep for one hour
#     await asyncio.sleep(3600)
#     print('yay!')
#
# async def main():
#     # Wait for at most 1 second
#     try:
#         await asyncio.wait_for(eternity(), timeout=1.0)
#     except asyncio.TimeoutError:
#         print('timeout!')
#
# asyncio.run(main())
'''简单等待'''
'''syncio.wait(aws, *, loop=None, timeout=None, return_when=ALL_COMPLETED)'''
# 用法:
# import asyncio
# done, pending = await asyncio.wait(aws)
# async def foo():
#     return 42
#
# task = asyncio.create_task(foo())
# done, pending = await asyncio.wait({task})
#
# if task in done:
#     asyncio.run(task)
#     # Everything will work as expected now.
'''在线程中运行'''
'''asyncio.to_thread(func, /, *args, **kwargs)在不同的线程中异步地运行函数 func。'''
'''这个协程函数主要是用于执行在其他情况下会阻塞事件循环的 IO 密集型函数/方法'''
# import asyncio,time
# def blocking_io():
#     print(f"start blocking_io at {time.strftime('%X')}")
#     # Note that time.sleep() can be replaced with any blocking
#     # IO-bound operation, such as file operations.
#     time.sleep(1)
#     print(f"blocking_io complete at {time.strftime('%X')}")
#
# async def main():
#     print(f"started main at {time.strftime('%X')}")
#
#     await asyncio.gather(
#         asyncio.to_thread(blocking_io),
#         asyncio.sleep(1))
#     print(f"finished main at {time.strftime('%X')}")
# asyncio.run(main())
''':要取消一个正在运行的 Task 对象可使用 cancel() 方法。调用此方法将使该 Task 对象抛出一个 CancelledError 异常给打包的协程'''
'''以下示例演示了协程是如何侦听取消请求的'''
# import asyncio
# async def cancel_me():
#     print('cancel_me(): before sleep')
#
#     try:
#         # Wait for 1 hour
#         await asyncio.sleep(3600)
#     except asyncio.CancelledError:
#         print('cancel_me(): cancel sleep')
#         raise
#     finally:
#         print('cancel_me(): after sleep')
#
# async def main():
#     # Create a "cancel_me" Task
#     task = asyncio.create_task(cancel_me())
#
#     # Wait for 1 second
#     await asyncio.sleep(1)
#
#     task.cancel()
#     try:
#         await task
#     except asyncio.CancelledError:
#         print("main(): cancel_me is cancelled now")
#
# asyncio.run(main())
'''基于生成器的协程'''
'''@asyncio.coroutine
用来标记基于生成器的协程的装饰器。
此装饰器使得旧式的基于生成器的协程能与 async/await 代码相兼容
'''
# import asyncio
# @asyncio.coroutine
# def old_style_coroutine():
#     yield from asyncio.sleep(1)
#
# async def main():
#     await old_style_coroutine()
'''队列能被用于多个的并发任务的工作量分配:'''
import asyncio
import random
import time
async def worker(name, queue):
    while True:
        # Get a "work item" out of the queue.
        sleep_for = await queue.get()
        # Sleep for the "sleep_for" seconds.
        await asyncio.sleep(sleep_for)
        # Notify the queue that the "work item" has been processed.
        queue.task_done()
        print(f'{name} has slept for {sleep_for:.2f} seconds')
async def main():
    # Create a queue that we will use to store our "workload".
    queue = asyncio.Queue()
    # Generate random timings and put them into the queue.
    total_sleep_time = 0
    for _ in range(20):
        sleep_for = random.uniform(0.05, 1.0)
        total_sleep_time += sleep_for
        queue.put_nowait(sleep_for)
    # Create three worker tasks to process the queue concurrently.
    tasks = []
    for i in range(3):
        task = asyncio.create_task(worker(f'worker-{i}', queue))
        tasks.append(task)
    # Wait until the queue is fully processed.
    started_at = time.monotonic()
    await queue.join()
    total_slept_for = time.monotonic() - started_at
    # Cancel our worker tasks.
    for task in tasks:
        task.cancel()
    # Wait until all worker tasks are cancelled.
    await asyncio.gather(*tasks, return_exceptions=True)
    print('====')
    print(f'3 workers slept in parallel for {total_slept_for:.2f} seconds')
    print(f'total expected sleep time: {total_sleep_time:.2f} seconds')
asyncio.run(main())


相关文章
|
7月前
|
数据采集 关系型数据库 MySQL
python-协程(async、await关键字与asyncio)
python-协程(async、await关键字与asyncio)
516 0
|
2月前
|
前端开发 Java API
vertx学习总结5之回调函数及其限制,如网关/边缘服务示例所示未来和承诺——链接异步操作的简单模型响应式扩展——一个更强大的模型,特别适合组合异步事件流Kotlin协程
本文是Vert.x学习系列的第五部分,讨论了回调函数的限制、Future和Promise在异步操作中的应用、响应式扩展以及Kotlin协程,并通过示例代码展示了如何在Vert.x中使用这些异步编程模式。
51 5
vertx学习总结5之回调函数及其限制,如网关/边缘服务示例所示未来和承诺——链接异步操作的简单模型响应式扩展——一个更强大的模型,特别适合组合异步事件流Kotlin协程
|
2月前
|
调度 Python
python知识点100篇系列(20)-python协程与异步编程asyncio
【10月更文挑战第8天】协程(Coroutine)是一种用户态内的上下文切换技术,通过单线程实现代码块间的切换执行。Python中实现协程的方法包括yield、asyncio模块及async/await关键字。其中,async/await结合asyncio模块可更便捷地编写和管理协程,支持异步IO操作,提高程序并发性能。协程函数、协程对象、Task对象等是其核心概念。
|
3月前
|
调度 开发者 Python
探索Python中的异步编程:理解asyncio和协程
【9月更文挑战第22天】在现代软件工程中,异步编程是提升应用性能的关键技术之一。本文将深入探讨Python语言中的异步编程模型,特别是asyncio库的使用和协程的概念。我们将了解如何通过事件循环和任务来处理并发操作,以及如何用协程来编写非阻塞的代码。文章不仅会介绍理论知识,还会通过实际的代码示例展示如何在Python中实现高效的异步操作。
|
3月前
|
数据采集
爬虫之协程异步 asyncio和aiohttp
爬虫之协程异步 asyncio和aiohttp
|
3月前
|
开发者 Python
探索Python中的异步编程:理解Asyncio和协程
【9月更文挑战第18天】在Python的世界中,异步编程是一个强大而神秘的概念。它像是一把双刃剑,掌握得好可以大幅提升程序的效率和性能;使用不当则可能让代码变得难以维护和理解。本文将带你一探究竟,通过深入浅出的方式介绍Python中asyncio库和协程的基本概念、使用方法及其背后的原理,让你对异步编程有一个全新的认识。
|
4月前
|
大数据 API 调度
Python中的异步编程:理解asyncio模块与协程
在现代编程中,异步编程越来越重要,特别是在处理大规模并发任务时。Python的asyncio模块提供了强大的工具来实现异步操作,其中协程是其核心机制之一。本文将深入探讨asyncio模块的基本概念、如何编写和管理异步任务,以及协程的工作原理和实际应用。
|
5月前
|
存储 调度 Python
异步编程概述在 Python中,`asyncio`库提供了对异步I/O、事件循环、协程(coroutine)和任务的支持。
异步编程概述在 Python中,`asyncio`库提供了对异步I/O、事件循环、协程(coroutine)和任务的支持。
|
6月前
|
JavaScript 前端开发 程序员
Python协程与asyncio
理解Python中的协程,我们需从其底层原理开始,逐步深入。协程的核心在于控制流的非阻塞式管理,它允许在单一线程内实现并发处理,通过事件循环和协作式多任务来提高效率。
|
7月前
|
调度 Python
python协程—asyncio模块
python协程—asyncio模块
67 0