【问题标题】:How properly abort a python coroutine in an infinite loop?如何在无限循环中正确中止 python 协程?
【发布时间】:2017-09-06 17:31:21
【问题描述】:

我的以下代码模拟 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)并且必须在最后返回它。 我该怎么做?

【问题讨论】:

  • 您需要某种方式在您的协议中指示文件结束;也许通过发送None 的值。当收到 EOF 时,管道中的每个阶段都需要跳出无限循环,然后将自己的 EOF 发送到下一个阶段。
  • 您可以关闭协程。您是否尝试过关闭管道并从 lc 中捕获“GeneratorExit”以打印您的结果?

标签: python coroutine


【解决方案1】:

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

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

这需要主要:

pipe.close()

非常感谢罗伯特!

【讨论】:

    猜你喜欢
    • 2013-11-19
    • 1970-01-01
    • 2018-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多