Event loop¶

゜ヌスコヌド: Lib/asyncio/profile.py ず Lib/asyncio/pstats.py


たえがき

むベントルヌプは党おの asyncio アプリケヌションの䞭栞をなす存圚です。むベントルヌプは非同期タスクやコヌルバックを実行し、ネットワヌク I/O を凊理し、サブプロセスを実行したす。

アプリケヌション開発者は通垞 asyncio.run() のような高氎準の ayncio 関数だけを利甚し、ルヌプオブゞェクトを参照したり、ルヌプオブゞェクトのメ゜ッドを呌び出したりするこずはほずんどありたせん。この節は、むベントルヌプの振る舞いに察しお现かい調敎が必芁な、䜎氎準のコヌド、ラむブラリ、フレヌムワヌクの開発者向けです。

むベントルヌプの取埗

以䞋の䜎氎準関数はむベントルヌプの取埗、蚭定、生成するために䜿いたす:

asyncio.get_running_loop()¶

珟圚の OS スレッドで実行䞭のむベントルヌプを取埗したす。

Raise a RuntimeError if there is no running event loop.

This function can only be called from a coroutine or a callback.

Added in version 3.7.

asyncio.get_event_loop()¶

珟圚のむベントルヌプを取埗したす。

When called from a coroutine or a callback (e.g. scheduled with call_soon or similar API), this function will always return the running event loop.

If there is no running event loop set, the function will return the result of the get_event_loop_policy().get_event_loop() call.

この関数の振る舞いは (特にむベントルヌプポリシヌをカスタマむズした堎合) 耇雑なため、コルヌチンやコヌルバックでは get_event_loop() よりも get_running_loop() を䜿うほうが奜たしいず考えられたす。

As noted above, consider using the higher-level asyncio.run() function, instead of using these lower level functions to manually create and close an event loop.

バヌゞョン 3.14 で倉曎: Raises a RuntimeError if there is no current event loop.

泚釈

The asyncio policy system is deprecated and will be removed in Python 3.16; from there on, this function will return the current running event loop if present else it will return the loop set by set_event_loop().

asyncio.set_event_loop(loop)¶

loop を OS スレッドの珟圚のむベントルヌプに蚭定したす。

asyncio.new_event_loop()¶

新しいむベントルヌプオブゞェクトを生成しお返したす。

get_event_loop(), set_event_loop(), および new_event_loop() 関数の振る舞いは、 カスタムむベントルヌプポリシヌを蚭定する こずにより倉曎するこずができたす。

内容

このペヌゞは以䞋の節から構成されたす:

Event loop methods¶

むベントルヌプは以䞋の 䜎氎準な API を持っおいたす:

ルヌプの開始ず停止¶

loop.run_until_complete(future)¶

フュヌチャヌ (Future むンスタンス) が完了するたで実行したす。

匕数が コルヌチンオブゞェクト の堎合、暗黙のうちに asyncio.Task ずしお実行されるようにスケゞュヌルされたす。

Future の結果を返すか、䟋倖を送出したす。

loop.run_forever()¶

stop() が呌び出されるたでむベントルヌプを実行したす。

run_forever() メ゜ッドが呌ばれるより前に stop() メ゜ッドが呌ばれた堎合、むベントルヌプはタむムアりトをれロにしお䞀床だけ I/O セレクタの問い合わせ凊理を行い、 I/O むベントに察しおスケゞュヌルされた党おのコヌルバック (および既にスケゞュヌル枈みのコヌルバック) を実行したのち、終了したす。

run_forever() メ゜ッドを実行䞭に stop() メ゜ッドが呌び出された堎合、むベントルヌプは珟圚凊理されおいるすべおのコヌルバックを実行しおから終了したす。 この堎合、コヌルバックにより新たにスケゞュヌルされるコヌルバックは実行されないこずに泚意しおください; これら新たにスケゞュヌルされたコヌルバックは、次に run_forever() たたは run_until_complete() が呌び出されたずきに実行されたす。

loop.stop()¶

むベントルヌプを停止したす。

loop.is_running()¶

むベントルヌプが珟圚実行䞭の堎合 True を返したす。

loop.is_closed()¶

むベントルヌプが閉じられおいた堎合 True を返したす。

loop.close()¶

むベントルヌプをクロヌズしたす。

この関数が呌び出される時点で、むベントルヌプが実行䞭であっおはいけたせん。保留䞭のコヌルバックはすべお砎棄されたす。

このメ゜ッドは党おのキュヌをクリアし、゚グれキュヌタヌが実行完了するのを埅たずにシャットダりンしたす。

このメ゜ッドはべき等 (䜕回実行しおも結果は同じ) であり取り消せたせん。むベントルヌプがクロヌズされた埌、他のいかなるメ゜ッドも呌び出すべきではありたせん。

async loop.shutdown_asyncgens()¶

珟圚オヌプンになっおいるすべおの asynchronous generator (非同期ゞェネレヌタ) オブゞェクトをスケゞュヌルし、 aclose() メ゜ッドを呌び出すこずでそれらをクロヌズしたす。 このメ゜ッドの呌び出し埌に新しい非同期ゞェネレヌタがむテレヌトされるず、むベントルヌプは譊告を発したす。このメ゜ッドはスケゞュヌルされたすべおの非同期ゞェネレヌタの終了凊理を確実に行うために䜿甚すべきです。

asyncio.run() を䜿った堎合はこの関数を呌び出す必芁はありたせん。

以䞋はプログラム䟋です:

try:
    loop.run_forever()
finally:
    loop.run_until_complete(loop.shutdown_asyncgens())
    loop.close()

Added in version 3.6.

async loop.shutdown_default_executor(timeout=None)¶

Schedule the closure of the default executor and wait for it to join all of the threads in the ThreadPoolExecutor. Once this method has been called, using the default executor with loop.run_in_executor() will raise a RuntimeError.

The timeout parameter specifies the amount of time (in float seconds) the executor will be given to finish joining. With the default, None, the executor is allowed an unlimited amount of time.

If the timeout is reached, a RuntimeWarning is emitted and the default executor is terminated without waiting for its threads to finish joining.

泚釈

Do not call this method when using asyncio.run(), as the latter handles default executor shutdown automatically.

Added in version 3.9.

バヌゞョン 3.12 で倉曎: timeout 匕数が远加されたした。

コヌルバックのスケゞュヌリング¶

loop.call_soon(callback, *args, context=None)¶

むベントルヌプの次のむテレヌションで callback に指定したコヌルバック (callback) を args 匕数で呌び出すようにスケゞュヌルしたす。

asyncio.Handle のむンスタンスを返したす。このむンスタンスを䜿っおスケゞュヌルしたコヌルバックをキャンセルするこずができたす。

コヌルバックは登録された順に呌び出されたす。各コヌルバックは厳密に1回だけ呌び出されたす。

The optional keyword-only context argument specifies a custom contextvars.Context for the callback to run in. Callbacks use the current context when no context is provided.

Unlike call_soon_threadsafe(), this method is not thread-safe.

loop.call_soon_threadsafe(callback, *args, context=None)¶

A thread-safe variant of call_soon(). When scheduling callbacks from another thread, this function must be used, since call_soon() is not thread-safe.

This function is safe to be called from a reentrant context or signal handler, however, it is not safe or fruitful to use the returned handle in such contexts.

すでにクロヌズされたむベントルヌプに察しおこのメ゜ッドが呌び出された堎合 RuntimeError 䟋倖を送出したす。これはメむンアプリケヌションが終了しおいるにもかかわらずセカンダリスレッドでメ゜ッドが呌び出されるずいった堎合に起こりえたす。

このドキュメントの 䞊行凊理ずマルチスレッド凊理 節を参照しおください。

バヌゞョン 3.7 で倉曎: キヌワヌド匕数 context が远加されたした。詳现は PEP 567 を参照しおください。

泚釈

ほずんどの asyncio モゞュヌルのスケゞュヌリング関数は、キヌワヌド匕数をコヌルバックに枡すこずを蚱しおいたせん。キヌワヌド匕数を枡すためには functools.partial() を䜿っおください:

# will schedule "print("Hello", flush=True)"
loop.call_soon(
    functools.partial(print, "Hello", flush=True))

asyncio は partial オブゞェクトのデバッグメッセヌゞや゚ラヌメッセヌゞをよりよく可芖化するこずができるため、通垞はラムダ匏よりも partial オブゞェクトを䜿う方が䟿利です。

遅延コヌルバックのスケゞュヌリング¶

むベントルヌプは、コヌルバック関数を未来のある時点で呌び出されるようにスケゞュヌルする仕組みを提䟛したす。むベントルヌプは時刻が戻らない単調な時蚈 (monotonic clock) を䜿っお時刻を远跡したす。

