select --- I/O 完了の待機


このモジュールでは、ほとんどのオペレーティングシステムで利用可能な select() および poll() 関数、Solaris やその派生で利用可能な devpoll() 、Linux 2.5+ で利用可能な epoll() 、多くのBSDで利用可能な kqueue() 関数に対するアクセスを提供しています。 Windows 上ではソケットに対してしか動作しないので注意してください; その他のオペレーティングシステムでは、他のファイル形式でも (特に Unixではパイプにも) 動作します。通常のファイルに対して適用し、最後にファイルを読み出した時から内容が増えているかを決定するために使うことはできません。

注釈

The selectors module allows high-level and efficient I/O multiplexing, built upon the select module primitives. Users are encouraged to use the selectors module instead, unless they want precise control over the OS-level primitives used.

Availability: not WASI.

このモジュールは WebAssembly では動作しないか、利用不可です。詳しくは、WebAssembly プラットフォーム を見てください。

このモジュールは以下を定義します:

exception select.error

OSError の非推奨のエイリアスです。

バージョン 3.3 で変更: PEP 3151 に基づき、このクラスは OSError のエイリアスになりました。

select.devpoll()

Returns a /dev/poll polling object; see section /dev/poll polling objects below for the methods supported by devpoll objects.

devpoll() オブジェクトはインスタンス化時に許されるファイル記述子の数にリンクされます。プログラムがこの値を減らす場合 devpoll() は失敗します。プログラムがこの値を増やす場合 devpoll() は有効なファイル記述子の不完全なリストを返すことがあります。

新しいファイル記述子は 継承不可 です。

Added in version 3.3.

バージョン 3.4 で変更: 新しいファイル記述子が継承不可になりました。

Availability: Solaris.

select.epoll(sizehint=-1, flags=0)

Return an edge polling object, which can be used as Edge or Level Triggered interface for I/O events.

sizehint informs epoll about the expected number of events to be registered. It must be positive, or -1 to use the default. It is only used on older systems where epoll_create1() is not available; otherwise it has no effect (though its value is still checked).

flags is deprecated and completely ignored. However, when supplied, its value must be 0 or select.EPOLL_CLOEXEC, otherwise OSError is raised.

エッジポーリングオブジェクトが提供しているメソッドについては Edge and level trigger polling (epoll) objects 節を参照してください。

epoll オブジェクトはコンテキストマネジメントプロトコルをサポートしています。 with 文内で使用された場合、新たなファイル記述子はブロックの最後で自動的に閉じられます。

新しいファイル記述子は 継承不可 です。

バージョン 3.3 で変更: flags 引数が追加されました。

バージョン 3.4 で変更: with 文のサポートが追加されました。新しいファイル記述子が継承不可になりました。

バージョン 3.4 で非推奨: flags パラメータ。 現在ではデフォルトで select.EPOLL_CLOEXEC が使われます。 ファイルディスクリプタを継承可能にするには os.set_inheritable() を使ってください。

Availability: Linux >= 2.5.44.

select.poll()

Returns a polling object, which supports registering and unregistering file descriptors, and then polling them for I/O events; see section Polling objects below for the methods supported by polling objects.

Availability: Unix.

select.kqueue()

Returns a kernel queue object; see section Kqueue objects below for the methods supported by kqueue objects.

新しいファイル記述子は 継承不可 です。

バージョン 3.4 で変更: 新しいファイル記述子が継承不可になりました。

Availability: BSD, macOS.

select.kevent(ident, filter=KQ_FILTER_READ, flags=KQ_EV_ADD, fflags=0, data=0, udata=0)

Returns a kernel event object; see section Kevent objects below for the methods supported by kevent objects.

Availability: BSD, macOS.

select.select(rlist, wlist, xlist, timeout=None)

This is a straightforward interface to the Unix select() system call. The first three arguments are iterables of 'waitable objects': either integers representing file descriptors or objects with a parameterless method named fileno() returning such an integer:

  • rlist: 読み込み可能になるまで待機

  • wlist: 書き込み可能になるまで待機

  • xlist: "例外状態 (exceptional condition)" になるまで待機 ("例外状態" については、システムのマニュアルページを参照してください)

Empty iterables are allowed, but acceptance of three empty iterables is platform-dependent. (It is known to work on Unix but not on Windows.) The optional timeout argument specifies a time-out as a floating-point number in seconds. When the timeout argument is omitted or None, the function blocks until at least one file descriptor is ready. A time-out value of zero specifies a poll and never blocks.

戻り値は準備完了状態のオブジェクトからなる 3 つのリストです: したがってこのリストはそれぞれ関数の最初の 3 つの引数のサブセットになります。ファイル記述子のいずれも準備完了にならないままタイムアウトした場合、3 つの空のリストが返されます。

