首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在无限循环中正确地中止python协程?

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

Stack Overflow用户
提问于 2017-09-07 01:31:22
回答 1查看 147关注 0票数 0

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

代码语言:javascript
复制
@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)

例如:

代码语言:javascript
复制
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)

提供:

代码语言:javascript
复制
it's an new string
whitespaces for grep

lc必须计算行数(如wc),并且必须在末尾返回它。我该怎么做呢?

EN

回答 1

Stack Overflow用户

发布于 2017-09-07 04:25:31

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

代码语言:javascript
复制
@coroutine
def lc(cible):
  nl = 0  
  while True:
      try:
        nl += 1  
        line = yield
      except GeneratorExit:
        cible.send("{}".format(nl))
        raise

这需要在main中实现:

代码语言:javascript
复制
pipe.close()

非常感谢你,RobertB!

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46081190

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档