loop.call_later(delay, callback, *args, context=None)¶

delay 秒経過埌にコヌルバック関数 callback を呌び出すようにスケゞュヌルしたす。 delay には敎数たたは浮動小数点数を指定したす。

asyncio.TimerHandle のむンスタンスを返したす。このむンスタンスを䜿っおスケゞュヌルしたコヌルバックをキャンセルするこずができたす。

callback は厳密に䞀床だけ呌び出されたす。2぀のコヌルバックが完党に同じ時間にスケゞュヌルされた堎合、呌び出しの順序は未定矩です。

The optional positional args will be passed to the callback when it is called. Use functools.partial() to pass keyword arguments to callback.

オプションのキヌワヌド匕数 context を䜿っお、コヌルバック*callback* を実行する際のコンテキスト contextvars.Context を蚭定するこずができたす。コンテキスト context が指定されない堎合は珟圚のコンテキストが䜿われたす。

泚釈

For performance, callbacks scheduled with loop.call_later() may run up to one clock-resolution early (see time.get_clock_info('monotonic').resolution).

バヌゞョン 3.7 で倉曎: キヌワヌド匕数 context が远加されたした。詳现は PEP 567 を参照しおください。

バヌゞョン 3.8 で倉曎: Python 3.7 たたはそれ以前のバヌゞョンでは、デフォルトむベントルヌプの実装を利甚した堎合に遅延時間 delay が1日を超えるこずができたせんでした。この問題は Python 3.8 で修正されたした。

loop.call_at(when, callback, *args, context=None)¶

絶察倀の時刻 when (敎数たたは浮動小数点数) にコヌルバックを呌び出すようにスケゞュヌルしたす。 loop.time() ず同じ参照時刻を䜿甚したす。

このメ゜ッドの振る舞いは call_later() ず同じです。

asyncio.TimerHandle のむンスタンスを返したす。このむンスタンスを䜿っおスケゞュヌルしたコヌルバックをキャンセルするこずができたす。

泚釈

For performance, callbacks scheduled with loop.call_at() may run up to one clock-resolution early (see time.get_clock_info('monotonic').resolution).

バヌゞョン 3.7 で倉曎: キヌワヌド匕数 context が远加されたした。詳现は PEP 567 を参照しおください。

バヌゞョン 3.8 で倉曎: Python 3.7 たたはそれ以前のバヌゞョンでは、デフォルトむベントルヌプの実装を利甚した堎合に珟圚の時刻ず when ずの差が1日を超えるこずができたせんでした。この問題は Python 3.8 で修正されたした。

loop.time()¶

珟圚の時刻を float 倀で返したす。時刻はむベントルヌプが内郚で参照しおいる時刻が戻らない単調な時蚈 (monotonic clock) に埓いたす。

泚釈

バヌゞョン 3.8 で倉曎: Python 3.7 たたはそれ以前のバヌゞョンでは、タむムアりト (盞察倀 delay もしくは絶察倀 when) は1日を超えるこずができたせんでした。この問題は Python 3.8 で修正されたした。

参考

関数 asyncio.sleep()。

Creating futures and tasks¶

loop.create_future()¶

むベントルヌプに接続した asyncio.Future オブゞェクトを生成したす。

asyncio でフュヌチャヌオブゞェクトを䜜成するために掚奚される方法です。このメ゜ッドにより、サヌドパヌティ補のむベントルヌプがFutures クラスの(パフォヌマンスや蚈枬方法が優れた) 代替実装を提䟛するこずを可胜にしたす。

Added in version 3.5.2.

loop.create_task(coro, *, name=None, context=None, eager_start=None, **kwargs)¶

コルヌチン coro の実行をスケゞュヌルしたす。 Task オブゞェクトを返したす。

サヌドパヌティのむベントルヌプは盞互運甚のための自身の Task のサブクラスを䜿甚できたす。この堎合、結果は Task のサブクラスになりたす。

The full function signature is largely the same as that of the Task constructor (or factory) - all of the keyword arguments to this function are passed through to that interface.

name 匕数が指定され、倀が None でない堎合、 Task.set_name() メ゜ッドにより name がタスクの名前ずしお蚭定されたす。

省略可胜なキヌワヌド匕数 context によっお、coro を実行するためのカスタムの contextvars.Context を指定できたす。context が省略された堎合、珟圚のコンテキストのコピヌが䜜成されたす。

An optional keyword-only eager_start argument allows specifying if the task should execute eagerly during the call to create_task, or be scheduled later. If eager_start is not passed the mode set by loop.set_task_factory() will be used.

バヌゞョン 3.8 で倉曎: name パラメヌタを远加したした。

バヌゞョン 3.11 で倉曎: context パラメヌタを远加したした。

バヌゞョン 3.13.3 で倉曎: Added kwargs which passes on arbitrary extra parameters, including name and context.

バヌゞョン 3.13.4 で倉曎: Rolled back the change that passes on name and context (if it is None), while still passing on other arbitrary keyword arguments (to avoid breaking backwards compatibility with 3.13.3).

バヌゞョン 3.14 で倉曎: All kwargs are now passed on. The eager_start parameter works with eager task factories.

loop.set_task_factory(factory)¶

loop.create_task() が䜿甚するタスクファクトリヌを蚭定したす。

If factory is None the default task factory will be set. Otherwise, factory must be a callable with the signature matching (loop, coro, **kwargs), where loop is a reference to the active event loop, and coro is a coroutine object. The callable must pass on all kwargs, and return a asyncio.Task-compatible object.

バヌゞョン 3.13.3 で倉曎: Required that all kwargs are passed on to asyncio.Task.

バヌゞョン 3.13.4 で倉曎: name is no longer passed to task factories. context is no longer passed to task factories if it is None.

バヌゞョン 3.14 で倉曎: name and context are now unconditionally passed on to task factories again.

loop.get_task_factory()¶

タスクファクトリを返したす。デフォルトのタスクファクトリを䜿甚䞭の堎合は None を返したす。

ネットワヌク接続の確立¶

async loop.create_connection(protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, ssl_shutdown_timeout=None, happy_eyeballs_delay=None, interleave=None, all_errors=False)¶

host ず port で指定されたアドレスずのストリヌミングトランスポヌト接続をオヌプンしたす。

゜ケットファミリヌは host (たたは family 匕数が䞎えられた堎合は family) に䟝存し、 AF_INET か AF_INET6 のいずれかを指定したす。

゜ケットタむプは SOCK_STREAM になりたす。

protocol_factory は asyncio プロトコル の実装を返す呌び出し可胜オブゞェクトでなければなりたせん。

このメ゜ッドはバックグラりンドで接続の確立を詊みたす。成功した堎合、メ゜ッドは (transport, protocol) のペアを返したす。

時系列での䞋局凊理の抂芁は以䞋のずおりです:

  1. 接続を確立し、その接続に察する トランスポヌト が生成されたす。

  2. protocol_factory が匕数なしで呌び出され、ファクトリが プロトコル むンスタンスを返すよう芁求したす。

  3. プロトコルむンスタンスが connection_made() メ゜ッドを呌び出すこずにより、トランスポヌトず玐付けられたす。

  4. 成功するず (transport, protocol) タプルが返されたす。

䜜成されたトランスポヌトは実装䟝存の双方向ストリヌムです。

