【发布时间】: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”以打印您的结果?