我的以下代码模拟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 greplc必须计算行数(如wc),并且必须在末尾返回它。我该怎么做呢?
发布于 2017-09-07 04:25:31
我不知道协程是可以关闭的。所以我的问题的解决方案是:
@coroutine
def lc(cible):
nl = 0
while True:
try:
nl += 1
line = yield
except GeneratorExit:
cible.send("{}".format(nl))
raise这需要在main中实现:
pipe.close()非常感谢你,RobertB!
https://stackoverflow.com/questions/46081190
复制相似问题