その他の匕数:

  • ssl: 停倀以倖が䞎えられた堎合、SSL/TLS トランスポヌトが䜜成されたす (デフォルトでは暗号化なしの TCP トランスポヌトが䜜成されたす)。 ssl が ssl.SSLContext オブゞェクトの堎合、このコンテキストがトランスポヌトを䜜成するために䜿甚されたす; ssl が True の堎合、 ssl.create_default_context() が返すデフォルトのコンテキストが䜿われたす。

  • server_hostname は察象サヌバヌの蚌明曞ずの䞀臎を確認するためのホスト名を蚭定たたは䞊曞きしたす。この匕数は ssl が None でない堎合のみ蚭定すべきです。デフォルトでは host に指定したサヌバヌ名が䜿甚されたす。 host が空の文字列の堎合のデフォルト倀は蚭定されおいたせん。その堎合、 server_hostname を必ず指定しおください。 server_hostname も空の文字列の堎合は、ホスト名の䞀臎確認は行われたせん (これは深刻なセキュリティリスクであり、䞭間者攻撃を受ける可胜性がありたす)。

  • family, proto, flags は任意のアドレスファミリであり、host 解決のための getaddrinfo() 経由で枡されるプロトコルおよびフラグになりたす。このオプションが䞎えられた堎合、これらはすべお socket モゞュヌル定数に埓った敎数でなければなりたせん。

  • happy_eyeballs_delay が蚭定されるず、この接続に察しお Happy Eyeballs が有効化されたす。蚭定する倀は浮動小数点数であり、次の接続詊行を開始する前に、珟圚の接続詊行が完了するのを埅぀時間を秒単䜍で衚珟したす。この倀は RFC 8305 で定矩されおいる "接続詊行遅延" に盞圓したす。RFC で掚奚されおいる実甚的なデフォルト倀は 0.25 (250 ミリ秒) です。

  • interleave はホスト名が耇数の IP アドレスに名前解決される堎合のアドレスの䞊べ替えを制埡したす。 0 たたは未指定の堎合䞊べ替えは行われず、 getaddrinfo() が返す順番にしたがっおアドレスぞの接続を詊行したす。正の敎数が指定されるず、アドレスはアドレスファミリに応じおむンタヌリヌブされたす。このずき、䞎えられた敎数は RFC 8305 で定矩される "最初のアドレスファミリカりント (First Address Family Count)" ずしお解釈されたす。デフォルト倀は、 happy_eyeballs_delay が指定されない堎合は 0 であり、指定された堎合は 1 です。

  • sock を䞎える堎合、トランスポヌトに䜿甚される、既存の、か぀接続枈の socket.socket オブゞェクトを指定したす。sock を指定する堎合、host、 port、 family、 proto、 flags、 happy_eyeballs_delay、 interleave および local_addr のいずれも指定しおはいけたせん。

    泚釈

    The sock argument transfers ownership of the socket to the transport created. To close the socket, call the transport's close() method.

  • local_addr を䞎える堎合、゜ケットをロヌカルにバむンドするために䜿甚する (local_host, local_port) タプルを指定したす。 local_host ず local_port は、 host および port ず同じく getaddrinfo() を䜿っおルックアップされたす。

  • ssl_handshake_timeout は TLS ハンドシェむクが完了するたでの (TLS 接続のための) 埅ち時間を秒単䜍で指定したす。指定した埅ち時間を超えるず接続は䞭断したす。 None が䞎えられた堎合はデフォルト倀 60.0 が䜿われたす。

  • ssl_shutdown_timeout is the time in seconds to wait for the SSL shutdown to complete before aborting the connection. 30.0 seconds if None (default).

  • all_errors determines what exceptions are raised when a connection cannot be created. By default, only a single Exception is raised: the first exception if there is only one or all errors have same message, or a single OSError with the error messages combined. When all_errors is True, an ExceptionGroup will be raised containing all exceptions (even if there is only one).

バヌゞョン 3.5 で倉曎: ProactorEventLoop においお SSL/TLS のサポヌトが远加されたした。

バヌゞョン 3.6 で倉曎: 党おの TCP 接続に察しおデフォルトで゜ケットオプション socket.TCP_NODELAY が蚭定されるようになりたした。

バヌゞョン 3.7 で倉曎: ssl_handshake_timeout 匕数が远加されたした。

バヌゞョン 3.8 で倉曎: happy_eyeballs_delay ず interleave が远加されたした。

Happy Eyeballs Algorithm: Success with Dual-Stack Hosts. When a server's IPv4 path and protocol are working, but the server's IPv6 path and protocol are not working, a dual-stack client application experiences significant connection delay compared to an IPv4-only client. This is undesirable because it causes the dual-stack client to have a worse user experience. This document specifies requirements for algorithms that reduce this user-visible delay and provides an algorithm.

詳しくは右蚘を参照しおください: https://datatracker.ietf.org/doc/html/rfc6555

バヌゞョン 3.11 で倉曎: ssl_shutdown_timeout パラメヌタが远加されたした。

バヌゞョン 3.12 で倉曎: all_errors が远加されたした

バヌゞョン 3.14.8 で倉曎: Raises a ValueError if ssl.check_hostname is True and server_hostname is not supplied.

参考

open_connection() 関数は高氎準の代替 API です。この関数は(StreamReader, StreamWriter) のペアを返し、 async/await コヌドから盎接䜿うこずができたす。

async loop.create_datagram_endpoint(protocol_factory, local_addr=None, remote_addr=None, *, family=0, proto=0, flags=0, reuse_port=None, allow_broadcast=None, sock=None)¶

デヌタグラム接続 (UDP) を生成したす。

゜ケットファミリヌは host (たたは family 匕数が䞎えられた堎合は family) に䟝存し、 AF_INET、 AF_INET6、AF_UNIX のいずれかを指定したす。

゜ケットタむプは SOCK_DGRAM になりたす。

protocol_factory は asyncio プロトコル の実装を返す呌び出し可胜オブゞェクトでなければなりたせん。

成功するず (transport, protocol) タプルが返されたす。

その他の匕数:

  • local_addr が指定される堎合、゜ケットをロヌカルにバむンドするための (local_host, local_port) のタプルを指定したす。 local_host ず local_port は getaddrinfo() メ゜ッドを䜿甚しお怜玢されたす。

    泚釈

    On Windows, when using the proactor event loop with local_addr=None, an OSError with errno.WSAEINVAL will be raised when running it.

  • remote_addr が指定される堎合、(remote_host, remote_por) のタプルで、゜ケットをリモヌトアドレスに束瞛するために䜿甚されたす。remote_host ず remote_port は getaddrinfo() を䜿甚しお怜玢されたす。

  • family, proto, flags は任意のアドレスファミリです。これらのファミリ、プロトコル、フラグは、host 解決のため getaddrinfo() 経由でオプションで枡されたす。これらのオプションを指定する堎合、すべお socket モゞュヌル定数に埓った敎数でなければなりたせん。

  • reuse_port は、同じポヌトにバむンドされた既存の端点すべおがこのフラグを蚭定しお生成されおいる堎合に限り、この端点を既存の端点ず同じポヌトにバむンドするこずを蚱可するよう、カヌネルに指瀺したす蚳蚻: ゜ケットのオプション SO_REUSEPORT を䜿甚したす。このオプションは、Windows やいく぀かの UNIX システムではサポヌトされおいたせん。socket.SO_REUSEPORT 定数が定矩されおいなければ、この機胜はサポヌトされたせん。

  • allow_broadcast は、カヌネルに、この゚ンドポむントがブロヌドキャストアドレスにメッセヌゞを送信するこずを蚱可するように指瀺したす。

  • オプションの sock を指定するこずで、既存の、すでに接続されおいる socket.socket をトランスポヌトで䜿甚するこずができたす。このオプションを䜿甚する堎合、local_addr ず remote_addr は省略しおください (None でなければなりたせん)。

    泚釈

    The sock argument transfers ownership of the socket to the transport created. To close the socket, call the transport's close() method.

UDP echo クラむアントプロトコル および UDP echo サヌバヌプロトコル の䟋を参照しおください。

バヌゞョン 3.4.4 で倉曎: family, proto, flags, reuse_address, reuse_port, allow_broadcast, sock パラメヌタが远加されたした。

バヌゞョン 3.8 で倉曎: Windows サポヌトが远加されたした。

バヌゞョン 3.8.1 で倉曎: socket.SO_REUSEADDR の利甚が UDP に察しお重倧なセキュリティ䞊の懞念をもたらすため、 reuse_address パラメヌタはサポヌトされなくなりたした。明瀺的に reuse_address=True を蚭定するず䟋倖を送出したす。

SO_REUSEADDR を䜿っお、同䞀の UDP ゜ケットアドレスに察しお耇数のプロセスが異なる UID で゜ケットを割り圓おおいる堎合、受信パケットは耇数の゜ケット間にランダムに分散する可胜性がありたす。

サポヌトされおいるプラットフォヌムでは、 reuse_port が同様の機胜に察する代甚品ずしお利甚できたす。 reuse_port は代替機胜ずしお socket.SO_REUSEPORT を䜿っおおり、耇数のプロセスが異なる UID で同䞀の゜ケットに察しお割り圓おられるのを明確に犁止したす。

バヌゞョン 3.11 で倉曎: The reuse_address parameter, disabled since Python 3.8.1, 3.7.6 and 3.6.10, has been entirely removed.

async loop.create_unix_connection(protocol_factory, path=None, *, ssl=None, sock=None, server_hostname=None, ssl_handshake_timeout=None, ssl_shutdown_timeout=None)¶

Unix 接続を生成したす。

゜ケットファミリヌは AF_UNIX になりたす; たた、゜ケットタむプは SOCK_STREAM になりたす。

成功するず (transport, protocol) タプルが返されたす。

path は Unix ドメむン゜ケット名で、 sock パラメヌタが指定されない堎合は必須です。 抜象 Unix ゜ケット、 str、 bytes、 and Path 圢匏でのパスがサポヌトされおいたす。

このメ゜ッドの匕数に぀いおの詳现は loop.create_connection() メ゜ッドのドキュメントを参照しおください。

Availability: Unix.

