如何连接不断生成和使用数据的asyncio.coroutines?

时间:2015-03-29 00:40:09

标签: python python-3.4 python-asyncio

我正在尝试学习如何(惯用)使用Python 3.4' asyncio。我最大的绊脚石是如何"链"协同程序,它不断消耗数据,用它更新状态,并允许该状态被另一个协程使用。

我期望从这个示例程序中观察到的可观察行为只是定期报告从子进程接收的数字总和。报告应该以与Source对象从子进程接收数字大致相同的速率发生。报告功能中的IO阻塞不应阻止从子进程读取。如果报告功能阻止的时间长于从子进程读取的迭代次数,我不在乎它是否会向前跳过或立即报告一堆;但在足够长的时间内,reporter()的{​​{1}}迭代次数应该与expect_exact()一样多。

#!/usr/bin/python3
import asyncio
import pexpect

class Source:

    def __init__(self):
        self.flag = asyncio.Event()
        self.sum = 0

    def start(self):
        self.flag.set()

    def stop(self):
        self.flag.clear()

    @asyncio.coroutine
    def run(self):
        yield from self.flag.wait()

        p = pexpect.spawn(
            "python -c "
            "'import random, time\n"
            "while True: print(random.choice((-1, 1))); time.sleep(0.5)'")

        while self.flag.is_set():
            yield from p.expect_exact('\n', async=True)
            self.sum += int(p.before)

        p.terminate()

@asyncio.coroutine
def reporter(source):
    while True:
        # Something like:
        new_sum = yield from source # ???
        print("New sum is: {:d}".format(new_sum))
        # Potentially some other blocking operation
        yield from limited_throughput.write(new_sum)

def main():
    loop = asyncio.get_event_loop()

    source = Source()
    loop.call_later(1, source.start)
    loop.call_later(11, source.stop)

    # Again, not sure what goes here...
    asyncio.async(reporter(source))

    loop.run_until_complete(source.run())
    loop.close()

if __name__ == '__main__':
    main()

此示例需要从git安装pexpect;您可以轻松地将run()替换为:

@asyncio.coroutine
def run(self):
    yield from self.flag.wait()

    while self.flag.is_set():
        value = yield from asyncio.sleep(0.5, random.choice((-1, 1)))
        self.sum += value

但我感兴趣的真正的子流程需要在pty中运行,我认为这意味着asyncio中提供的子流程传输/协议框架不够为了这。关键是异步活动的来源是一个可以与yield from一起使用的协程。

请注意,此示例中的reporter()函数不是有效代码;我的问题是我不知道应该去哪里。理想情况下,我希望将reporter()代码与run()分开;这个问题的关键在于看看如何使用asyncio中的组件将更复杂的程序分解为更小的代码单元。

有没有办法用asyncio模块构建这种行为?

1 个答案:

答案 0 :(得分:5)

asyncio中的锁定原语和队列本身提供了一些执行此操作的机制。

条件

asyncio.Condition()提供了一种通知条件的方法。如果丢弃某些事件并不重要,请使用此选项。

class Source:

    def __init__(self):
        self.flag = asyncio.Event()
        self.sum = 0

        # For consumers
        self.ready = asyncio.Condition()

    def start(self):
        self.flag.set()

    def stop(self):
        self.flag.clear()

    @asyncio.coroutine
    def run(self):
        yield from self.flag.wait()

        p = pexpect.spawn(
            "python -c "
            "'import random, time\n"
            "while True: print(random.choice((-1, 1))); time.sleep(0.5)'")

        while self.flag.is_set():
            yield from p.expect_exact('\n', async=True)
            self.sum += int(p.before)
            with (yield from self.ready):
                self.ready.notify_all() # Or just notify() depending on situation

        p.terminate()

    @asyncio.coroutine
    def read(self):
        with (yield from self.ready):
            yield from self.ready.wait()
            return self.sum


@asyncio.coroutine
def reporter(source):
    while True:
        # Something like:
        new_sum = yield from source.read()
        print("New sum is: {:d}".format(new_sum))
        # Other potentially blocking stuff in here

队列

asyncio.Queue()允许您将数据放入队列(LIFO或FIFO)并从中读取其他内容。如果您绝对想要回复每个事件,即使您的消费者落后(及时),请使用此选项。请注意,如果限制队列的大小,如果您的消费者足够慢,您的生产者最终会阻止。

请注意,这允许我们将sum转换为本地变量。

#!/usr/bin/python3
import asyncio
import pexpect

class Source:

    def __init__(self):
        self.flag = asyncio.Event()
        # NOTE: self.sum removed!

        # For consumers
        self.output = asyncio.Queue()

    def start(self):
        self.flag.set()

    def stop(self):
        self.flag.clear()

    @asyncio.coroutine
    def run(self):
        yield from self.flag.wait()

        sum = 0

        p = pexpect.spawn(
            "python -c "
            "'import random, time\n"
            "while True: print(random.choice((-1, 1))); time.sleep(0.5)'")

        while self.flag.is_set():
            yield from p.expect_exact('\n', async=True)
            sum += int(p.before)
            yield from self.output.put(sum)

        p.terminate()

    @asyncio.coroutine
    def read(self):
        return (yield from self.output.get())

@asyncio.coroutine
def reporter(source):
    while True:
        # Something like:
        new_sum = yield from source.read()
        print("New sum is: {:d}".format(new_sum))
        # Other potentially blocking stuff here

请注意,Python 3.4.4将task_done()join()方法添加到Queue,以便在您知道消费者完成后(适用时)优雅地完成所有内容的处理。