イテラブルの中に含めることのできるオブジェクトは Python ファイルオブジェクト (例えば sys.stdin や、 open() または os.popen() が返すオブジェクト)、 socket.socket() が返すソケットオブジェクトです。 ラッパー <wrapper> クラスを自分で定義することもできます。この場合、適切な (まったくデタラメな数ではなく本物のファイル記述子を返す) fileno() メソッドを持つ必要があります。

注釈

File objects on Windows are not acceptable, but sockets are. On Windows, the underlying select() function is provided by the WinSock library, and does not handle file descriptors that don't originate from WinSock.

バージョン 3.5 で変更: この関数は、シグナルによって中断された時に、 InterruptedError を上げる代わりに再計算されたタイムアウトによってリトライするようになりました。ただし、シグナルハンドラが例外を起こした場合を除きます (この論理的根拠については PEP 475 を見てください)。

select.PIPE_BUF

The minimum number of bytes which can be written without blocking to a pipe when the pipe has been reported as ready for writing by select(), poll() or another interface in this module. This doesn't apply to other kinds of file-like objects such as sockets.

この値は POSIX により少なくとも512であることが保証されています。

Availability: Unix

Added in version 3.2.

/dev/poll polling objects

Solaris and derivatives have /dev/poll. While select() is O(highest file descriptor) and poll() is O(number of file descriptors), /dev/poll is O(active file descriptors).

/dev/poll behaviour is very close to the standard poll() object.

devpoll.close()

ポーリングオブジェクトのファイル記述子を閉じます。

Added in version 3.4.

devpoll.closed

ポーリングオブジェクトが閉じている場合 True です。

Added in version 3.4.

devpoll.fileno()

ポーリングオブジェクトのファイル記述子番号を返します。

Added in version 3.4.

devpoll.register(fd[, eventmask])

ファイル記述子をポーリングオブジェクトに登録します。これ以降の poll() メソッド呼び出しでは、そのファイル記述子に処理待ち中の I/O イベントがあるかどうかを監視します。 fd は整数か、整数値を返す fileno() メソッドを持つオブジェクトを取ります。ファイルオブジェクトも fileno() を実装しているので、引数として使うことができます。

eventmask is an optional bitmask describing the type of events you want to check for. The constants are the same as with poll() object. The default value is a combination of the constants POLLIN, POLLPRI, and POLLOUT.

警告

Registering a file descriptor that's already registered is not an error, but the result is undefined. The appropriate action is to unregister or modify it first. This is an important difference compared with poll().

devpoll.modify(fd[, eventmask])

This method does an unregister() followed by a register(). It is (a bit) more efficient than doing the same explicitly.

devpoll.unregister(fd)

ポーリングオブジェクトによって追跡中のファイル記述子を登録解除します。 register() メソッドと同様に、 fd は整数か、整数値を返す fileno() メソッドを持つオブジェクトを取ります。

登録されていないファイル記述子の削除を試みるのは安全に無視されます。

devpoll.poll([timeout])

登録されたファイル記述子に対してポーリングを行い、報告すべき I/O イベントまたはエラーの発生したファイル記述子毎に 2 要素のタプル (fd, event) からなるリストを返します。リストは空になることもあります。 fd はファイル記述子で、 event は該当するファイル記述子について報告されたイベントを表すビットマスクです --- 例えば POLLIN は入力待ちを示し、 POLLOUT はファイル記述子に対する書き込みが可能を示す、などです。空のリストは呼び出しがタイムアウトしたか、報告すべきイベントがどのファイル記述子でも発生しなかったことを示します。 timeout が与えられた場合、処理を戻すまで待機する時間の長さをミリ秒単位で指定します。 timeout が省略されたり、 -1 であったり、あるいは None の場合、そのポーリングオブジェクトが監視している何らかのイベントが発生するまでブロックします。

バージョン 3.5 で変更: この関数は、シグナルによって中断された時に、 InterruptedError を上げる代わりに再計算されたタイムアウトによってリトライするようになりました。ただし、シグナルハンドラが例外を起こした場合を除きます (この論理的根拠については PEP 475 を見てください)。

Edge and level trigger polling (epoll) objects

https://linux.die.net/man/4/epoll

The eventmask is a bit mask using the following constants:

定数

意味

EPOLLIN

Available for read.

EPOLLOUT

Available for write.

EPOLLPRI

Urgent data for read.

EPOLLERR

Error condition happened on the associated fd.

EPOLLHUP

Hang up happened on the associated fd.

EPOLLET

Set Edge Trigger behavior, the default is Level Trigger behavior.

EPOLLONESHOT

Set one-shot behavior. After one event is pulled out, the fd is internally disabled.

