如何在无限循环中正确中止python协程?

时间:2017-09-06 17:31:22

标签: python coroutine

我的以下代码模拟UNIX管道:

@coroutine
def grep(cible,motif):
    while True:
        line = yield
        if motif in line:
            cible.send("{}".format(line))

@coroutine
def subst(cible,old,new):
    while True:
        line = yield
        line=line.replace(old,new)
        cible.send("{}".format(line))

@coroutine
def lc(cible):
    nl = 0  
    while True:
            line = yield
            cible.send("{}".format(line))
    print(nl) # obvously not like that ! But how ??

@coroutine
def echo():
    while True:
        line = yield
        print(line)

例如:

pipe = grep(subst(lc(echo()),"old","new")," ")
for line in ["wathever","it's an old string","old_or_new","whitespaces for grep"]:
    pipe.send(line)

给出:

it's an new string
whitespaces for grep

lc必须计算行数(如wc)并且必须在结尾处返回它。 我怎么能这样做?

1 个答案:

答案 0 :(得分:0)

我不知道可以关闭一个协程。所以解决我的问题是:

@coroutine
def lc(cible):
  nl = 0  
  while True:
      try:
        nl += 1  
        line = yield
      except GeneratorExit:
        cible.send("{}".format(nl))
        raise

这需要在main:

pipe.close()

非常感谢RobertB!