【メモ】Pythonの非同期I/Oライブラリ「asyncio」について触ってみる

はじめに

こんにちは、がんがんです。
Pythonの非同期I/Oライブラリasyncioについて調査を行ったので備忘録としてまとめておきます。
今回はメモ的な内容です。

目的

  • 非同期I/Oのasyncioについて調査および実験してみる
  • まずは試してみる

簡単な実験

import time
import asyncio

async def waiter(name):
    for _ in range(3):
        await asyncio.sleep(1)
        print(f"{name}は1秒待ちました")

async def main():
    await asyncio.wait([waiter("aomame"), waiter("tengo")])

if __name__ == "__main__":
    start = time.time()
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())
    loop.close()
    print(f"time:{time.time() - start}")

future

import asyncio
import sys
from random import randint

def random_hit(future, n_upper, cnt=1, loop=None):
    # n_upper = n
    if loop is None:
        loop = asyncio.get_event_loop()
    value = randint(1, n_upper)
    #print(value)

    if value == n_upper:
        print("Hit!")
        future.set_result(cnt)
    else:
        print("Not yet.")
        cnt += 1
        loop.call_soon(random_hit, future, n_upper, cnt, loop)

def _callback(future):
    print("DONE!")
    loop = asyncio.get_event_loop()

def eternal_hello(loop):
    print("Hello!")
    loop.call_soon(eternal_hello, loop)

def ojama(loop):
    print("こんにちは")
    loop.call_soon(ojama, loop)


try:
    n = int(sys.argv[1])
except IndexError:
    print("Input an integer.")
    n = int(input())
if n < 1:
    n = 1

#  メイン
loop = asyncio.get_event_loop()
future = loop.create_future()
future.add_done_callback(_callback)

#loop.call_soon(ojama, loop)
loop.call_soon(random_hit, future, n)
loop.call_soon(eternal_hello, loop)
result = loop.run_until_complete(future)
print("{}回".format(result))
loop.close()

おわりに

今回はPythonの非同期I/Oライブラリasyncioを試してみました。