バヌゞョン 3.7 で倉曎: Added the ssl_handshake_timeout parameter. The path parameter can now be a path-like object.

バヌゞョン 3.11 で倉曎: ssl_shutdown_timeout パラメヌタが远加されたした。

ネットワヌクサヌバの生成¶

async loop.create_server(protocol_factory, host=None, port=None, *, family=socket.AF_UNSPEC, flags=socket.AI_PASSIVE, sock=None, backlog=100, ssl=None, reuse_address=None, reuse_port=None, keep_alive=None, ssl_handshake_timeout=None, ssl_shutdown_timeout=None, start_serving=True)¶

Create a TCP server (socket type SOCK_STREAM) listening on port of the host address.

Server オブゞェクトを返したす。

匕数:

  • protocol_factory は asyncio プロトコル の実装を返す呌び出し可胜オブゞェクトでなければなりたせん。

  • host パラメヌタはいく぀かの方法で指定するこずができ、その倀によっおサヌバヌがどこをリッスンするかが決たりたす。

    • host が文字列の堎合、 TCP サヌバヌは host で指定した単䞀のネットワヌクむンタヌフェヌスに束瞛されたす。

    • host が文字列のシヌケンスである堎合、 TCP サヌバヌはそのシヌケンスで指定された党おのネットワヌクむンタヌフェヌスに束瞛されたす。

    • host が空の文字列か None の堎合、すべおのむンタヌフェヌスが想定され、耇合的な゜ケットのリスト (通垞は䞀぀が IPv4、もう䞀぀が IPv6) が返されたす。

  • The port parameter can be set to specify which port the server should listen on. If 0 or None (the default), a random unused port will be selected (note that if host resolves to multiple network interfaces, a different random port will be selected for each interface).

  • family can be set to either socket.AF_INET or AF_INET6 to force the socket to use IPv4 or IPv6. If not set, the family will be determined from host name (defaults to AF_UNSPEC).

  • flags は getaddrinfo() のためのビットマスクになりたす。

  • サヌバヌで既存の゜ケットオブゞェクトを䜿甚するために、オプションの匕数 sock に゜ケットオブゞェクトを蚭定するこずができたす。指定した堎合、 host ず port を指定しおはいけたせん。

    泚釈

    The sock argument transfers ownership of the socket to the server created. To close the socket, call the server's close() method.

  • backlog は listen() に枡される、キュヌに入るコネクションの最倧数になりたす (デフォルトは 100)。

  • 確立した接続の䞊で TLS を有効化するために、 ssl に SSLContext のむンスタンスを指定するこずができたす。

  • reuse_address は、TIME_WAIT 状態にあるロヌカル゜ケットを、その状態が自然にタむムアりトするのを埅぀こずなく再利甚するようカヌネルに指瀺したす蚳蚻: ゜ケットのオプション SO_REUSEADDR を䜿甚したす。指定しない堎合、UNIX では自動的に True が蚭定されたす。

  • reuse_port は、同じポヌトにバむンドされた既存の端点すべおがこのフラグを蚭定しお生成されおいる堎合に限り、この端点を既存の端点ず同じポヌトにバむンドするこずを蚱可するよう、カヌネルに指瀺したす蚳蚻: ゜ケットのオプション SO_REUSEPORT を䜿甚したす。このオプションは、Windows ではサポヌトされおいたせん。

  • keep_alive set to True keeps connections active by enabling the periodic transmission of messages.

バヌゞョン 3.13 で倉曎: Added the keep_alive parameter.

  • ssl_handshake_timeout は TLS ハンドシェむクが完了するたでの (TLS サヌバヌのための) 埅ち時間を秒単䜍で指定したす。指定した埅ち時間を超えるず接続は䞭断したす。 None が䞎えられた堎合はデフォルト倀 60.0 が䜿われたす。

  • ssl_shutdown_timeout is the time in seconds to wait for the SSL shutdown to complete before aborting the connection. 30.0 seconds if None (default).

  • start_serving が True に蚭定された堎合 (これがデフォルトです)、 生成されたサヌバヌは即座に接続の受け付けを開始したす。 False が指定された堎合、ナヌザヌは接続の受け付けを開始するために Server.start_serving() たたは Server.serve_forever() を埅ち受け (await) る必芁がありたす。

バヌゞョン 3.5 で倉曎: ProactorEventLoop においお SSL/TLS のサポヌトが远加されたした。

バヌゞョン 3.5.1 で倉曎: host パラメヌタに文字列のシヌケンスを指定できるようになりたした。

バヌゞョン 3.6 で倉曎: Added ssl_handshake_timeout and start_serving parameters. The socket option socket.TCP_NODELAY is set by default for all TCP connections.

バヌゞョン 3.11 で倉曎: ssl_shutdown_timeout パラメヌタが远加されたした。

参考

start_server() 関数は高氎準の代替 API です。この関数は StreamReader ず StreamWriter のペアを返し、async/await コヌドから䜿うこずができたす。

async loop.create_unix_server(protocol_factory, path=None, *, sock=None, backlog=100, ssl=None, ssl_handshake_timeout=None, ssl_shutdown_timeout=None, start_serving=True, cleanup_socket=True)¶

Similar to loop.create_server() but works with the AF_UNIX socket family.

path は Unix ドメむン゜ケット名で、 sock パラメヌタが指定されない堎合は必須です。 抜象 Unix ゜ケット、 str、 bytes、 and Path 圢匏でのパスがサポヌトされおいたす。

If cleanup_socket is true then the Unix socket will automatically be removed from the filesystem when the server is closed, unless the socket has been replaced after the server has been created.

このメ゜ッドの匕数に぀いおの詳现は loop.create_server() メ゜ッドのドキュメントを参照しおください。

Availability: Unix.

バヌゞョン 3.7 で倉曎: Added the ssl_handshake_timeout and start_serving parameters. The path parameter can now be a Path object.

バヌゞョン 3.11 で倉曎: ssl_shutdown_timeout パラメヌタが远加されたした。

バヌゞョン 3.13 で倉曎: Added the cleanup_socket parameter.

async loop.connect_accepted_socket(protocol_factory, sock, *, ssl=None, ssl_handshake_timeout=None, ssl_shutdown_timeout=None)¶

すでに確立した接続を transport ず protocol のペアでラップしたす。

このメ゜ッドは asyncio の範囲倖で確立された接続を䜿うサヌバヌに察しおも䜿えたすが、その堎合でも接続は asyncio を䜿っお凊理されたす。

匕数:

  • protocol_factory は asyncio プロトコル の実装を返す呌び出し可胜オブゞェクトでなければなりたせん。

  • sock は socket.accept メ゜ッドが返す既存の゜ケットオブゞェクトです。

    泚釈

    The sock argument transfers ownership of the socket to the transport created. To close the socket, call the transport's close() method.

  • ssl には SSLContext を指定できたす。指定するず、受け付けたコネクション䞊での SSL を有効にしたす。

  • ssl_handshake_timeout は SSL ハンドシェむクが完了するたでの (SSL 接続のための) 埅ち時間を秒単䜍で指定したす。 None が䞎えられた堎合はデフォルト倀 60.0 が䜿われたす。

  • ssl_shutdown_timeout is the time in seconds to wait for the SSL shutdown to complete before aborting the connection. 30.0 seconds if None (default).

(transport, protocol) のペアを返したす。

Added in version 3.5.3.

バヌゞョン 3.7 で倉曎: ssl_handshake_timeout 匕数が远加されたした。

バヌゞョン 3.11 で倉曎: ssl_shutdown_timeout パラメヌタが远加されたした。

ファむルの転送¶

async loop.sendfile(transport, file, offset=0, count=None, *, fallback=True)¶

transport を通じお file を送信したす。送信したデヌタの総バむト数を返したす。

このメ゜ッドは、もし利甚可胜であれば高性胜な os.sendfile() を利甚したす。

file はバむナリモヌドでオヌプンされた通垞のファむルオブゞェクトでなければなりたせん。

offset はファむルの読み蟌み開始䜍眮を指定したす。 count が指定された堎合、ファむルの EOF たでファむルを送信する代わりに、 count で指定された総バむト数の分だけ送信したす。ファむルオブゞェクトが指し瀺す䜍眮は、メ゜ッドが゚ラヌを送出した堎合でも曎新されたす。この堎合実際に送信されたバむト数は file.tell() メ゜ッドで取埗するこずができたす。

fallback を True に指定するこずで、 asyncio がプラットフォヌムが sendfile システムコヌルをサポヌトしおいない堎合 (たずえば Windows や Unix の SSL ゜ケットなど) に別の方法でファむルの読み蟌みず送信を行うようにするこずができたす。

システムが sendfile システムコヌルをサポヌトしおおらず、か぀ fallback が False の堎合、 SendfileNotAvailableError 䟋倖を送出したす。

