Python协同程序:它们为什么有用?有什么用例?

时间:2018-06-13 19:38:23

标签: python coroutine

我理解Python协同程序是消耗数据的生成器函数。 它们有用吗?你能给我一些用例吗?

以下是协同程序示例。

def match(pattern):
    print('Looking for ' + pattern)
    try:
        while True:
            s = (yield)
            print ("S is: {}".format(s))
            if pattern in s:
                print(s)
    except GeneratorExit:
        print("=== Done ===")


def read(text, next_coroutine):
    for line in text.split():
        next_coroutine.send(line)
    next_coroutine.close()



text = 'Commending spending is offending to people pending lending!'
matcher = match('ending')
matcher.__next__()
read(text, matcher)

0 个答案:

没有答案