为什么写这个coroutine呢?因为,在第一次send一个非None的值的时候,会出现异常。
这个异常是,TypeError: can't send non-None value to a just-started generator。
为了避免以后忘掉这个第一个send(None),所以写了这个。
def coroutine(func):
def inner(*args,**kwargs):
f=func(*args,**kwargs)
next(f)
return f
return inner
@coroutine
def grep(pattern):
print("Looking for %s"%pattern)
# try:
while True:
line =yield
if pattern in line:
print(line)
break
return '--done--'
g=grep('hudahai')
('hutiankong')
try:
("hudahai is a handsome boy")
except StopIteration as s:
print(s.__repr__())