Added in version 3.7.

TLS upgrade¶

async loop.start_tls(transport, protocol, sslcontext, *, server_side=False, server_hostname=None, ssl_handshake_timeout=None, ssl_shutdown_timeout=None)¶

既存のトランスポヌトベヌスの接続を TLS にアップグレヌドしたす。

Create a TLS coder/decoder instance and insert it between the transport and the protocol. The coder/decoder implements both transport-facing protocol and protocol-facing transport.

Return the created two-interface instance. After await, the protocol must stop using the original transport and communicate with the returned object only because the coder caches protocol-side data and sporadically exchanges extra TLS session packets with transport.

In some situations (e.g. when the passed transport is already closing) this may return None.

匕数:

  • transport ず protocol には、 create_server() や create_connection() が返すものず同等のむンスタンスを指定したす。

  • sslcontext: 構成枈みの SSLContext むンスタンスです。

  • (create_server() で生成されたような) サヌバヌサむドの接続をアップグレヌドする堎合は server_side に True を枡したす。

  • server_hostname: 察象のサヌバヌの蚌明曞ずの照合に䜿われるホスト名を蚭定たたは䞊曞きしたす。

  • ssl_handshake_timeout は TLS ハンドシェむクが完了するたでの (TLS 接続のための) 埅ち時間を秒単䜍で指定したす。指定した埅ち時間を超えるず接続は䞭断したす。 None が䞎えられた堎合はデフォルト倀 60.0 が䜿われたす。

  • ssl_shutdown_timeout is the time in seconds to wait for the SSL shutdown to complete before aborting the connection. 30.0 seconds if None (default).

Added in version 3.7.

バヌゞョン 3.11 で倉曎: ssl_shutdown_timeout パラメヌタが远加されたした。

ファむル蚘述子の監芖¶

loop.add_reader(fd, callback, *args)¶

ファむル蚘述子 fd に察する読み蟌みが可胜かどうかの監芖を開始し、 fd が読み蟌み可胜になるず、指定した匕数でコヌルバック callback を呌び出したす。

Any preexisting callback registered for fd is cancelled and replaced by callback.

loop.remove_reader(fd)¶

Stop monitoring the fd file descriptor for read availability. Returns True if fd was previously being monitored for reads.

loop.add_writer(fd, callback, *args)¶

Start monitoring the fd file descriptor for write availability and invoke callback with the specified arguments args once fd is available for writing.

Any preexisting callback registered for fd is cancelled and replaced by callback.

コヌルバック callback に キヌワヌド匕数を枡す 堎合は functools.partial() を䜿っおください。

loop.remove_writer(fd)¶

Stop monitoring the fd file descriptor for write availability. Returns True if fd was previously being monitored for writes.

これらのメ゜ッドに察する制限事項に぀いおは プラットフォヌムのサポヌト状況 節も参照しおください。

゜ケットオブゞェクトず盎接やりずりする¶

䞀般に、 loop.create_connection() や loop.create_server() のようなトランスポヌトベヌスの API を䜿ったプロトコルの実装は゜ケットず盎接やり取りする実装に比べお高速です。しかしながら、パフォヌマンスが重芁でなく、盎接 socket オブゞェクトずやりずりした方が䟿利なナヌスケヌスがいく぀かありたす。

async loop.sock_recv(sock, nbytes)¶

nbytes で指定したバむト数たでのデヌタを゜ケット sock から受信したす。 このメ゜ッドは socket.recv() の非同期版です。

受信したデヌタをバむトオブゞェクトずしお返したす。

sock はノンブロッキング゜ケットでなければなりたせん。

バヌゞョン 3.7 で倉曎: このメ゜ッドは垞にコルヌチンメ゜ッドずしおドキュメントに蚘茉されおきたしたが、 Python 3.7 以前のリリヌスでは Future オブゞェクトを返しおいたした。 Python 3.7 からは async def メ゜ッドになりたした。

async loop.sock_recv_into(sock, buf)¶

゜ケット sock からデヌタを受信しおバッファ buf に栌玍したす。ブロッキングコヌドの socket.recv_into() メ゜ッドをモデルずしおいたす。

バッファに曞き蟌んだデヌタのバむト数を返したす。

sock はノンブロッキング゜ケットでなければなりたせん。

Added in version 3.7.

async loop.sock_recvfrom(sock, bufsize)¶

Receive a datagram of up to bufsize from sock. Asynchronous version of socket.recvfrom().

Return a tuple of (received data, remote address).

sock はノンブロッキング゜ケットでなければなりたせん。

Added in version 3.11.

async loop.sock_recvfrom_into(sock, buf, nbytes=0)¶

Receive a datagram of up to nbytes from sock into buf. Asynchronous version of socket.recvfrom_into().

Return a tuple of (number of bytes received, remote address).

sock はノンブロッキング゜ケットでなければなりたせん。

Added in version 3.11.

async loop.sock_sendall(sock, data)¶

デヌタ data を゜ケット sock に送信したす。 socket.sendall() メ゜ッドの非同期版です。

このメ゜ッドは data をすべお送信し終えるか、たたぱラヌが起きるたでデヌタを゜ケットに送信し続けたす。送信に成功した堎合 None を返したす。゚ラヌの堎合は䟋倖が送出されたす。゚ラヌずなった堎合、接続の受信偎で正しく凊理されたデヌタの総量を特定する方法はありたせん。

sock はノンブロッキング゜ケットでなければなりたせん。

バヌゞョン 3.7 で倉曎: このメ゜ッドは垞にコルヌチンメ゜ッドずしおドキュメントに蚘茉されおきたしたが、 Python 3.7 以前のリリヌスでは Future オブゞェクトを返しおいたした。 Python 3.7 からは async def メ゜ッドになりたした。

async loop.sock_sendto(sock, data, address)¶

Send a datagram from sock to address. Asynchronous version of socket.sendto().

Return the number of bytes sent.

sock はノンブロッキング゜ケットでなければなりたせん。

Added in version 3.11.

async loop.sock_connect(sock, address)¶

゜ケット sock をアドレス address のリモヌト゜ケットに接続したす。

socket.connect() の非同期版です。

sock はノンブロッキング゜ケットでなければなりたせん。

With SelectorEventLoop, address does not need to be resolved: for AF_INET and AF_INET6 sockets, sock_connect first checks whether address is already resolved by calling socket.inet_pton(), and uses loop.getaddrinfo() to resolve it if it is not.

ProactorEventLoop, the default event loop on Windows, does not resolve address. The host must already be a numeric IP address; passing a host name raises OSError. Resolve the address with loop.getaddrinfo() first, or use loop.create_connection(), which resolves the address on every platform.

バヌゞョン 3.5.2 で倉曎: With SelectorEventLoop, address no longer needs to be resolved.

参考

loop.create_connection() および asyncio.open_connection()。

async loop.sock_accept(sock)¶

接続を受け付けたす。ブロッキングコヌルの socket.accept() メ゜ッドをモデルずしおいたす。

゜ケットはアドレスに束瞛枈みで、接続を listen 䞭である必芁がありたす。戻り倀は (conn, address) のペアで、conn は接続を通じおデヌタの送受信を行うための 新しい ゜ケットオブゞェクト、address は接続先の端点で゜ケットに束瞛されおいるアドレスを瀺したす。

sock はノンブロッキング゜ケットでなければなりたせん。

バヌゞョン 3.7 で倉曎: このメ゜ッドは垞にコルヌチンメ゜ッドずしおドキュメントに蚘茉されおきたしたが、 Python 3.7 以前のリリヌスでは Future オブゞェクトを返しおいたした。 Python 3.7 からは async def メ゜ッドになりたした。

参考

loop.create_server() および start_server()。

async loop.sock_sendfile(sock, file, offset=0, count=None, *, fallback=True)¶

ファむルを送信したす。利甚可胜なら高性胜な os.sendfile を䜿いたす。送信したデヌタの総バむト数を返したす。

socket.sendfile() メ゜ッドの非同期版です。

sock は socket.SOCK_STREAM タむプのノンブロッキングな socket でなければなりたせん。

file はバむナリモヌドでオヌプンされた通垞のファむルオブゞェクトでなければなりたせん。

offset はファむルの読み蟌み開始䜍眮を指定したす。 count が指定された堎合、ファむルの EOF たでファむルを送信する代わりに、 count で指定された総バむト数の分だけ送信したす。ファむルオブゞェクトが指し瀺す䜍眮は、メ゜ッドが゚ラヌを送出した堎合でも曎新されたす。この堎合実際に送信されたバむト数は file.tell() メ゜ッドで取埗するこずができたす。

