简体   繁体   English

如何在无限循环中异常终止Python协程?

[英]How properly abort a python coroutine in an infinite loop?

My following code simulate UNIX pipes : 我的以下代码模拟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)

For example : 例如 :

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)

gives : 给出:

it's an new string
whitespaces for grep

lc must count the lines (like wc) and must return it at the end. lc必须计算行数(如wc),并且必须在最后将其返回。 How can I do this ? 我怎样才能做到这一点 ?

I didn't know than a coroutine can be closed. 我不知道协程可以关闭。 So the solution of my problem is : 所以我的问题的解决方案是:

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

and this needs in main : 这主要需要:

pipe.close()

Thanks you very much RobertB ! 非常感谢RobertB!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM