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())