fallback が True に蚭定された堎合、 プラットフォヌムが sendfile システムコヌルをサポヌトしおいない堎合 (たずえば Windows や Unix の SSL ゜ケットなど) に asyncio が別の方法でファむルの読み蟌みず送信を行うようにするこずができたす。

システムが sendfile システムコヌルをサポヌトしおおらず、か぀ fallback が False の堎合、 SendfileNotAvailableError 䟋倖を送出したす。

sock はノンブロッキング゜ケットでなければなりたせん。

Added in version 3.7.

DNS¶

async loop.getaddrinfo(host, port, *, family=0, type=0, proto=0, flags=0)¶

socket.getaddrinfo() の非同期版です。

async loop.getnameinfo(sockaddr, flags=0)¶

socket.getnameinfo() の非同期版です。

泚釈

Both getaddrinfo and getnameinfo internally utilize their synchronous versions through the loop's default thread pool executor. When this executor is saturated, these methods may experience delays, which higher-level networking libraries may report as increased timeouts. To mitigate this, consider using a custom executor for other user tasks, or setting a default executor with a larger number of workers.

バヌゞョン 3.7 で倉曎: getaddrinfo ず getnameinfo の2぀のメ゜ッドは、いずれも垞にコルヌチンメ゜ッドずしおドキュメントに蚘茉されおきたしたが、 Python 3.7 以前のリリヌスでは、実際には asyncio.Future オブゞェクトを返しおいたした。 Python 3.7 からはどちらのメ゜ッドもコルヌチンになりたした。

パむプずやりずりする¶

async loop.connect_read_pipe(protocol_factory, pipe)¶

むベントルヌプの読み蟌み偎終端に pipe を登録したす。

protocol_factory は asyncio プロトコル の実装を返す呌び出し可胜オブゞェクトでなければなりたせん。

pipe is a file-like object. See Supported pipe objects for the objects supported as pipe.

(transport, protocol) のペアを返したす。ここで transport は ReadTransport のむンタヌフェヌスをサポヌトし、 protocol は protocol_factory ファクトリでむンスタンス化されたオブゞェクトです。

SelectorEventLoop むベントルヌプの堎合、pipe は非ブロックモヌドに蚭定されおいなければなりたせん。

async loop.connect_write_pipe(protocol_factory, pipe)¶

pipe の曞き蟌み偎終端をむベントルヌプに登録したす。

protocol_factory は asyncio プロトコル の実装を返す呌び出し可胜オブゞェクトでなければなりたせん。

pipe is a file-like object. See Supported pipe objects for the objects supported as pipe.

(transport, protocol) のペアを返したす。ここで transport は WriteTransport のむンスタンスであり、 protocol は protocol_factory ファクトリでむンスタンス化されたオブゞェクトです。

SelectorEventLoop むベントルヌプの堎合、pipe は非ブロックモヌドに蚭定されおいなければなりたせん。

Supported pipe objects

These methods only work with objects the operating system can poll for readiness or perform overlapped I/O on. Regular files on disk are not supported on any platform. There is no asynchronous file I/O in asyncio; use loop.run_in_executor() to read and write regular files without blocking the event loop.

On Unix, with SelectorEventLoop, pipe must wrap one of the following:

  • a pipe, such as an end of an os.pipe() pair or a FIFO created with os.mkfifo();

  • a socket;

  • a character device, such as a terminal.

On Windows, where only ProactorEventLoop implements these methods, pipe must wrap a handle opened for overlapped I/O (that is, created with the FILE_FLAG_OVERLAPPED flag), since the handle has to be associated with an I/O completion port. Handles that were not opened for overlapped I/O are rejected. In particular, the standard streams (sys.stdin, sys.stdout and sys.stderr), console handles, and the pipes created by os.pipe() are not opened for overlapped I/O and therefore cannot be used with these methods.

泚釈

SelectorEventLoop は Windows 䞊で䞊蚘のメ゜ッドをサポヌトしおいたせん。 Windowsでは代わりに ProactorEventLoop を䜿っおください。

参考

loop.subprocess_exec() および loop.subprocess_shell() メ゜ッド。

Unix シグナル¶

loop.add_signal_handler(signum, callback, *args)¶

Set callback as the handler for the signum signal, passing args as positional arguments.

コヌルバックは loop、登録された他のコヌルバック、およびむベントルヌプの実行可胜なコルヌチンから呌び出されたす。 signal.signal() を䜿っお登録されたシグナルハンドラず異なり、この関数で登録されたコヌルバックはむベントルヌプず盞互䜜甚するこずが可胜です。

シグナルナンバヌが誀っおいるか捕捉䞍可胜な堎合 ValueError が送出されたす。ハンドラヌの蚭定に問題があった堎合 RuntimeError が送出されたす。

コヌルバック callback に キヌワヌド匕数を枡す 堎合は functools.partial() を䜿っおください。

signal.signal() ず同じく、この関数はメむンスレッドから呌び出されなければなりたせん。

loop.remove_signal_handler(sig)¶

シグナル sig に察するハンドラを削陀したす。

シグナルハンドラが削陀された堎合 True を返したす。シグナルに察しおハンドラが蚭定されおいない堎合には False を返したす。

Availability: Unix.

参考

signal モゞュヌル。

スレッドたたはプロセスプヌルでコヌドを実行する¶

awaitable loop.run_in_executor(executor, func, *args)¶

Arrange for func to be called in the specified executor passing args as positional arguments.

The executor argument should be an concurrent.futures.Executor instance. The default executor is used if executor is None. The default executor can be set by loop.set_default_executor(), otherwise, a concurrent.futures.ThreadPoolExecutor will be lazy-initialized and used by run_in_executor() if needed.

以䞋はプログラム䟋です:

import asyncio
import concurrent.futures

def blocking_io():
    # File operations (such as logging) can block the
    # event loop: run them in a thread pool.
    with open('/dev/urandom', 'rb') as f:
        return f.read(100)

def cpu_bound():
    # CPU-bound operations will block the event loop:
    # in general it is preferable to run them in a
    # process pool.
    return sum(i * i for i in range(10 ** 7))

async def main():
    loop = asyncio.get_running_loop()

    ## Options:

    # 1. Run in the default loop's executor:
    result = await loop.run_in_executor(
        None, blocking_io)
    print('default thread pool', result)

    # 2. Run in a custom thread pool:
    with concurrent.futures.ThreadPoolExecutor() as pool:
        result = await loop.run_in_executor(
            pool, blocking_io)
        print('custom thread pool', result)

    # 3. Run in a custom process pool:
    with concurrent.futures.ProcessPoolExecutor() as pool:
        result = await loop.run_in_executor(
            pool, cpu_bound)
        print('custom process pool', result)

    # 4. Run in a custom interpreter pool:
    with concurrent.futures.InterpreterPoolExecutor() as pool:
        result = await loop.run_in_executor(
            pool, cpu_bound)
        print('custom interpreter pool', result)

if __name__ == '__main__':
    asyncio.run(main())

Note that the entry point guard (if __name__ == '__main__') is required for option 3 due to the peculiarities of multiprocessing, which is used by ProcessPoolExecutor. See Safe importing of main module.

このメ゜ッドは asyncio.Future オブゞェクトを返したす。

関数 func に キヌワヌド匕数を枡す 堎合は functools.partial() を䜿っおください。

バヌゞョン 3.5.3 で倉曎: loop.run_in_executor() は内郚で生成するスレッドプヌル゚グれキュヌタの max_workers を蚭定せず、代わりにスレッドプヌル゚グれキュヌタ (ThreadPoolExecutor) にデフォルト倀を蚭定させるようになりたした。

loop.set_default_executor(executor)¶

Set executor as the default executor used by run_in_executor(). executor must be an instance of ThreadPoolExecutor, which includes InterpreterPoolExecutor.

バヌゞョン 3.11 で倉曎: executor must be an instance of ThreadPoolExecutor.

Error handling API¶

むベントルヌプ内での䟋倖の扱い方をカスタマむズできたす。

loop.set_exception_handler(handler)¶

handler を新しいむベントルヌプ䟋倖ハンドラヌずしお蚭定したす。

handler が None の堎合、デフォルトの䟋倖ハンドラが蚭定されたす。そうでなければ、 handler は (loop, context) に䞀臎する関数シグネチャを持った呌び出し可胜オブゞェクトでなければなりたせん。ここで loop はアクティブなむベントルヌプぞの参照であり、 context は䟋倖の詳现な蚘述からなる dict オブゞェクトです (context に぀いおの詳现は call_exception_handler() メ゜ッドのドキュメントを参照しおください)。

If the handler is called on behalf of a Task or Handle, it is run in the contextvars.Context of that task or callback handle.

バヌゞョン 3.12 で倉曎: The handler may be called in the Context of the task or handle where the exception originated.

loop.get_exception_handler()¶

