blob: fa6a29604ca2ba4f395ca9efebd25912fe165b87 [file] [log] [blame]
R David Murray6a143812013-12-20 14:37:39 -05001.. currentmodule:: asyncio
Victor Stinnerea3183f2013-12-03 01:08:00 +01002
Victor Stinner9592edb2014-02-02 15:03:02 +01003.. _asyncio-event-loop:
Victor Stinnerea3183f2013-12-03 01:08:00 +01004
Victor Stinneraea82292014-07-08 23:42:38 +02005Base Event Loop
6===============
Victor Stinnerea3183f2013-12-03 01:08:00 +01007
8The event loop is the central execution device provided by :mod:`asyncio`.
Zachary Ware5e580da2015-08-27 15:54:39 -05009It provides multiple facilities, including:
Victor Stinnerea3183f2013-12-03 01:08:00 +010010
Eli Benderskyb73c8332014-02-09 06:07:47 -080011* Registering, executing and cancelling delayed calls (timeouts).
Victor Stinnerea3183f2013-12-03 01:08:00 +010012
Victor Stinner9592edb2014-02-02 15:03:02 +010013* Creating client and server :ref:`transports <asyncio-transport>` for various
Eli Benderskyb73c8332014-02-09 06:07:47 -080014 kinds of communication.
Victor Stinnerea3183f2013-12-03 01:08:00 +010015
Eli Bendersky136fea22014-02-09 06:55:58 -080016* Launching subprocesses and the associated :ref:`transports
17 <asyncio-transport>` for communication with an external program.
Victor Stinnerea3183f2013-12-03 01:08:00 +010018
Eli Benderskyb73c8332014-02-09 06:07:47 -080019* Delegating costly function calls to a pool of threads.
Victor Stinnerea3183f2013-12-03 01:08:00 +010020
Victor Stinneraea82292014-07-08 23:42:38 +020021.. class:: BaseEventLoop
Eli Bendersky136fea22014-02-09 06:55:58 -080022
Guido van Rossumf68afd82016-08-08 09:41:21 -070023 This class is an implementation detail. It is a subclass of
24 :class:`AbstractEventLoop` and may be a base class of concrete
25 event loop implementations found in :mod:`asyncio`. It should not
26 be used directly; use :class:`AbstractEventLoop` instead.
27 ``BaseEventLoop`` should not be subclassed by third-party code; the
28 internal interface is not stable.
29
30.. class:: AbstractEventLoop
31
32 Abstract base class of event loops.
Victor Stinnerea3183f2013-12-03 01:08:00 +010033
Victor Stinner83704962015-02-25 14:24:15 +010034 This class is :ref:`not thread safe <asyncio-multithreading>`.
35
Victor Stinnerea3183f2013-12-03 01:08:00 +010036Run an event loop
37-----------------
38
Guido van Rossumf68afd82016-08-08 09:41:21 -070039.. method:: AbstractEventLoop.run_forever()
Victor Stinnerea3183f2013-12-03 01:08:00 +010040
Guido van Rossum41f69f42015-11-19 13:28:47 -080041 Run until :meth:`stop` is called. If :meth:`stop` is called before
42 :meth:`run_forever()` is called, this polls the I/O selector once
43 with a timeout of zero, runs all callbacks scheduled in response to
44 I/O events (and those that were already scheduled), and then exits.
45 If :meth:`stop` is called while :meth:`run_forever` is running,
46 this will run the current batch of callbacks and then exit. Note
47 that callbacks scheduled by callbacks will not run in that case;
48 they will run the next time :meth:`run_forever` is called.
49
Guido van Rossum82f9fea2015-11-19 13:33:34 -080050 .. versionchanged:: 3.5.1
Victor Stinnerea3183f2013-12-03 01:08:00 +010051
Guido van Rossumf68afd82016-08-08 09:41:21 -070052.. method:: AbstractEventLoop.run_until_complete(future)
Victor Stinnerea3183f2013-12-03 01:08:00 +010053
Victor Stinner99c2ab42013-12-03 19:17:25 +010054 Run until the :class:`Future` is done.
Victor Stinnerea3183f2013-12-03 01:08:00 +010055
Victor Stinner530ef2f2014-07-08 12:39:10 +020056 If the argument is a :ref:`coroutine object <coroutine>`, it is wrapped by
Yury Selivanov04356e12015-06-30 22:13:22 -040057 :func:`ensure_future`.
Victor Stinnerea3183f2013-12-03 01:08:00 +010058
59 Return the Future's result, or raise its exception.
60
Guido van Rossumf68afd82016-08-08 09:41:21 -070061.. method:: AbstractEventLoop.is_running()
Victor Stinnerea3183f2013-12-03 01:08:00 +010062
63 Returns running status of event loop.
64
Guido van Rossumf68afd82016-08-08 09:41:21 -070065.. method:: AbstractEventLoop.stop()
Victor Stinnerea3183f2013-12-03 01:08:00 +010066
67 Stop running the event loop.
68
Guido van Rossum41f69f42015-11-19 13:28:47 -080069 This causes :meth:`run_forever` to exit at the next suitable
70 opportunity (see there for more details).
71
Guido van Rossum82f9fea2015-11-19 13:33:34 -080072 .. versionchanged:: 3.5.1
Victor Stinnerea3183f2013-12-03 01:08:00 +010073
Guido van Rossumf68afd82016-08-08 09:41:21 -070074.. method:: AbstractEventLoop.is_closed()
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +020075
76 Returns ``True`` if the event loop was closed.
77
78 .. versionadded:: 3.4.2
79
Guido van Rossumf68afd82016-08-08 09:41:21 -070080.. method:: AbstractEventLoop.close()
Victor Stinnerea3183f2013-12-03 01:08:00 +010081
Guido van Rossum41f69f42015-11-19 13:28:47 -080082 Close the event loop. The loop must not be running. Pending
83 callbacks will be lost.
Victor Stinnerea3183f2013-12-03 01:08:00 +010084
85 This clears the queues and shuts down the executor, but does not wait for
86 the executor to finish.
87
88 This is idempotent and irreversible. No other methods should be called after
89 this one.
90
Yury Selivanov03660042016-12-15 17:36:05 -050091
92.. coroutinemethod:: AbstractEventLoop.shutdown_asyncgens()
93
94 Schedule all currently open :term:`asynchronous generator` objects to
95 close with an :meth:`~agen.aclose()` call. After calling this method,
96 the event loop will issue a warning whenever a new asynchronous generator
97 is iterated. Should be used to finalize all scheduled asynchronous
98 generators reliably. Example::
99
100 try:
101 loop.run_forever()
102 finally:
103 loop.run_until_complete(loop.shutdown_asyncgens())
104 loop.close()
105
106 .. versionadded:: 3.6
107
108
Victor Stinner8464c242014-11-28 13:15:41 +0100109.. _asyncio-pass-keywords:
Victor Stinnerea3183f2013-12-03 01:08:00 +0100110
111Calls
112-----
113
Victor Stinner8464c242014-11-28 13:15:41 +0100114Most :mod:`asyncio` functions don't accept keywords. If you want to pass
115keywords to your callback, use :func:`functools.partial`. For example,
116``loop.call_soon(functools.partial(print, "Hello", flush=True))`` will call
117``print("Hello", flush=True)``.
118
119.. note::
120 :func:`functools.partial` is better than ``lambda`` functions, because
121 :mod:`asyncio` can inspect :func:`functools.partial` object to display
122 parameters in debug mode, whereas ``lambda`` functions have a poor
123 representation.
124
Guido van Rossumf68afd82016-08-08 09:41:21 -0700125.. method:: AbstractEventLoop.call_soon(callback, \*args)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100126
Victor Stinner4d5115c2014-12-15 17:50:55 +0100127 Arrange for a callback to be called as soon as possible. The callback is
128 called after :meth:`call_soon` returns, when control returns to the event
129 loop.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100130
Serhiy Storchaka4ecfa452016-05-16 09:31:54 +0300131 This operates as a :abbr:`FIFO (first-in, first-out)` queue, callbacks
132 are called in the order in which they are registered. Each callback
133 will be called exactly once.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100134
135 Any positional arguments after the callback will be passed to the
136 callback when it is called.
137
Yury Selivanov1096f762015-06-25 13:49:52 -0400138 An instance of :class:`asyncio.Handle` is returned, which can be
139 used to cancel the callback.
Yury Selivanov43ee1c12014-02-19 20:58:44 -0500140
Victor Stinner8464c242014-11-28 13:15:41 +0100141 :ref:`Use functools.partial to pass keywords to the callback
142 <asyncio-pass-keywords>`.
143
Guido van Rossumf68afd82016-08-08 09:41:21 -0700144.. method:: AbstractEventLoop.call_soon_threadsafe(callback, \*args)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100145
146 Like :meth:`call_soon`, but thread safe.
147
Victor Stinner83704962015-02-25 14:24:15 +0100148 See the :ref:`concurrency and multithreading <asyncio-multithreading>`
149 section of the documentation.
150
Victor Stinnerea3183f2013-12-03 01:08:00 +0100151
Victor Stinner45b27ed2014-02-01 02:36:43 +0100152.. _asyncio-delayed-calls:
153
Victor Stinnerea3183f2013-12-03 01:08:00 +0100154Delayed calls
155-------------
156
157The event loop has its own internal clock for computing timeouts.
158Which clock is used depends on the (platform-specific) event loop
159implementation; ideally it is a monotonic clock. This will generally be
160a different clock than :func:`time.time`.
161
Victor Stinnerfd9d3742014-02-18 09:37:43 +0100162.. note::
163
164 Timeouts (relative *delay* or absolute *when*) should not exceed one day.
165
Victor Stinner45b27ed2014-02-01 02:36:43 +0100166
Guido van Rossumf68afd82016-08-08 09:41:21 -0700167.. method:: AbstractEventLoop.call_later(delay, callback, *args)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100168
169 Arrange for the *callback* to be called after the given *delay*
170 seconds (either an int or float).
171
Yury Selivanov1096f762015-06-25 13:49:52 -0400172 An instance of :class:`asyncio.Handle` is returned, which can be
173 used to cancel the callback.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100174
175 *callback* will be called exactly once per call to :meth:`call_later`.
176 If two callbacks are scheduled for exactly the same time, it is
177 undefined which will be called first.
178
179 The optional positional *args* will be passed to the callback when it
180 is called. If you want the callback to be called with some named
181 arguments, use a closure or :func:`functools.partial`.
182
Victor Stinner8464c242014-11-28 13:15:41 +0100183 :ref:`Use functools.partial to pass keywords to the callback
184 <asyncio-pass-keywords>`.
185
Guido van Rossumf68afd82016-08-08 09:41:21 -0700186.. method:: AbstractEventLoop.call_at(when, callback, *args)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100187
188 Arrange for the *callback* to be called at the given absolute timestamp
Berker Peksagb5563992014-11-07 19:51:07 +0200189 *when* (an int or float), using the same time reference as
Guido van Rossumf68afd82016-08-08 09:41:21 -0700190 :meth:`AbstractEventLoop.time`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100191
192 This method's behavior is the same as :meth:`call_later`.
193
Yury Selivanov1096f762015-06-25 13:49:52 -0400194 An instance of :class:`asyncio.Handle` is returned, which can be
195 used to cancel the callback.
196
Victor Stinner8464c242014-11-28 13:15:41 +0100197 :ref:`Use functools.partial to pass keywords to the callback
198 <asyncio-pass-keywords>`.
199
Guido van Rossumf68afd82016-08-08 09:41:21 -0700200.. method:: AbstractEventLoop.time()
Victor Stinnerea3183f2013-12-03 01:08:00 +0100201
202 Return the current time, as a :class:`float` value, according to the
203 event loop's internal clock.
204
Victor Stinner3e09e322013-12-03 01:22:06 +0100205.. seealso::
206
207 The :func:`asyncio.sleep` function.
208
Victor Stinnerea3183f2013-12-03 01:08:00 +0100209
Yury Selivanov950204d2016-05-16 16:23:00 -0400210Futures
211-------
212
Guido van Rossumf68afd82016-08-08 09:41:21 -0700213.. method:: AbstractEventLoop.create_future()
Yury Selivanov950204d2016-05-16 16:23:00 -0400214
215 Create an :class:`asyncio.Future` object attached to the loop.
216
217 This is a preferred way to create futures in asyncio, as event
218 loop implementations can provide alternative implementations
219 of the Future class (with better performance or instrumentation).
220
221 .. versionadded:: 3.5.2
222
223
Yury Selivanovbb961342015-06-25 11:54:34 -0400224Tasks
225-----
Victor Stinner530ef2f2014-07-08 12:39:10 +0200226
Guido van Rossumf68afd82016-08-08 09:41:21 -0700227.. method:: AbstractEventLoop.create_task(coro)
Victor Stinner530ef2f2014-07-08 12:39:10 +0200228
229 Schedule the execution of a :ref:`coroutine object <coroutine>`: wrap it in
230 a future. Return a :class:`Task` object.
231
232 Third-party event loops can use their own subclass of :class:`Task` for
233 interoperability. In this case, the result type is a subclass of
234 :class:`Task`.
235
Victor Stinner337e03f2014-08-11 01:11:13 +0200236 This method was added in Python 3.4.2. Use the :func:`async` function to
237 support also older Python versions.
Victor Stinner530ef2f2014-07-08 12:39:10 +0200238
239 .. versionadded:: 3.4.2
240
Guido van Rossumf68afd82016-08-08 09:41:21 -0700241.. method:: AbstractEventLoop.set_task_factory(factory)
Yury Selivanov71854612015-05-11 16:28:27 -0400242
243 Set a task factory that will be used by
Guido van Rossumf68afd82016-08-08 09:41:21 -0700244 :meth:`AbstractEventLoop.create_task`.
Yury Selivanov71854612015-05-11 16:28:27 -0400245
246 If *factory* is ``None`` the default task factory will be set.
247
248 If *factory* is a *callable*, it should have a signature matching
249 ``(loop, coro)``, where *loop* will be a reference to the active
250 event loop, *coro* will be a coroutine object. The callable
251 must return an :class:`asyncio.Future` compatible object.
252
253 .. versionadded:: 3.4.4
254
Guido van Rossumf68afd82016-08-08 09:41:21 -0700255.. method:: AbstractEventLoop.get_task_factory()
Yury Selivanov71854612015-05-11 16:28:27 -0400256
257 Return a task factory, or ``None`` if the default one is in use.
258
259 .. versionadded:: 3.4.4
260
Victor Stinner530ef2f2014-07-08 12:39:10 +0200261
Victor Stinnerea3183f2013-12-03 01:08:00 +0100262Creating connections
Victor Stinner0c6f1ca2013-12-03 01:46:39 +0100263--------------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100264
Guido van Rossumf68afd82016-08-08 09:41:21 -0700265.. coroutinemethod:: AbstractEventLoop.create_connection(protocol_factory, host=None, port=None, \*, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100266
267 Create a streaming transport connection to a given Internet *host* and
Victor Stinnera6919aa2014-02-19 13:32:34 +0100268 *port*: socket family :py:data:`~socket.AF_INET` or
269 :py:data:`~socket.AF_INET6` depending on *host* (or *family* if specified),
270 socket type :py:data:`~socket.SOCK_STREAM`. *protocol_factory* must be a
271 callable returning a :ref:`protocol <asyncio-protocol>` instance.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100272
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500273 This method is a :ref:`coroutine <coroutine>` which will try to
Victor Stinnerea3183f2013-12-03 01:08:00 +0100274 establish the connection in the background. When successful, the
275 coroutine returns a ``(transport, protocol)`` pair.
276
277 The chronological synopsis of the underlying operation is as follows:
278
Victor Stinner9592edb2014-02-02 15:03:02 +0100279 #. The connection is established, and a :ref:`transport <asyncio-transport>`
Victor Stinnerea3183f2013-12-03 01:08:00 +0100280 is created to represent it.
281
282 #. *protocol_factory* is called without arguments and must return a
Victor Stinner9592edb2014-02-02 15:03:02 +0100283 :ref:`protocol <asyncio-protocol>` instance.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100284
285 #. The protocol instance is tied to the transport, and its
286 :meth:`connection_made` method is called.
287
288 #. The coroutine returns successfully with the ``(transport, protocol)``
289 pair.
290
291 The created transport is an implementation-dependent bidirectional stream.
292
293 .. note::
294 *protocol_factory* can be any kind of callable, not necessarily
295 a class. For example, if you want to use a pre-created
296 protocol instance, you can pass ``lambda: my_protocol``.
297
Martin Panterc04fb562016-02-10 05:44:01 +0000298 Options that change how the connection is created:
Victor Stinnerea3183f2013-12-03 01:08:00 +0100299
300 * *ssl*: if given and not false, a SSL/TLS transport is created
301 (by default a plain TCP transport is created). If *ssl* is
302 a :class:`ssl.SSLContext` object, this context is used to create
303 the transport; if *ssl* is :const:`True`, a context with some
304 unspecified default settings is used.
305
Berker Peksag9c1dba22014-09-28 00:00:58 +0300306 .. seealso:: :ref:`SSL/TLS security considerations <ssl-security>`
Antoine Pitrouc5e075f2014-03-22 18:19:11 +0100307
Victor Stinnerea3183f2013-12-03 01:08:00 +0100308 * *server_hostname*, is only for use together with *ssl*,
309 and sets or overrides the hostname that the target server's certificate
310 will be matched against. By default the value of the *host* argument
311 is used. If *host* is empty, there is no default and you must pass a
312 value for *server_hostname*. If *server_hostname* is an empty
313 string, hostname matching is disabled (which is a serious security
314 risk, allowing for man-in-the-middle-attacks).
315
316 * *family*, *proto*, *flags* are the optional address family, protocol
317 and flags to be passed through to getaddrinfo() for *host* resolution.
318 If given, these should all be integers from the corresponding
319 :mod:`socket` module constants.
320
321 * *sock*, if given, should be an existing, already connected
322 :class:`socket.socket` object to be used by the transport.
323 If *sock* is given, none of *host*, *port*, *family*, *proto*, *flags*
324 and *local_addr* should be specified.
325
326 * *local_addr*, if given, is a ``(local_host, local_port)`` tuple used
327 to bind the socket to locally. The *local_host* and *local_port*
328 are looked up using getaddrinfo(), similarly to *host* and *port*.
329
Victor Stinner60208a12015-09-15 22:41:52 +0200330 .. versionchanged:: 3.5
331
332 On Windows with :class:`ProactorEventLoop`, SSL/TLS is now supported.
Victor Stinner41f3c3f2014-08-31 14:47:37 +0200333
Victor Stinnerc8ea8132014-01-23 11:02:09 +0100334 .. seealso::
335
336 The :func:`open_connection` function can be used to get a pair of
337 (:class:`StreamReader`, :class:`StreamWriter`) instead of a protocol.
338
Victor Stinnerea3183f2013-12-03 01:08:00 +0100339
Guido van Rossumf68afd82016-08-08 09:41:21 -0700340.. coroutinemethod:: AbstractEventLoop.create_datagram_endpoint(protocol_factory, local_addr=None, remote_addr=None, \*, family=0, proto=0, flags=0, reuse_address=None, reuse_port=None, allow_broadcast=None, sock=None)
Victor Stinnera6919aa2014-02-19 13:32:34 +0100341
342 Create datagram connection: socket family :py:data:`~socket.AF_INET` or
343 :py:data:`~socket.AF_INET6` depending on *host* (or *family* if specified),
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700344 socket type :py:data:`~socket.SOCK_DGRAM`. *protocol_factory* must be a
345 callable returning a :ref:`protocol <asyncio-protocol>` instance.
Victor Stinnera6919aa2014-02-19 13:32:34 +0100346
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500347 This method is a :ref:`coroutine <coroutine>` which will try to
Victor Stinnera6919aa2014-02-19 13:32:34 +0100348 establish the connection in the background. When successful, the
349 coroutine returns a ``(transport, protocol)`` pair.
350
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700351 Options changing how the connection is created:
352
353 * *local_addr*, if given, is a ``(local_host, local_port)`` tuple used
354 to bind the socket to locally. The *local_host* and *local_port*
355 are looked up using :meth:`getaddrinfo`.
356
357 * *remote_addr*, if given, is a ``(remote_host, remote_port)`` tuple used
358 to connect the socket to a remote address. The *remote_host* and
359 *remote_port* are looked up using :meth:`getaddrinfo`.
360
361 * *family*, *proto*, *flags* are the optional address family, protocol
362 and flags to be passed through to :meth:`getaddrinfo` for *host*
363 resolution. If given, these should all be integers from the
364 corresponding :mod:`socket` module constants.
365
366 * *reuse_address* tells the kernel to reuse a local socket in
367 TIME_WAIT state, without waiting for its natural timeout to
Serhiy Storchaka4adf01c2016-10-19 18:30:05 +0300368 expire. If not specified will automatically be set to ``True`` on
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700369 UNIX.
370
371 * *reuse_port* tells the kernel to allow this endpoint to be bound to the
372 same port as other existing endpoints are bound to, so long as they all
373 set this flag when being created. This option is not supported on Windows
374 and some UNIX's. If the :py:data:`~socket.SO_REUSEPORT` constant is not
375 defined then this capability is unsupported.
376
377 * *allow_broadcast* tells the kernel to allow this endpoint to send
378 messages to the broadcast address.
379
380 * *sock* can optionally be specified in order to use a preexisting,
381 already connected, :class:`socket.socket` object to be used by the
382 transport. If specified, *local_addr* and *remote_addr* should be omitted
383 (must be :const:`None`).
Victor Stinnera6919aa2014-02-19 13:32:34 +0100384
Victor Stinner41f3c3f2014-08-31 14:47:37 +0200385 On Windows with :class:`ProactorEventLoop`, this method is not supported.
386
Victor Stinnerc7edffd2014-10-12 11:24:26 +0200387 See :ref:`UDP echo client protocol <asyncio-udp-echo-client-protocol>` and
388 :ref:`UDP echo server protocol <asyncio-udp-echo-server-protocol>` examples.
389
Victor Stinnera6919aa2014-02-19 13:32:34 +0100390
Guido van Rossumf68afd82016-08-08 09:41:21 -0700391.. coroutinemethod:: AbstractEventLoop.create_unix_connection(protocol_factory, path, \*, ssl=None, sock=None, server_hostname=None)
Victor Stinnera6919aa2014-02-19 13:32:34 +0100392
393 Create UNIX connection: socket family :py:data:`~socket.AF_UNIX`, socket
394 type :py:data:`~socket.SOCK_STREAM`. The :py:data:`~socket.AF_UNIX` socket
395 family is used to communicate between processes on the same machine
396 efficiently.
397
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500398 This method is a :ref:`coroutine <coroutine>` which will try to
Victor Stinnera6919aa2014-02-19 13:32:34 +0100399 establish the connection in the background. When successful, the
400 coroutine returns a ``(transport, protocol)`` pair.
401
Guido van Rossum9e80eeb2016-11-03 14:17:25 -0700402 *path* is the name of a UNIX domain socket, and is required unless a *sock*
403 parameter is specified. Abstract UNIX sockets, :class:`str`, and
404 :class:`bytes` paths are supported.
405
Guido van Rossumf68afd82016-08-08 09:41:21 -0700406 See the :meth:`AbstractEventLoop.create_connection` method for parameters.
Victor Stinnera6919aa2014-02-19 13:32:34 +0100407
408 Availability: UNIX.
409
410
Victor Stinnerea3183f2013-12-03 01:08:00 +0100411Creating listening connections
412------------------------------
413
Guido van Rossumf68afd82016-08-08 09:41:21 -0700414.. coroutinemethod:: AbstractEventLoop.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)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100415
Victor Stinner33f6abe2014-10-12 20:36:04 +0200416 Create a TCP server (socket type :data:`~socket.SOCK_STREAM`) bound to
417 *host* and *port*.
418
419 Return a :class:`Server` object, its :attr:`~Server.sockets` attribute
420 contains created sockets. Use the :meth:`Server.close` method to stop the
421 server: close listening sockets.
422
423 Parameters:
424
Victor Stinner5e4a7d82015-09-21 18:33:43 +0200425 * The *host* parameter can be a string, in that case the TCP server is
426 bound to *host* and *port*. The *host* parameter can also be a sequence
427 of strings and in that case the TCP server is bound to all hosts of the
428 sequence. If *host* is an empty string or ``None``, all interfaces are
429 assumed and a list of multiple sockets will be returned (most likely one
430 for IPv4 and another one for IPv6).
Victor Stinner33f6abe2014-10-12 20:36:04 +0200431
432 * *family* can be set to either :data:`socket.AF_INET` or
433 :data:`~socket.AF_INET6` to force the socket to use IPv4 or IPv6. If not set
434 it will be determined from host (defaults to :data:`socket.AF_UNSPEC`).
435
436 * *flags* is a bitmask for :meth:`getaddrinfo`.
437
438 * *sock* can optionally be specified in order to use a preexisting
439 socket object. If specified, *host* and *port* should be omitted (must be
440 :const:`None`).
441
442 * *backlog* is the maximum number of queued connections passed to
443 :meth:`~socket.socket.listen` (defaults to 100).
444
445 * *ssl* can be set to an :class:`~ssl.SSLContext` to enable SSL over the
446 accepted connections.
447
448 * *reuse_address* tells the kernel to reuse a local socket in
449 TIME_WAIT state, without waiting for its natural timeout to
Serhiy Storchaka4adf01c2016-10-19 18:30:05 +0300450 expire. If not specified will automatically be set to ``True`` on
Victor Stinner33f6abe2014-10-12 20:36:04 +0200451 UNIX.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100452
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700453 * *reuse_port* tells the kernel to allow this endpoint to be bound to the
454 same port as other existing endpoints are bound to, so long as they all
455 set this flag when being created. This option is not supported on
456 Windows.
457
Victor Stinnerd1432092014-06-19 17:11:49 +0200458 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100459
Victor Stinner60208a12015-09-15 22:41:52 +0200460 .. versionchanged:: 3.5
461
462 On Windows with :class:`ProactorEventLoop`, SSL/TLS is now supported.
Victor Stinner41f3c3f2014-08-31 14:47:37 +0200463
Victor Stinnerc8ea8132014-01-23 11:02:09 +0100464 .. seealso::
465
466 The function :func:`start_server` creates a (:class:`StreamReader`,
467 :class:`StreamWriter`) pair and calls back a function with this pair.
468
Victor Stinner7b58a2b2015-09-21 18:41:05 +0200469 .. versionchanged:: 3.5.1
Victor Stinner5e4a7d82015-09-21 18:33:43 +0200470
471 The *host* parameter can now be a sequence of strings.
472
Victor Stinnerea3183f2013-12-03 01:08:00 +0100473
Guido van Rossumf68afd82016-08-08 09:41:21 -0700474.. coroutinemethod:: AbstractEventLoop.create_unix_server(protocol_factory, path=None, \*, sock=None, backlog=100, ssl=None)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100475
Guido van Rossumf68afd82016-08-08 09:41:21 -0700476 Similar to :meth:`AbstractEventLoop.create_server`, but specific to the
Victor Stinnera6919aa2014-02-19 13:32:34 +0100477 socket family :py:data:`~socket.AF_UNIX`.
478
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100479 This method is a :ref:`coroutine <coroutine>`.
480
Victor Stinnera6919aa2014-02-19 13:32:34 +0100481 Availability: UNIX.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100482
Yury Selivanov3b3a1412016-11-07 15:35:25 -0500483.. coroutinemethod:: BaseEventLoop.connect_accepted_socket(protocol_factory, sock, \*, ssl=None)
484
485 Handle an accepted connection.
486
487 This is used by servers that accept connections outside of
488 asyncio but that use asyncio to handle them.
489
490 Parameters:
491
492 * *sock* is a preexisting socket object returned from an ``accept``
493 call.
494
495 * *ssl* can be set to an :class:`~ssl.SSLContext` to enable SSL over the
496 accepted connections.
497
498 This method is a :ref:`coroutine <coroutine>`. When completed, the
499 coroutine returns a ``(transport, protocol)`` pair.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100500
Victor Stinnerc1567df2014-02-08 23:22:58 +0100501Watch file descriptors
502----------------------
503
Victor Stinner41f3c3f2014-08-31 14:47:37 +0200504On Windows with :class:`SelectorEventLoop`, only socket handles are supported
505(ex: pipe file descriptors are not supported).
506
507On Windows with :class:`ProactorEventLoop`, these methods are not supported.
508
Guido van Rossumf68afd82016-08-08 09:41:21 -0700509.. method:: AbstractEventLoop.add_reader(fd, callback, \*args)
Victor Stinnerc1567df2014-02-08 23:22:58 +0100510
511 Start watching the file descriptor for read availability and then call the
512 *callback* with specified arguments.
513
Victor Stinner8464c242014-11-28 13:15:41 +0100514 :ref:`Use functools.partial to pass keywords to the callback
515 <asyncio-pass-keywords>`.
516
Guido van Rossumf68afd82016-08-08 09:41:21 -0700517.. method:: AbstractEventLoop.remove_reader(fd)
Victor Stinnerc1567df2014-02-08 23:22:58 +0100518
519 Stop watching the file descriptor for read availability.
520
Guido van Rossumf68afd82016-08-08 09:41:21 -0700521.. method:: AbstractEventLoop.add_writer(fd, callback, \*args)
Victor Stinnerc1567df2014-02-08 23:22:58 +0100522
523 Start watching the file descriptor for write availability and then call the
524 *callback* with specified arguments.
525
Victor Stinner8464c242014-11-28 13:15:41 +0100526 :ref:`Use functools.partial to pass keywords to the callback
527 <asyncio-pass-keywords>`.
528
Guido van Rossumf68afd82016-08-08 09:41:21 -0700529.. method:: AbstractEventLoop.remove_writer(fd)
Victor Stinnerc1567df2014-02-08 23:22:58 +0100530
531 Stop watching the file descriptor for write availability.
532
Victor Stinner04e6df32014-10-11 16:16:27 +0200533The :ref:`watch a file descriptor for read events <asyncio-watch-read-event>`
Guido van Rossumf68afd82016-08-08 09:41:21 -0700534example uses the low-level :meth:`AbstractEventLoop.add_reader` method to register
Victor Stinner04e6df32014-10-11 16:16:27 +0200535the file descriptor of a socket.
536
Victor Stinnerc1567df2014-02-08 23:22:58 +0100537
538Low-level socket operations
539---------------------------
540
Guido van Rossumf68afd82016-08-08 09:41:21 -0700541.. coroutinemethod:: AbstractEventLoop.sock_recv(sock, nbytes)
Victor Stinnerc1567df2014-02-08 23:22:58 +0100542
Yury Selivanov55c50842016-06-08 12:48:15 -0400543 Receive data from the socket. Modeled after blocking
544 :meth:`socket.socket.recv` method.
545
546 The return value is a bytes object
Victor Stinnerc1567df2014-02-08 23:22:58 +0100547 representing the data received. The maximum amount of data to be received
548 at once is specified by *nbytes*.
549
Victor Stinnerd84fd732014-08-26 01:01:59 +0200550 With :class:`SelectorEventLoop` event loop, the socket *sock* must be
551 non-blocking.
Victor Stinnerec2ce092014-07-29 23:12:22 +0200552
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500553 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100554
Guido van Rossumf68afd82016-08-08 09:41:21 -0700555.. coroutinemethod:: AbstractEventLoop.sock_sendall(sock, data)
Victor Stinnerc1567df2014-02-08 23:22:58 +0100556
Yury Selivanov55c50842016-06-08 12:48:15 -0400557 Send data to the socket. Modeled after blocking
558 :meth:`socket.socket.sendall` method.
559
560 The socket must be connected to a remote socket.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100561 This method continues to send data from *data* until either all data has
562 been sent or an error occurs. ``None`` is returned on success. On error,
563 an exception is raised, and there is no way to determine how much data, if
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500564 any, was successfully processed by the receiving end of the connection.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100565
Victor Stinnerd84fd732014-08-26 01:01:59 +0200566 With :class:`SelectorEventLoop` event loop, the socket *sock* must be
567 non-blocking.
Victor Stinnerec2ce092014-07-29 23:12:22 +0200568
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500569 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100570
Guido van Rossumf68afd82016-08-08 09:41:21 -0700571.. coroutinemethod:: AbstractEventLoop.sock_connect(sock, address)
Victor Stinnerc1567df2014-02-08 23:22:58 +0100572
Yury Selivanov55c50842016-06-08 12:48:15 -0400573 Connect to a remote socket at *address*. Modeled after
574 blocking :meth:`socket.socket.connect` method.
Victor Stinner1b0580b2014-02-13 09:24:37 +0100575
Victor Stinnerd84fd732014-08-26 01:01:59 +0200576 With :class:`SelectorEventLoop` event loop, the socket *sock* must be
577 non-blocking.
Victor Stinnerec2ce092014-07-29 23:12:22 +0200578
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500579 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100580
Yury Selivanov55c50842016-06-08 12:48:15 -0400581 .. versionchanged:: 3.5.2
582 ``address`` no longer needs to be resolved. ``sock_connect``
583 will try to check if the *address* is already resolved by calling
584 :func:`socket.inet_pton`. If not,
Guido van Rossumf68afd82016-08-08 09:41:21 -0700585 :meth:`AbstractEventLoop.getaddrinfo` will be used to resolve the
Yury Selivanov55c50842016-06-08 12:48:15 -0400586 *address*.
587
Victor Stinnerc1567df2014-02-08 23:22:58 +0100588 .. seealso::
589
Guido van Rossumf68afd82016-08-08 09:41:21 -0700590 :meth:`AbstractEventLoop.create_connection`
Yury Selivanov55c50842016-06-08 12:48:15 -0400591 and :func:`asyncio.open_connection() <open_connection>`.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100592
593
Guido van Rossumf68afd82016-08-08 09:41:21 -0700594.. coroutinemethod:: AbstractEventLoop.sock_accept(sock)
Victor Stinnerc1567df2014-02-08 23:22:58 +0100595
Yury Selivanov55c50842016-06-08 12:48:15 -0400596 Accept a connection. Modeled after blocking
597 :meth:`socket.socket.accept`.
598
599 The socket must be bound to an address and listening
Victor Stinnerc1567df2014-02-08 23:22:58 +0100600 for connections. The return value is a pair ``(conn, address)`` where *conn*
601 is a *new* socket object usable to send and receive data on the connection,
602 and *address* is the address bound to the socket on the other end of the
603 connection.
604
Victor Stinnerec2ce092014-07-29 23:12:22 +0200605 The socket *sock* must be non-blocking.
606
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500607 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100608
609 .. seealso::
610
Guido van Rossumf68afd82016-08-08 09:41:21 -0700611 :meth:`AbstractEventLoop.create_server` and :func:`start_server`.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100612
613
614Resolve host name
615-----------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100616
Guido van Rossumf68afd82016-08-08 09:41:21 -0700617.. coroutinemethod:: AbstractEventLoop.getaddrinfo(host, port, \*, family=0, type=0, proto=0, flags=0)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100618
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500619 This method is a :ref:`coroutine <coroutine>`, similar to
620 :meth:`socket.getaddrinfo` function but non-blocking.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100621
Guido van Rossumf68afd82016-08-08 09:41:21 -0700622.. coroutinemethod:: AbstractEventLoop.getnameinfo(sockaddr, flags=0)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100623
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500624 This method is a :ref:`coroutine <coroutine>`, similar to
625 :meth:`socket.getnameinfo` function but non-blocking.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100626
627
Victor Stinner984600f2014-03-25 09:40:26 +0100628Connect pipes
629-------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100630
Victor Stinner41f3c3f2014-08-31 14:47:37 +0200631On Windows with :class:`SelectorEventLoop`, these methods are not supported.
632Use :class:`ProactorEventLoop` to support pipes on Windows.
633
Guido van Rossumf68afd82016-08-08 09:41:21 -0700634.. coroutinemethod:: AbstractEventLoop.connect_read_pipe(protocol_factory, pipe)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100635
Victor Stinnerd84fd732014-08-26 01:01:59 +0200636 Register read pipe in eventloop.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100637
638 *protocol_factory* should instantiate object with :class:`Protocol`
Victor Stinnera5b257a2014-05-29 00:14:03 +0200639 interface. *pipe* is a :term:`file-like object <file object>`.
640 Return pair ``(transport, protocol)``, where *transport* supports the
Victor Stinnerea3183f2013-12-03 01:08:00 +0100641 :class:`ReadTransport` interface.
642
Victor Stinnerd84fd732014-08-26 01:01:59 +0200643 With :class:`SelectorEventLoop` event loop, the *pipe* is set to
644 non-blocking mode.
645
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500646 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100647
Guido van Rossumf68afd82016-08-08 09:41:21 -0700648.. coroutinemethod:: AbstractEventLoop.connect_write_pipe(protocol_factory, pipe)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100649
650 Register write pipe in eventloop.
651
652 *protocol_factory* should instantiate object with :class:`BaseProtocol`
Victor Stinner2cef3002014-10-23 22:38:46 +0200653 interface. *pipe* is :term:`file-like object <file object>`.
654 Return pair ``(transport, protocol)``, where *transport* supports
Victor Stinnerea3183f2013-12-03 01:08:00 +0100655 :class:`WriteTransport` interface.
656
Victor Stinnerd84fd732014-08-26 01:01:59 +0200657 With :class:`SelectorEventLoop` event loop, the *pipe* is set to
658 non-blocking mode.
659
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500660 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100661
Victor Stinner08444382014-02-02 22:43:39 +0100662.. seealso::
663
Guido van Rossumf68afd82016-08-08 09:41:21 -0700664 The :meth:`AbstractEventLoop.subprocess_exec` and
665 :meth:`AbstractEventLoop.subprocess_shell` methods.
Victor Stinner08444382014-02-02 22:43:39 +0100666
Victor Stinnerea3183f2013-12-03 01:08:00 +0100667
Victor Stinner8b863482014-01-27 10:07:50 +0100668UNIX signals
669------------
670
671Availability: UNIX only.
672
Guido van Rossumf68afd82016-08-08 09:41:21 -0700673.. method:: AbstractEventLoop.add_signal_handler(signum, callback, \*args)
Victor Stinner8b863482014-01-27 10:07:50 +0100674
675 Add a handler for a signal.
676
677 Raise :exc:`ValueError` if the signal number is invalid or uncatchable.
678 Raise :exc:`RuntimeError` if there is a problem setting up the handler.
679
Victor Stinner8464c242014-11-28 13:15:41 +0100680 :ref:`Use functools.partial to pass keywords to the callback
681 <asyncio-pass-keywords>`.
682
Guido van Rossumf68afd82016-08-08 09:41:21 -0700683.. method:: AbstractEventLoop.remove_signal_handler(sig)
Victor Stinner8b863482014-01-27 10:07:50 +0100684
685 Remove a handler for a signal.
686
687 Return ``True`` if a signal handler was removed, ``False`` if not.
688
689.. seealso::
690
691 The :mod:`signal` module.
692
693
Victor Stinnerea3183f2013-12-03 01:08:00 +0100694Executor
695--------
696
697Call a function in an :class:`~concurrent.futures.Executor` (pool of threads or
698pool of processes). By default, an event loop uses a thread pool executor
699(:class:`~concurrent.futures.ThreadPoolExecutor`).
700
Guido van Rossumf68afd82016-08-08 09:41:21 -0700701.. coroutinemethod:: AbstractEventLoop.run_in_executor(executor, func, \*args)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100702
Andrew Svetlov1c62b522015-10-01 09:48:08 +0300703 Arrange for a *func* to be called in the specified executor.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100704
Larry Hastings3732ed22014-03-15 21:13:56 -0700705 The *executor* argument should be an :class:`~concurrent.futures.Executor`
706 instance. The default executor is used if *executor* is ``None``.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100707
Andrew Svetlov1c62b522015-10-01 09:48:08 +0300708 :ref:`Use functools.partial to pass keywords to the *func*
Victor Stinner8464c242014-11-28 13:15:41 +0100709 <asyncio-pass-keywords>`.
710
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500711 This method is a :ref:`coroutine <coroutine>`.
712
Yury Selivanove8a60452016-10-21 17:40:42 -0400713 .. versionchanged:: 3.5.3
714 :meth:`BaseEventLoop.run_in_executor` no longer configures the
715 ``max_workers`` of the thread pool executor it creates, instead
716 leaving it up to the thread pool executor
717 (:class:`~concurrent.futures.ThreadPoolExecutor`) to set the
718 default.
719
Guido van Rossumf68afd82016-08-08 09:41:21 -0700720.. method:: AbstractEventLoop.set_default_executor(executor)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100721
722 Set the default executor used by :meth:`run_in_executor`.
723
724
Yury Selivanov43ee1c12014-02-19 20:58:44 -0500725Error Handling API
726------------------
727
Martin Panterc04fb562016-02-10 05:44:01 +0000728Allows customizing how exceptions are handled in the event loop.
Yury Selivanov43ee1c12014-02-19 20:58:44 -0500729
Guido van Rossumf68afd82016-08-08 09:41:21 -0700730.. method:: AbstractEventLoop.set_exception_handler(handler)
Yury Selivanov43ee1c12014-02-19 20:58:44 -0500731
732 Set *handler* as the new event loop exception handler.
733
734 If *handler* is ``None``, the default exception handler will
735 be set.
736
737 If *handler* is a callable object, it should have a
738 matching signature to ``(loop, context)``, where ``loop``
739 will be a reference to the active event loop, ``context``
740 will be a ``dict`` object (see :meth:`call_exception_handler`
741 documentation for details about context).
742
Guido van Rossumf68afd82016-08-08 09:41:21 -0700743.. method:: AbstractEventLoop.get_exception_handler()
Yury Selivanov950204d2016-05-16 16:23:00 -0400744
745 Return the exception handler, or ``None`` if the default one
746 is in use.
747
748 .. versionadded:: 3.5.2
749
Guido van Rossumf68afd82016-08-08 09:41:21 -0700750.. method:: AbstractEventLoop.default_exception_handler(context)
Yury Selivanov43ee1c12014-02-19 20:58:44 -0500751
752 Default exception handler.
753
754 This is called when an exception occurs and no exception
755 handler is set, and can be called by a custom exception
756 handler that wants to defer to the default behavior.
757
758 *context* parameter has the same meaning as in
759 :meth:`call_exception_handler`.
760
Guido van Rossumf68afd82016-08-08 09:41:21 -0700761.. method:: AbstractEventLoop.call_exception_handler(context)
Yury Selivanov43ee1c12014-02-19 20:58:44 -0500762
763 Call the current event loop exception handler.
764
765 *context* is a ``dict`` object containing the following keys
766 (new keys may be introduced later):
767
768 * 'message': Error message;
769 * 'exception' (optional): Exception object;
770 * 'future' (optional): :class:`asyncio.Future` instance;
771 * 'handle' (optional): :class:`asyncio.Handle` instance;
772 * 'protocol' (optional): :ref:`Protocol <asyncio-protocol>` instance;
773 * 'transport' (optional): :ref:`Transport <asyncio-transport>` instance;
774 * 'socket' (optional): :class:`socket.socket` instance.
775
776 .. note::
777
778 Note: this method should not be overloaded in subclassed
779 event loops. For any custom exception handling, use
780 :meth:`set_exception_handler()` method.
781
Victor Stinner0f3e6bc2014-02-19 23:15:02 +0100782Debug mode
783----------
784
Guido van Rossumf68afd82016-08-08 09:41:21 -0700785.. method:: AbstractEventLoop.get_debug()
Victor Stinner0f3e6bc2014-02-19 23:15:02 +0100786
Victor Stinner7b7120e2014-06-23 00:12:14 +0200787 Get the debug mode (:class:`bool`) of the event loop.
788
789 The default value is ``True`` if the environment variable
790 :envvar:`PYTHONASYNCIODEBUG` is set to a non-empty string, ``False``
791 otherwise.
Victor Stinner0f3e6bc2014-02-19 23:15:02 +0100792
Victor Stinner64d750b2014-06-18 03:25:23 +0200793 .. versionadded:: 3.4.2
794
Guido van Rossumf68afd82016-08-08 09:41:21 -0700795.. method:: AbstractEventLoop.set_debug(enabled: bool)
Victor Stinner0f3e6bc2014-02-19 23:15:02 +0100796
797 Set the debug mode of the event loop.
798
Victor Stinner64d750b2014-06-18 03:25:23 +0200799 .. versionadded:: 3.4.2
800
Victor Stinner0f3e6bc2014-02-19 23:15:02 +0100801.. seealso::
802
Victor Stinner62511fd2014-06-23 00:36:11 +0200803 The :ref:`debug mode of asyncio <asyncio-debug-mode>`.
Victor Stinner0f3e6bc2014-02-19 23:15:02 +0100804
Victor Stinner8c462c52014-01-24 18:11:43 +0100805Server
806------
807
Victor Stinner8ebeb032014-07-11 23:47:40 +0200808.. class:: Server
Victor Stinner8c462c52014-01-24 18:11:43 +0100809
Victor Stinner8ebeb032014-07-11 23:47:40 +0200810 Server listening on sockets.
811
Guido van Rossumf68afd82016-08-08 09:41:21 -0700812 Object created by the :meth:`AbstractEventLoop.create_server` method and the
R David Murray756f0b12015-01-29 19:53:33 -0500813 :func:`start_server` function. Don't instantiate the class directly.
Victor Stinner8c462c52014-01-24 18:11:43 +0100814
815 .. method:: close()
816
Victor Stinner4bfb14a2014-07-12 03:20:24 +0200817 Stop serving: close listening sockets and set the :attr:`sockets`
818 attribute to ``None``.
819
Berker Peksag49c9edf2016-01-20 07:14:22 +0200820 The sockets that represent existing incoming client connections are left
821 open.
Victor Stinner8ebeb032014-07-11 23:47:40 +0200822
Berker Peksag49c9edf2016-01-20 07:14:22 +0200823 The server is closed asynchronously, use the :meth:`wait_closed`
824 coroutine to wait until the server is closed.
Victor Stinner8c462c52014-01-24 18:11:43 +0100825
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100826 .. coroutinemethod:: wait_closed()
Victor Stinner8c462c52014-01-24 18:11:43 +0100827
Victor Stinner8ebeb032014-07-11 23:47:40 +0200828 Wait until the :meth:`close` method completes.
829
830 This method is a :ref:`coroutine <coroutine>`.
831
832 .. attribute:: sockets
833
834 List of :class:`socket.socket` objects the server is listening to, or
835 ``None`` if the server is closed.
Victor Stinner8c462c52014-01-24 18:11:43 +0100836
837
Yury Selivanov43ee1c12014-02-19 20:58:44 -0500838Handle
839------
840
841.. class:: Handle
842
Guido van Rossumf68afd82016-08-08 09:41:21 -0700843 A callback wrapper object returned by :func:`AbstractEventLoop.call_soon`,
844 :func:`AbstractEventLoop.call_soon_threadsafe`, :func:`AbstractEventLoop.call_later`,
845 and :func:`AbstractEventLoop.call_at`.
Yury Selivanov43ee1c12014-02-19 20:58:44 -0500846
847 .. method:: cancel()
848
Yury Selivanov1096f762015-06-25 13:49:52 -0400849 Cancel the call. If the callback is already canceled or executed,
850 this method has no effect.
Victor Stinneraea82292014-07-08 23:42:38 +0200851
Yury Selivanov43ee1c12014-02-19 20:58:44 -0500852
Victor Stinner6888b962014-10-11 16:15:58 +0200853Event loop examples
Victor Stinnera092a612015-01-09 15:58:41 +0100854-------------------
Yury Selivanov43ee1c12014-02-19 20:58:44 -0500855
Victor Stinner3e09e322013-12-03 01:22:06 +0100856.. _asyncio-hello-world-callback:
Victor Stinnerea3183f2013-12-03 01:08:00 +0100857
Victor Stinner7f314ed2014-10-15 18:49:16 +0200858Hello World with call_soon()
Victor Stinnera092a612015-01-09 15:58:41 +0100859^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Victor Stinnerea3183f2013-12-03 01:08:00 +0100860
Guido van Rossumf68afd82016-08-08 09:41:21 -0700861Example using the :meth:`AbstractEventLoop.call_soon` method to schedule a
Victor Stinner7f314ed2014-10-15 18:49:16 +0200862callback. The callback displays ``"Hello World"`` and then stops the event
863loop::
Victor Stinnerea3183f2013-12-03 01:08:00 +0100864
865 import asyncio
866
Victor Stinner7f314ed2014-10-15 18:49:16 +0200867 def hello_world(loop):
Victor Stinnerea3183f2013-12-03 01:08:00 +0100868 print('Hello World')
Victor Stinner7f314ed2014-10-15 18:49:16 +0200869 loop.stop()
Victor Stinnerea3183f2013-12-03 01:08:00 +0100870
871 loop = asyncio.get_event_loop()
Victor Stinner7f314ed2014-10-15 18:49:16 +0200872
873 # Schedule a call to hello_world()
874 loop.call_soon(hello_world, loop)
875
876 # Blocking call interrupted by loop.stop()
877 loop.run_forever()
878 loop.close()
Victor Stinnerea3183f2013-12-03 01:08:00 +0100879
Victor Stinner3e09e322013-12-03 01:22:06 +0100880.. seealso::
Victor Stinnerea3183f2013-12-03 01:08:00 +0100881
Victor Stinner6888b962014-10-11 16:15:58 +0200882 The :ref:`Hello World coroutine <asyncio-hello-world-coroutine>` example
883 uses a :ref:`coroutine <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100884
Victor Stinner8b863482014-01-27 10:07:50 +0100885
Victor Stinner7f314ed2014-10-15 18:49:16 +0200886.. _asyncio-date-callback:
887
888Display the current date with call_later()
Victor Stinnera092a612015-01-09 15:58:41 +0100889^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Victor Stinner7f314ed2014-10-15 18:49:16 +0200890
891Example of callback displaying the current date every second. The callback uses
Guido van Rossumf68afd82016-08-08 09:41:21 -0700892the :meth:`AbstractEventLoop.call_later` method to reschedule itself during 5
Victor Stinner7f314ed2014-10-15 18:49:16 +0200893seconds, and then stops the event loop::
894
895 import asyncio
896 import datetime
897
898 def display_date(end_time, loop):
899 print(datetime.datetime.now())
900 if (loop.time() + 1.0) < end_time:
901 loop.call_later(1, display_date, end_time, loop)
902 else:
903 loop.stop()
904
905 loop = asyncio.get_event_loop()
906
907 # Schedule the first call to display_date()
908 end_time = loop.time() + 5.0
909 loop.call_soon(display_date, end_time, loop)
910
911 # Blocking call interrupted by loop.stop()
912 loop.run_forever()
913 loop.close()
914
915.. seealso::
916
917 The :ref:`coroutine displaying the current date
918 <asyncio-date-coroutine>` example uses a :ref:`coroutine
919 <coroutine>`.
920
921
Victor Stinner04e6df32014-10-11 16:16:27 +0200922.. _asyncio-watch-read-event:
Victor Stinner8b863482014-01-27 10:07:50 +0100923
Victor Stinner04e6df32014-10-11 16:16:27 +0200924Watch a file descriptor for read events
Victor Stinnera092a612015-01-09 15:58:41 +0100925^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Victor Stinner04e6df32014-10-11 16:16:27 +0200926
927Wait until a file descriptor received some data using the
Guido van Rossumf68afd82016-08-08 09:41:21 -0700928:meth:`AbstractEventLoop.add_reader` method and then close the event loop::
Victor Stinner04e6df32014-10-11 16:16:27 +0200929
930 import asyncio
Victor Stinnerccd8e342014-10-11 16:30:02 +0200931 try:
932 from socket import socketpair
933 except ImportError:
934 from asyncio.windows_utils import socketpair
Victor Stinner04e6df32014-10-11 16:16:27 +0200935
936 # Create a pair of connected file descriptors
Victor Stinnerccd8e342014-10-11 16:30:02 +0200937 rsock, wsock = socketpair()
Victor Stinner04e6df32014-10-11 16:16:27 +0200938 loop = asyncio.get_event_loop()
939
940 def reader():
941 data = rsock.recv(100)
942 print("Received:", data.decode())
Victor Stinner2cef3002014-10-23 22:38:46 +0200943 # We are done: unregister the file descriptor
Victor Stinner04e6df32014-10-11 16:16:27 +0200944 loop.remove_reader(rsock)
945 # Stop the event loop
946 loop.stop()
947
Victor Stinner2cef3002014-10-23 22:38:46 +0200948 # Register the file descriptor for read event
Victor Stinner04e6df32014-10-11 16:16:27 +0200949 loop.add_reader(rsock, reader)
950
951 # Simulate the reception of data from the network
952 loop.call_soon(wsock.send, 'abc'.encode())
953
954 # Run the event loop
955 loop.run_forever()
956
957 # We are done, close sockets and the event loop
958 rsock.close()
959 wsock.close()
960 loop.close()
961
962.. seealso::
963
964 The :ref:`register an open socket to wait for data using a protocol
965 <asyncio-register-socket>` example uses a low-level protocol created by the
Guido van Rossumf68afd82016-08-08 09:41:21 -0700966 :meth:`AbstractEventLoop.create_connection` method.
Victor Stinner04e6df32014-10-11 16:16:27 +0200967
968 The :ref:`register an open socket to wait for data using streams
969 <asyncio-register-socket-streams>` example uses high-level streams
970 created by the :func:`open_connection` function in a coroutine.
971
972
973Set signal handlers for SIGINT and SIGTERM
Victor Stinnera092a612015-01-09 15:58:41 +0100974^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Victor Stinner04e6df32014-10-11 16:16:27 +0200975
976Register handlers for signals :py:data:`SIGINT` and :py:data:`SIGTERM` using
Guido van Rossumf68afd82016-08-08 09:41:21 -0700977the :meth:`AbstractEventLoop.add_signal_handler` method::
Victor Stinner8b863482014-01-27 10:07:50 +0100978
979 import asyncio
980 import functools
981 import os
982 import signal
983
984 def ask_exit(signame):
985 print("got signal %s: exit" % signame)
986 loop.stop()
987
988 loop = asyncio.get_event_loop()
989 for signame in ('SIGINT', 'SIGTERM'):
990 loop.add_signal_handler(getattr(signal, signame),
991 functools.partial(ask_exit, signame))
992
Serhiy Storchaka0424eaf2015-09-12 17:45:25 +0300993 print("Event loop running forever, press Ctrl+C to interrupt.")
Victor Stinner8b863482014-01-27 10:07:50 +0100994 print("pid %s: send SIGINT or SIGTERM to exit." % os.getpid())
Victor Stinner63b21a82014-07-05 15:38:59 +0200995 try:
996 loop.run_forever()
997 finally:
998 loop.close()
Victor Stinner2cef3002014-10-23 22:38:46 +0200999
1000This example only works on UNIX.