selectors --- 高階 I/O 多工

在 3.4 版被加入.

原始碼:Lib/selectors.py


簡介

This module allows high-level and efficient I/O multiplexing, built upon theselect module primitives. Users are encouraged to use this moduleinstead, unless they want precise control over the OS-level primitives used.

It defines aBaseSelector abstract base class, along with severalconcrete implementations (KqueueSelector,EpollSelector...),that can be used to wait for I/O readiness notification on multiple fileobjects. In the following, "file object" refers to any object with afileno() method, or a raw file descriptor. Seefile object.

DefaultSelector is an alias to the most efficient implementationavailable on the current platform: this should be the default choice for mostusers.

備註

The type of file objects supported depends on the platform: on Windows,sockets are supported, but not pipes, whereas on Unix, both are supported(some other types may be supported as well, such as fifos or special filedevices).

也參考

select

Low-level I/O multiplexing module.

適用: not WASI.

此模組在 WebAssembly 平台上不起作用或無法使用。更多資訊請參閱WebAssembly 平台

Classes

Classes hierarchy:

BaseSelector+--SelectSelector+--PollSelector+--EpollSelector+--DevpollSelector+--KqueueSelector

In the following,events is a bitwise mask indicating which I/O events shouldbe waited for on a given file object. It can be a combination of the modulesconstants below:

常數

含義

selectors.EVENT_READ

Available for read

selectors.EVENT_WRITE

Available for write

classselectors.SelectorKey

ASelectorKey is anamedtuple used toassociate a file object to its underlying file descriptor, selected eventmask and attached data. It is returned by severalBaseSelectormethods.

fileobj

File object registered.

fd

Underlying file descriptor.

events

Events that must be waited for on this file object.

data

Optional opaque data associated to this file object: for example, thiscould be used to store a per-client session ID.

classselectors.BaseSelector

ABaseSelector is used to wait for I/O event readiness on multiplefile objects. It supports file stream registration, unregistration, and amethod to wait for I/O events on those streams, with an optional timeout.It's an abstract base class, so cannot be instantiated. UseDefaultSelector instead, or one ofSelectSelector,KqueueSelector etc. if you want to specifically use animplementation, and your platform supports it.BaseSelector and its concrete implementations support thecontext manager protocol.

abstractmethodregister(fileobj,events,data=None)

Register a file object for selection, monitoring it for I/O events.

fileobj is the file object to monitor. It may either be an integerfile descriptor or an object with afileno() method.events is a bitwise mask of events to monitor.data is an opaque object.

This returns a newSelectorKey instance, or raises aValueError in case of invalid event mask or file descriptor, orKeyError if the file object is already registered.

abstractmethodunregister(fileobj)

Unregister a file object from selection, removing it from monitoring. Afile object shall be unregistered prior to being closed.

fileobj must be a file object previously registered.

This returns the associatedSelectorKey instance, or raises aKeyError iffileobj is not registered. It will raiseValueError iffileobj is invalid (e.g. it has nofileno()method or itsfileno() method has an invalid return value).

modify(fileobj,events,data=None)

Change a registered file object's monitored events or attached data.

This is equivalent toBaseSelector.unregister(fileobj) followedbyBaseSelector.register(fileobj,events,data), except that itcan be implemented more efficiently.

This returns a newSelectorKey instance, or raises aValueError in case of invalid event mask or file descriptor, orKeyError if the file object is not registered.

abstractmethodselect(timeout=None)

Wait until some registered file objects become ready, or the timeoutexpires.

Iftimeout>0, this specifies the maximum wait time, in seconds.Iftimeout<=0, the call won't block, and will report the currentlyready file objects.Iftimeout isNone, the call will block until a monitored file objectbecomes ready.

This returns a list of(key,events) tuples, one for each ready fileobject.

key is theSelectorKey instance corresponding to a ready fileobject.events is a bitmask of events ready on this file object.

備註

This method can return before any file object becomes ready or thetimeout has elapsed if the current process receives a signal: in thiscase, an empty list will be returned.

在 3.5 版的變更:The selector is now retried with a recomputed timeout when interruptedby a signal if the signal handler did not raise an exception (seePEP 475 for the rationale), instead of returning an empty listof events before the timeout.

close()

Close the selector.

This must be called to make sure that any underlying resource is freed.The selector shall not be used once it has been closed.

get_key(fileobj)

Return the key associated with a registered file object.

This returns theSelectorKey instance associated to this fileobject, or raisesKeyError if the file object is not registered.

abstractmethodget_map()

Return a mapping of file objects to selector keys.

This returns aMapping instance mappingregistered file objects to their associatedSelectorKeyinstance.

classselectors.DefaultSelector

The default selector class, using the most efficient implementationavailable on the current platform. This should be the default choice formost users.

classselectors.SelectSelector

select.select()-based selector.

classselectors.PollSelector

select.poll()-based selector.

classselectors.EpollSelector

select.epoll()-based selector.

fileno()

This returns the file descriptor used by the underlyingselect.epoll() object.

classselectors.DevpollSelector

select.devpoll()-based selector.

fileno()

This returns the file descriptor used by the underlyingselect.devpoll() object.

在 3.5 版被加入.

classselectors.KqueueSelector

select.kqueue()-based selector.

fileno()

This returns the file descriptor used by the underlyingselect.kqueue() object.

範例

Here is a simple echo server implementation:

importselectorsimportsocketsel=selectors.DefaultSelector()defaccept(sock,mask):conn,addr=sock.accept()# Should be readyprint('accepted',conn,'from',addr)conn.setblocking(False)sel.register(conn,selectors.EVENT_READ,read)defread(conn,mask):data=conn.recv(1000)# Should be readyifdata:print('echoing',repr(data),'to',conn)conn.send(data)# Hope it won't blockelse:print('closing',conn)sel.unregister(conn)conn.close()sock=socket.socket()sock.bind(('localhost',1234))sock.listen(100)sock.setblocking(False)sel.register(sock,selectors.EVENT_READ,accept)whileTrue:events=sel.select()forkey,maskinevents:callback=key.datacallback(key.fileobj,mask)