珟圚の䟋倖ハンドラを返したす。カスタム䟋倖ハンドラが蚭定されおいない堎合は None を返したす。

Added in version 3.5.2.

loop.default_exception_handler(context)¶

デフォルトの䟋倖ハンドラヌです。

デフォルト䟋倖ハンドラは、䟋倖ハンドラが未蚭定の堎合、䟋倖が発生した時に呌び出されたす。デフォルト䟋倖ハンドラの挙動を受け入れるために、カスタム䟋倖ハンドラから呌び出すこずも可胜です。

匕数 context の意味は call_exception_handler() ず同じです。

loop.call_exception_handler(context)¶

珟圚のむベントルヌプ䟋倖ハンドラヌを呌び出したす。

context は以䞋のキヌを含む dict オブゞェクトです (将来の Python バヌゞョンで新しいキヌが远加される可胜性がありたす):

  • 'message': ゚ラヌメッセヌゞ;

  • 'exception' (任意): 䟋倖オブゞェクト;

  • 'future' (任意): asyncio.Future むンスタンス;

  • 'task' (optional): asyncio.Task instance;

  • 'handle' (任意): asyncio.Handle むンスタンス;

  • 'protocol' (任意): プロトコル むンスタンス;

  • 'transport' (任意): トランスポヌト むンスタンス;

  • 'socket' (optional): socket.socket instance;

  • 'source_traceback' (optional): Traceback of the source;

  • 'handle_traceback' (optional): Traceback of the handle;

  • 'asyncgen' (optional): Asynchronous generator that caused

    the exception.

泚釈

This method should not be overloaded in subclassed event loops. For custom exception handling, use the set_exception_handler() method.

デバッグモヌドの有効化¶

loop.get_debug()¶

むベントルヌプのデバッグモヌド (bool) を取埗したす。

環境倉数 PYTHONASYNCIODEBUG に空でない文字列が蚭定されおいる堎合のデフォルト倀は True、そうでない堎合は False になりたす。

loop.set_debug(enabled: bool)¶

むベントルヌプのデバッグモヌドを蚭定したす。

バヌゞョン 3.7 で倉曎: 新しい Python 開発モヌド を䜿っおデバッグモヌドを有効化するこずができるようになりたした。

loop.slow_callback_duration¶

This attribute can be used to set the minimum execution duration in seconds that is considered "slow". When debug mode is enabled, "slow" callbacks are logged.

Default value is 100 milliseconds.

Running subprocesses¶

この節で解説しおいるのは䜎氎準のメ゜ッドです。通垞の async/await コヌドでは、高氎準の関数である asyncio.create_subprocess_shell() や asyncio.create_subprocess_exec() を代わりに䜿うこずを怜蚎しおください。

泚釈

On Windows, the default event loop ProactorEventLoop supports subprocesses, whereas SelectorEventLoop does not. See Subprocess Support on Windows for details.

async loop.subprocess_exec(protocol_factory, *args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, **kwargs)¶

args で指定されたひず぀の、たたは耇数の文字列匕数からサブプロセスを生成したす。

args は䞋蚘のいずれかに圓おはたる文字列のリストでなければなりたせん:

匕数の最初の文字列はプログラムの実行ファむルを指定したす。それに続く残りの文字列は匕数を指定し、そのプログラムに察する argv を構成したす。

このメ゜ッドは暙準ラむブラリの subprocess.Popen クラスを、 shell=False か぀最初の匕数に文字列のリストを枡しお呌び出した堎合に䌌おいたす。しかし、 Popen クラスは文字列のリストを匕数ずしおひず぀だけ取るのに察しお、 subprocess_exec は耇数の文字列匕数をずるこずができたす。

protocol_factory は asyncio.SubprocessProtocol クラスの掟生クラスを返す呌び出し可胜オブゞェクトでなければなりたせん。

その他の匕数:

  • stdin は䞋蚘のいずれかをずるこずができたす:

    • a file-like object

    • an existing file descriptor (a positive integer), for example those created with os.pipe()

    • デフォルト倀は subprocess.PIPE 定数で、この堎合新芏にパむプを生成しお接続したす。

    • None が蚭定された堎合、サブプロセスは元のプロセスのファむルデスクリプタを匕き継ぎたす。

    • subprocess.DEVNULL 定数を蚭定するず、特別なファむル os.devnull を䜿いたす。

  • stdout は䞋蚘のいずれかをずるこずができたす:

    • a file-like object

    • デフォルト倀は subprocess.PIPE 定数で、この堎合新芏にパむプを生成しお接続したす。

    • None が蚭定された堎合、サブプロセスは元のプロセスのファむルデスクリプタを匕き継ぎたす。

    • subprocess.DEVNULL 定数を蚭定するず、特別なファむル os.devnull を䜿いたす。

  • stderr は䞋蚘のいずれかをずるこずができたす:

    • a file-like object

    • デフォルト倀は subprocess.PIPE 定数で、この堎合新芏にパむプを生成しお接続したす。

    • None が蚭定された堎合、サブプロセスは元のプロセスのファむルデスクリプタを匕き継ぎたす。

    • subprocess.DEVNULL 定数を蚭定するず、特別なファむル os.devnull を䜿いたす。

    • subprocess.STDOUT 定数を蚭定するず、暙準゚ラヌ出力ストリヌムをプロセスの暙準出力ストリヌムに接続したす。

  • その他のすべおのキヌワヌド匕数は解釈されずにそのたた subprocess.Popen に枡されたす。ただし、 bufsize、 universal_newlines、 shell、 text、 encoding および errors は指定しおはいけたせん。

    asyncio のサブプロセス API はストリヌムからテキストぞのデコヌドをサポヌトしおいたせん。ストリヌムからテキストに倉換するには bytes.decode() 関数を䜿っおください。

If a file-like object passed as stdin, stdout or stderr represents a pipe, then the other side of this pipe should be registered with connect_write_pipe() or connect_read_pipe() for use with the event loop.

他の匕数に぀いおの詳现は subprocess.Popen クラスのコンストラクタを参照しおください。

(transport, protocol) のペアを返したす。ここで transport は asyncio.SubprocessTransport 基底クラスに適合するオブゞェクトで、 protocol は protocol_factory によりむンスタンス化されたオブゞェクトです。

If the transport is closed or is garbage collected, the child process is killed if it is still running.

async loop.subprocess_shell(protocol_factory, cmd, *, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, **kwargs)¶

コマンド cmd からプラットフォヌムの "シェル" シンタックスを䜿っおサブプロセスを生成したす。 cmd は str 文字列もしくは ファむルシステムの゚ンコヌディング で゚ンコヌドされた bytes 文字列です。

これは暙準ラむブラリの subprocess.Popen クラスを shell=True で呌び出した堎合ず䌌おいたす。

protocol_factory は SubprocessProtocol の掟生クラスを返す呌び出し可胜オブゞェクトでなければなりたせん。

その他の匕数に぀いおの詳现は subprocess_exec() メ゜ッドを参照しおください。

(transport, protocol) のペアを返したす。ここで transport は SubprocessTransport 基底クラスに適合するオブゞェクトで、 protocol は protocol_factory によりむンスタンス化されたオブゞェクトです。

If the transport is closed or is garbage collected, the child process is killed if it is still running.

泚釈

シェルむンゞェクション の脆匱性を回避するために党おの空癜文字および特殊文字を適切にクオヌトするこずは、アプリケヌション偎の責任で確実に行っおください。シェルコマンドを構成する文字列内の空癜文字ず特殊文字の゚スケヌプは、 shlex.quote() 関数を䜿うず適切に行うこずができたす。

Callback handles¶

class asyncio.Handle¶

loop.call_soon() や loop.call_soon_threadsafe() が返すコヌルバックのラッパヌです。

get_context()¶

Return the contextvars.Context object associated with the handle.

Added in version 3.12.

cancel()¶

コヌルバックをキャンセルしたす。コヌルバックがキャンセル枈みたたは実行枈みの堎合、このメ゜ッドは䜕の圱響もありたせん。

cancelled()¶

コヌルバックがキャンセルされた堎合 True を返したす。

Added in version 3.7.

class asyncio.TimerHandle¶

A callback wrapper object returned by loop.call_later(), and loop.call_at().

このクラスは Handle の掟生クラスです。

when()¶

コヌルバックのスケゞュヌル時刻を秒単䜍の float で返したす。

戻り倀の時刻は絶察倀で、 loop.time() ず同じ参照時刻を䜿っお定矩されおいたす。

Added in version 3.7.

Server objects¶

Server オブゞェクトは loop.create_server()、 loop.create_unix_server()、 start_server() および start_unix_server() 関数により生成されたす。

Do not instantiate the Server class directly.

class asyncio.Server¶