EPOLLEXCLUSIVE

Wake only one epoll object when the associated fd has an event. The default (if this flag is not set) is to wake all epoll objects polling on an fd.

EPOLLRDHUP

ストリームソケットの他端が接続を切断したか、接続の書き込み側のシャットダウンを行った。

EPOLLRDNORM

EPOLLIN と同じ

EPOLLRDBAND

優先データバンドを読み込める。

EPOLLWRNORM

Equivalent to EPOLLOUT.

EPOLLWRBAND

優先データに書き込みできる。

EPOLLMSG

無視される。

EPOLLWAKEUP

Prevents sleep during event waiting.

Added in version 3.6: EPOLLEXCLUSIVE was added. It's only supported by Linux Kernel 4.5 or later.

Added in version 3.14: EPOLLWAKEUP was added. It's only supported by Linux Kernel 3.5 or later.

epoll.close()

epoll オブジェクトの制御用ファイル記述子を閉じます。

epoll.closed

epoll オブジェクトが閉じている場合 True です。

epoll.fileno()

制御用ファイル記述子の番号を返します。

epoll.fromfd(fd)

fd から epoll オブジェクトを作成します。

epoll.register(fd[, eventmask])

Register a file descriptor fd with the epoll object.

epoll.modify(fd, eventmask)

Modify a registered file descriptor fd.

epoll.unregister(fd)

epoll オブジェクトから登録されたファイル記述子 fd を削除します。

バージョン 3.9 で変更: The method no longer ignores the EBADF error.

epoll.poll(timeout=None, maxevents=-1)

Wait for events. timeout in seconds (float)

バージョン 3.5 で変更: この関数は、シグナルによって中断された時に、 InterruptedError を上げる代わりに再計算されたタイムアウトによってリトライするようになりました。ただし、シグナルハンドラが例外を起こした場合を除きます (この論理的根拠については PEP 475 を見てください)。

Polling objects

The poll() system call, supported on most Unix systems, provides better scalability for network servers that service many, many clients at the same time. poll() scales better because the system call only requires listing the file descriptors of interest, while select() builds a bitmap, turns on bits for the fds of interest, and then afterward the whole bitmap has to be linearly scanned again. select() is O(highest file descriptor), while poll() is O(number of file descriptors).

poll.register(fd[, eventmask])

ファイル記述子をポーリングオブジェクトに登録します。これ以降の poll() メソッド呼び出しでは、そのファイル記述子に処理待ち中の I/O イベントがあるかどうかを監視します。 fd は整数か、整数値を返す fileno() メソッドを持つオブジェクトを取ります。ファイルオブジェクトも fileno() を実装しているので、引数として使うことができます。

eventmask はオプションのビットマスクで、どの種類の I/O イベントを監視したいかを記述します。この値は以下の表で述べる定数 POLLINPOLLPRI 、および POLLOUT の組み合わせにすることができます。ビットマスクを指定しない場合、標準の値が使われ、 3 種類のイベント全てに対して監視が行われます。

定数

意味

POLLIN

There is data to read.

POLLPRI

There is urgent data to read.

POLLOUT

Ready for output: writing will not block.

POLLERR

Error condition of some sort.

POLLHUP

Hung up.

POLLRDHUP

Stream socket peer closed connection, or shut down writing half of connection.

POLLNVAL

Invalid request: descriptor not open.

登録済みのファイル記述子を登録してもエラーにはならず、一度だけ登録した場合と同じ効果になります。

poll.modify(fd, eventmask)

登録されているファイル記述子 fd を変更する。これは、 register(fd, eventmask) と同じ効果を持ちます。登録されていないファイル記述子に対してこのメソッドを呼び出すと、 errno ENOENTOSError 例外が発生します。

poll.unregister(fd)

ポーリングオブジェクトによって追跡中のファイル記述子を登録解除します。 register() メソッドと同様に、 fd は整数か、整数値を返す fileno() メソッドを持つオブジェクトを取ります。

登録されていないファイル記述子を登録解除しようとすると KeyError 例外が送出されます。

poll.poll([timeout])

登録されたファイル記述子に対してポーリングを行い、報告すべき I/O イベントまたはエラーの発生したファイル記述子毎に 2 要素のタプル (fd, event) からなるリストを返します。リストは空になることもあります。 fd はファイル記述子で、 event は該当するファイル記述子について報告されたイベントを表すビットマスクです --- 例えば POLLIN は入力待ちを示し、 POLLOUT はファイル記述子に対する書き込みが可能を示す、などです。空のリストは呼び出しがタイムアウトしたか、報告すべきイベントがどのファイル記述子でも発生しなかったことを示します。 timeout が与えられた場合、処理を戻すまで待機する時間の長さをミリ秒単位で指定します。 timeout が省略されたり、負の値であったり、あるいは None の場合、そのポーリングオブジェクトが監視している何らかのイベントが発生するまでブロックします。

