生成器send,throw,close示例,加yield运用场景与协程关系

from collections.abc import Generator
from collections.abc import Iterator
import sys
def intNum():
    print("开始执行")
    for i in range(5):
        yield i
        print("继续执行")
num = intNum()

# 生成器send用法
#第一次一定要传入None
# print(num.send(None))
# while True:
#     try:
#         print(num.send(999))
#     except StopIteration:
#         exc_type, exc_value, exc_tb = sys.exc_info()
#         print('异常追踪信息:%s' % exc_tb)
#         break

#生成器throw用法
# ret=next(num)
# print(ret)
# try:
#     ret2 = num.throw(ZeroDivisionError)  # ret2 并没有收到任何值
# except ZeroDivisionError:
#     print('调用方捕获到 ZeroDivisionError 异常')
#     print(sys.exc_info())
# # 因为赋值没有发生就抛出了异常,所以变量 ret2 还不存在
# try:
#     print(ret2)
# except NameError:
#     print('捕获到了 NameError')
#     print(sys.exc_info())
#
# print()
# print('尝试再次从生成器中获取值')
# print(next(num))

#生成器close用法
# print(next(num))
# a=num.close()
# print(a)


Python 的关键字 yield 有哪些用法和用途? - 知乎
上下文管理器
from contextlib import contextmanager

@contextmanager
def managed_file(name):
    try:
        f = open(name, 'w')
        yield f
    finally:
        f.close()

class ManagedFile:
    def __init__(self, name):
        self.name = name

    def __enter__(self):
        self.file = open(self.name, 'w')
        return self.file

    def __exit__(self, exc_type, exc_val, exc_tb):
        if self.file:
            self.file.close()

with ManagedFile('hello.txt') as f:
    f.write('hello, world!')
    f.write('bye now')

with managed_file('hello.txt') as f:
    f.write('hello, world!')
    f.write('bye now')

#协程

from collections import deque

# Two simple generator functions
def countdown(n):
    while n > 0:
        print('T-minus', n)
        yield
        n -= 1
    print('Blastoff!')

def countup(n):
    x = 0
    while x < n:
        print('Counting up', x)
        yield
        x += 1

def create_break():
    x = 0
    while x < 100:
        print('破坏', x)
        yield
        x += 1

class TaskScheduler:
    def __init__(self):
        self._task_queue = deque()

    def new_task(self, task):
        '''
        Admit a newly started task to the scheduler

        '''
        self._task_queue.append(task)

    def run(self):
        '''
        Run until there are no more tasks
        '''
        while self._task_queue:
            task = self._task_queue.popleft()
            try:
                # Run until the next yield statement
                a=next(task)
                self._task_queue.append(task)
            except StopIteration:
                # Generator is no longer executing
                pass

# Example use
sched = TaskScheduler()
sched.new_task(countdown(20))
sched.new_task(countup(10))
sched.new_task(create_break())
sched.run()

#asyncio写的协程任务

import asyncio

async def countdown(n):
    while n > 0:
        print('T-minus', n)
        await asyncio.sleep(0)
        n -= 1
    print('Blastoff!')

async def countup(n):
    x = 0
    while x < n:
        print('Counting up', x)
        await asyncio.sleep(0)
        x += 1

async def main():
    await asyncio.gather(countdown(1000), countup(500))

asyncio.run(main())

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值