defgrep(pattern): print("Looking for {}".format(pattern)) whileTrue: line = yield if pattern in line: print('{} : grep success '.format(line))
>>> g=grep('python') # 还是个生成器 >>> g <generator object grep at 0x7f17e86f3780> # 激活协程!只能用一次,也可以用g.send(None)来代替next(g) >>> next(g) Looking for python # 使用.send(...)发送数据,发送的数据会成为生成器函数中yield表达式值,即变量line的值 >>> g.send("Yeah, but no, but yeah, but no")
defcoroutine(func): defprimer(*args,**kwargs): cr = func(*args,**kwargs) next(cr) return cr return primer
@coroutine defgrep(pattern): ...
2.4 关闭一个协程
一个协程有可能永远运行下去
可以 .close()让它停下来 例子中已经体现,不展开。
2.5 捕捉close()
1 2 3 4 5 6 7 8 9
defgrep(pattern): print("Looking for {}".format(pattern)) try: whileTrue: line = yield if pattern in line: print(line) except GeneratorExit: print("Going away. Goodbye")
捕捉到.close()方法,然后会打印"Going away. Goodbye"。
2.6 抛出异常
1 2 3 4 5 6 7 8 9 10 11
>>> g = grep("python") >>> next(g) # Prime it Looking for python >>> g.send("python generators rock!") python generators rock! : grep success >>> g.throw(RuntimeError,"You're hosed") Traceback (most recent call last): ..... ..... RuntimeError: You're hosed >>>
defgrep(pattern): print("Looking for {}".format(pattern)) whileTrue: line = yield # 当发送的数据为None时,跳出while循环 if line isNone: break else: if pattern in line: print('{} : grep success '.format(line)) return'End'