バージョン 3.5 で変更: この関数は、シグナルによって中断された時に、 InterruptedError を上げる代わりに再計算されたタイムアウトによってリトライするようになりました。ただし、シグナルハンドラが例外を起こした場合を除きます (この論理的根拠については PEP 475 を見てください)。

Kqueue objects

kqueue.close()

kqueue オブジェクトの制御用ファイル記述子を閉じる。

kqueue.closed

kqueue オブジェクトが閉じている場合 True です。

kqueue.fileno()

制御用ファイル記述子の番号を返します。

kqueue.fromfd(fd)

与えられたファイル記述子から、kqueue オブジェクトを作成する。

kqueue.control(changelist, max_events[, timeout]) eventlist

kevent に対する低水準のインターフェース

  • changelist は kevent オブジェクトのイテラブルまたは None

  • max_events は 0 または正の整数

  • timeout in seconds (floats possible); the default is None, to wait forever

バージョン 3.5 で変更: この関数は、シグナルによって中断された時に、 InterruptedError を上げる代わりに再計算されたタイムアウトによってリトライするようになりました。ただし、シグナルハンドラが例外を起こした場合を除きます (この論理的根拠については PEP 475 を見てください)。

Kevent objects

https://man.freebsd.org/cgi/man.cgi?query=kqueue&sektion=2

kevent.ident

イベントを特定するための値。この値は、フィルタにもよりますが、大抵の場合はファイル記述子です。コンストラクタでは、 ident として、整数値か fileno() メソッドを持ったオブジェクトを渡せます。 kevent は内部で整数値を保存します。

kevent.filter

カーネルフィルタの名前。

定数

意味

KQ_FILTER_READ

Takes a descriptor and returns whenever there is data available to read.

KQ_FILTER_WRITE

Takes a descriptor and returns whenever there is data available to write.

KQ_FILTER_AIO

AIO requests.

KQ_FILTER_VNODE

Returns when one or more of the requested events watched in fflag occurs.

KQ_FILTER_PROC

Watch for events on a process ID.

KQ_FILTER_NETDEV

Watch for events on a network device (not available on macOS).

KQ_FILTER_SIGNAL

Returns whenever the watched signal is delivered to the process.

KQ_FILTER_TIMER

Establishes an arbitrary timer.

kevent.flags

フィルタアクション。

定数

意味

KQ_EV_ADD

Adds or modifies an event.

KQ_EV_DELETE

Removes an event from the queue.

KQ_EV_ENABLE

Permits control() to return the event.

KQ_EV_DISABLE

Disables event.

KQ_EV_ONESHOT

Removes event after first occurrence.

KQ_EV_CLEAR

Reset the state after an event is retrieved.

KQ_EV_SYSFLAGS

Internal event.

KQ_EV_FLAG1

Internal event.

KQ_EV_EOF

Filter-specific EOF condition.

KQ_EV_ERROR

See return values.

kevent.fflags

Filter-specific flags.

KQ_FILTER_READKQ_FILTER_WRITE フィルタのフラグ:

定数

意味

KQ_NOTE_LOWAT

Low water mark of a socket buffer.

KQ_FILTER_VNODE フィルタのフラグ:

定数

意味

KQ_NOTE_DELETE

unlink() was called.

KQ_NOTE_WRITE

A write occurred.

KQ_NOTE_EXTEND

The file was extended.

KQ_NOTE_ATTRIB

An attribute was changed.

KQ_NOTE_LINK

The link count has changed.

KQ_NOTE_RENAME

The file was renamed.

KQ_NOTE_REVOKE

Access to the file was revoked.

KQ_FILTER_PROC フィルタフラグ:

定数

意味

KQ_NOTE_EXIT

The process has exited.

KQ_NOTE_FORK

The process has called fork().

KQ_NOTE_EXEC

The process has executed a new process.

KQ_NOTE_PCTRLMASK

Internal filter flag.

KQ_NOTE_PDATAMASK

Internal filter flag.

KQ_NOTE_TRACK

Follow a process across fork().

KQ_NOTE_CHILD

Returned on the child process for NOTE_TRACK.

KQ_NOTE_TRACKERR

Unable to attach to a child.

KQ_FILTER_NETDEV フィルタフラグ (macOS では利用不可):

定数

意味

KQ_NOTE_LINKUP

Link is up.

KQ_NOTE_LINKDOWN

Link is down.

KQ_NOTE_LINKINV

Link state is invalid.

kevent.data

Filter-specific data.

kevent.udata

User-defined value.