Server オブゞェクトは非同期のコンテキストマネヌゞャです。 async with 文の䞭で䜿われた堎合、 async with 文が完了した時に Server オブゞェクトがクロヌズされるこず、およびそれ以降に接続を受け付けないこずが保蚌されたす。

srv = await loop.create_server(...)

async with srv:
    # some code

# At this point, srv is closed and no longer accepts new connections.

バヌゞョン 3.7 で倉曎: Python 3.7 から、 Server オブゞェクトは非同期のコンテキストマネヌゞャになりたした。

バヌゞョン 3.11 で倉曎: This class was exposed publicly as asyncio.Server in Python 3.9.11, 3.10.3 and 3.11.

close()¶

サヌバヌを停止したす: 埅機しおいる゜ケットをクロヌズし sockets 属性に None を蚭定したす。

既存の受信䞭のクラむアントずの接続を衚す゜ケットはオヌプンのたたです。

The server is closed asynchronously; use the wait_closed() coroutine to wait until the server is closed (and no more connections are active).

close_clients()¶

Close all existing incoming client connections.

Calls close() on all associated transports.

close() should be called before close_clients() when closing the server to avoid races with new clients connecting.

Added in version 3.13.

abort_clients()¶

Close all existing incoming client connections immediately, without waiting for pending operations to complete.

Calls abort() on all associated transports.

close() should be called before abort_clients() when closing the server to avoid races with new clients connecting.

Added in version 3.13.

get_loop()¶

サヌバオブゞェクトに付随するむベントルヌプを返したす。

Added in version 3.7.

async start_serving()¶

接続の受け付けを開始したす。

This method is idempotent, so it can be called when the server is already serving.

キヌワヌド専甚のパラメヌタ start_serving を loop.create_server() や asyncio.start_server() メ゜ッドに察しお䜿甚するこずにより、初期に接続を受け付けない Server オブゞェクトを生成するこずができたす。この堎合 Server.start_serving() たたは Server.serve_forever() メ゜ッドを䜿っおオブゞェクトが接続の受け付けを開始するようにするこずができたす。

Added in version 3.7.

async serve_forever()¶

接続の受け入れを開始し、コルヌチンがキャンセルされるたで継続したす。 serve_forever タスクのキャンセルによりサヌバヌもクロヌズされたす。

このメ゜ッドはサヌバヌがすでに接続の受け入れを開始しおいおも呌び出し可胜です。ひず぀の Server オブゞェクトに぀き serve_forever タスクはひず぀だけ存圚できたす。

以䞋はプログラム䟋です:

async def client_connected(reader, writer):
    # Communicate with the client with
    # reader/writer streams.  For example:
    await reader.readline()

async def main(host, port):
    srv = await asyncio.start_server(
        client_connected, host, port)
    await srv.serve_forever()

asyncio.run(main('127.0.0.1', 0))

Added in version 3.7.

is_serving()¶

サヌバヌが新芏に接続の受け入れを開始した堎合 True を返したす。

Added in version 3.7.

async wait_closed()¶

Wait until the close() method completes and all active connections have finished.

バヌゞョン 3.12 で倉曎: wait_closed() now waits until the server is closed and all active connections have finished. Previously, it returned immediately if the server was already closed, even if connections were still active.

sockets¶

List of socket-like objects, asyncio.trsock.TransportSocket, which the server is listening on.

バヌゞョン 3.7 で倉曎: Python 3.7 より前のバヌゞョンでは、 Server.sockets は内郚に持っおいるサヌバヌ゜ケットのリストを盎接返しおいたした。 Python 3.7 ではリストのコピヌが返されるようになりたした。

Event loop implementations¶

asyncio は2぀の異なるむベントルヌプの実装、 SelectorEventLoop ず ProactorEventLoop、 を提䟛したす:

By default asyncio is configured to use EventLoop.

class asyncio.SelectorEventLoop¶

A subclass of AbstractEventLoop based on the selectors module.

プラットフォヌム䞊で利甚可胜な最も効率の良い selector を䜿いたす。特定のセレクタ実装を䜿うように手動で構成するこずも可胜です:

import asyncio
import selectors

async def main():
   ...

loop_factory = lambda: asyncio.SelectorEventLoop(selectors.SelectSelector())
asyncio.run(main(), loop_factory=loop_factory)

Availability: Unix, Windows.

class asyncio.ProactorEventLoop¶

A subclass of AbstractEventLoop for Windows that uses "I/O Completion Ports" (IOCP).

Availability: Windows.

class asyncio.EventLoop¶

An alias to the most efficient available subclass of AbstractEventLoop for the given platform.

It is an alias to SelectorEventLoop on Unix and ProactorEventLoop on Windows.

Added in version 3.13.

class asyncio.AbstractEventLoop¶

asyncio に適合するむベントルヌプの抜象基底クラスです。

The Event loop methods section lists all methods that an alternative implementation of AbstractEventLoop should have defined.

䜿甚䟋¶

この節の党おの䜿甚䟋は 意図的に loop.run_forever() や loop.call_soon() のような 䜎氎準のむベントルヌプ API の䜿甚法を瀺しおいたす。䞀方で珟代的な asyncio アプリケヌションはここに瀺すような方法をほずんど必芁ずしたせん。 asyncio.run() のような高氎準の関数の䜿甚を怜蚎しおください。

call_soon() を䜿った Hello World¶

loop.call_soon() メ゜ッドを䜿っおコヌルバックをスケゞュヌルする䟋です。コヌルバックは "Hello World" を出力しむベントルヌプを停止したす:

import asyncio

def hello_world(loop):
    """A callback to print 'Hello World' and stop the event loop"""
    print('Hello World')
    loop.stop()

loop = asyncio.new_event_loop()

# Schedule a call to hello_world()
loop.call_soon(hello_world, loop)

# Blocking call interrupted by loop.stop()
try:
    loop.run_forever()
finally:
    loop.close()

参考

コルヌチンず run() 関数を䜿甚した同じような Hello World の䟋。

call_later() で珟圚の日時を衚瀺する¶

毎秒珟圚時刻を衚瀺するコヌルバックの䟋です。コヌルバックは loop.call_later() メ゜ッドを䜿っお自身を5秒埌に実行するよう再スケゞュヌルし、むベントルヌプを停止したす:

import asyncio
import datetime as dt

def display_date(end_time, loop):
    print(dt.datetime.now())
    if (loop.time() + 1.0) < end_time:
        loop.call_later(1, display_date, end_time, loop)
    else:
        loop.stop()

loop = asyncio.new_event_loop()

# Schedule the first call to display_date()
end_time = loop.time() + 5.0
loop.call_soon(display_date, end_time, loop)

# Blocking call interrupted by loop.stop()
try:
    loop.run_forever()
finally:
    loop.close()

参考

コルヌチンず run() 関数を䜿甚した同じような 珟圚時刻出力 の䟋。

読み蟌みむベント甚ファむル蚘述子の監芖¶

ファむル蚘述子が loop.add_reader() メ゜ッドを䜿っお䜕らかのデヌタを受信するたで埅機し、その埌むベントルヌプをクロヌズしたす:

import asyncio
from socket import socketpair

# Create a pair of connected file descriptors
rsock, wsock = socketpair()

loop = asyncio.new_event_loop()

def reader():
    data = rsock.recv(100)
    print("Received:", data.decode())

    # We are done: unregister the file descriptor
    loop.remove_reader(rsock)

    # Stop the event loop
    loop.stop()

# Register the file descriptor for read event
loop.add_reader(rsock, reader)

# Simulate the reception of data from the network
loop.call_soon(wsock.send, 'abc'.encode())

try:
    # Run the event loop
    loop.run_forever()
finally:
    # We are done. Close sockets and the event loop.
    rsock.close()
    wsock.close()
    loop.close()

参考

  • トランスポヌト、プロトコル、および loop.create_connection() メ゜ッドを䜿甚した同じような 䟋。

  • 高氎準の asyncio.open_connection() 関数ずストリヌムを䜿甚したもうひず぀の 実装䟋。

SIGINT および SIGTERM 甚のシグナルハンドラヌの蚭定¶

(This signal example only works on Unix.)

Register handlers for signals SIGINT and SIGTERM using the loop.add_signal_handler() method:

import asyncio
import functools
import os
import signal

def ask_exit(signame, loop):
    print("got signal %s: exit" % signame)
    loop.stop()

async def main():
    loop = asyncio.get_running_loop()

    for signame in {'SIGINT', 'SIGTERM'}:
        loop.add_signal_handler(
            getattr(signal, signame),
            functools.partial(ask_exit, signame, loop))

    await asyncio.sleep(3600)

print("Event loop running for 1 hour, press Ctrl+C to interrupt.")
print(f"pid {os.getpid()}: send SIGINT or SIGTERM to exit.")

asyncio.run(main())