asyncioメモ

Debug *


asyncio.Protocol *

httpのプロトコルを実装するためのベースクラス
AbstractEventLoop.create_server()で使用する

asyncio.open_connection(host=None, port=None, *, loop=None, limit=None, **kwds)  *

asyncioのソケット


asyncio.gather(*coros_or_futures, loop=None, return_exceptions=False) *

与えられたコルーチンやFutrueを並列実行するFutureを返す

asyncio.Task(coro, *, loop=None) *

TaskはFutureのサブクラス

asyncio.CancelledError

asyncio.CancelledErrorはconcurrent.futures.CancelledErrorと同じクラスを参照している

import asyncio

async def sleep():
    try:
        await asyncio.sleep(3)
    except asyncio.CancelledError:
        print('cancaled')


def cancel():
    task.cancel()

task = asyncio.Task(sleep())

loop = asyncio.get_event_loop()
loop.call_later(1, cancel)
loop.run_until_complete(task)

# canceled


async for *

Asynchronous Iterators
aiter(self)
anext(self)

import asyncio


class Foo:
    def __init__(self):
        self.count = 0

    def __aiter__(self):
        return self

    async def __anext__(self):
        if self.count == 3:
            raise StopAsyncIteration
        await asyncio.sleep(1)
        self.count += 1
        return self.count


async def go():
    a = Foo()
    async for i in a:
        print(i)

loop = asyncio.get_event_loop()
loop.run_until_complete(go())

# 1
# 2
# 3


async with *

Asynchronous Context Managers
aenter(self)
aexit(self, exc_type, exc_value, traceback)

import asyncio


class Foo:
    async def __aenter__(self):
        print('start __aenter__')
        await asyncio.sleep(2)
        print('end __aenter__')

    async def __aexit__(self, exc_type, exc_value, traceback):
        print('start __aexit__')
        await asyncio.sleep(3)
        print('end __aexit__')


async def go():
    a = Foo()
    async with a as f:
            print('start')
            await asyncio.sleep(4)
            print('end')

loop = asyncio.get_event_loop()
loop.run_until_complete(go())

# start __aenter__
# end __aenter__
# start
# end
# start __aexit__
# end __aexit__