blob: eed4f08d9f16e713da2dba925e29f5823808c30c [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
Victor Stinner8464c242014-11-28 13:15:41 +010091.. _asyncio-pass-keywords:
Victor Stinnerea3183f2013-12-03 01:08:00 +010092
93Calls
94-----
95
Victor Stinner8464c242014-11-28 13:15:41 +010096Most :mod:`asyncio` functions don't accept keywords. If you want to pass
97keywords to your callback, use :func:`functools.partial`. For example,
98``loop.call_soon(functools.partial(print, "Hello", flush=True))`` will call
99``print("Hello", flush=True)``.
100
101.. note::
102 :func:`functools.partial` is better than ``lambda`` functions, because
103 :mod:`asyncio` can inspect :func:`functools.partial` object to display
104 parameters in debug mode, whereas ``lambda`` functions have a poor
105 representation.
106
Guido van Rossumf68afd82016-08-08 09:41:21 -0700107.. method:: AbstractEventLoop.call_soon(callback, \*args)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100108
Victor Stinner4d5115c2014-12-15 17:50:55 +0100109 Arrange for a callback to be called as soon as possible. The callback is
110 called after :meth:`call_soon` returns, when control returns to the event
111 loop.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100112
113 This operates as a FIFO queue, callbacks are called in the order in
114 which they are registered. Each callback will be called exactly once.
115
116 Any positional arguments after the callback will be passed to the
117 callback when it is called.
118
Yury Selivanov1096f762015-06-25 13:49:52 -0400119 An instance of :class:`asyncio.Handle` is returned, which can be
120 used to cancel the callback.
Yury Selivanov43ee1c12014-02-19 20:58:44 -0500121
Victor Stinner8464c242014-11-28 13:15:41 +0100122 :ref:`Use functools.partial to pass keywords to the callback
123 <asyncio-pass-keywords>`.
124
Guido van Rossumf68afd82016-08-08 09:41:21 -0700125.. method:: AbstractEventLoop.call_soon_threadsafe(callback, \*args)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100126
127 Like :meth:`call_soon`, but thread safe.
128
Victor Stinner83704962015-02-25 14:24:15 +0100129 See the :ref:`concurrency and multithreading <asyncio-multithreading>`
130 section of the documentation.
131
Victor Stinnerea3183f2013-12-03 01:08:00 +0100132
Victor Stinner45b27ed2014-02-01 02:36:43 +0100133.. _asyncio-delayed-calls:
134
Victor Stinnerea3183f2013-12-03 01:08:00 +0100135Delayed calls
136-------------
137
138The event loop has its own internal clock for computing timeouts.
139Which clock is used depends on the (platform-specific) event loop
140implementation; ideally it is a monotonic clock. This will generally be
141a different clock than :func:`time.time`.
142
Victor Stinnerfd9d3742014-02-18 09:37:43 +0100143.. note::
144
145 Timeouts (relative *delay* or absolute *when*) should not exceed one day.
146
Victor Stinner45b27ed2014-02-01 02:36:43 +0100147
Guido van Rossumf68afd82016-08-08 09:41:21 -0700148.. method:: AbstractEventLoop.call_later(delay, callback, *args)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100149
150 Arrange for the *callback* to be called after the given *delay*
151 seconds (either an int or float).
152
Yury Selivanov1096f762015-06-25 13:49:52 -0400153 An instance of :class:`asyncio.Handle` is returned, which can be
154 used to cancel the callback.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100155
156 *callback* will be called exactly once per call to :meth:`call_later`.
157 If two callbacks are scheduled for exactly the same time, it is
158 undefined which will be called first.
159
160 The optional positional *args* will be passed to the callback when it
161 is called. If you want the callback to be called with some named
162 arguments, use a closure or :func:`functools.partial`.
163
Victor Stinner8464c242014-11-28 13:15:41 +0100164 :ref:`Use functools.partial to pass keywords to the callback
165 <asyncio-pass-keywords>`.
166
Guido van Rossumf68afd82016-08-08 09:41:21 -0700167.. method:: AbstractEventLoop.call_at(when, callback, *args)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100168
169 Arrange for the *callback* to be called at the given absolute timestamp
Berker Peksagb5563992014-11-07 19:51:07 +0200170 *when* (an int or float), using the same time reference as
Guido van Rossumf68afd82016-08-08 09:41:21 -0700171 :meth:`AbstractEventLoop.time`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100172
173 This method's behavior is the same as :meth:`call_later`.
174
Yury Selivanov1096f762015-06-25 13:49:52 -0400175 An instance of :class:`asyncio.Handle` is returned, which can be
176 used to cancel the callback.
177
Victor Stinner8464c242014-11-28 13:15:41 +0100178 :ref:`Use functools.partial to pass keywords to the callback
179 <asyncio-pass-keywords>`.
180
Guido van Rossumf68afd82016-08-08 09:41:21 -0700181.. method:: AbstractEventLoop.time()
Victor Stinnerea3183f2013-12-03 01:08:00 +0100182
183 Return the current time, as a :class:`float` value, according to the
184 event loop's internal clock.
185
Victor Stinner3e09e322013-12-03 01:22:06 +0100186.. seealso::
187
188 The :func:`asyncio.sleep` function.
189
Victor Stinnerea3183f2013-12-03 01:08:00 +0100190
Yury Selivanov950204d2016-05-16 16:23:00 -0400191Futures
192-------
193
Guido van Rossumf68afd82016-08-08 09:41:21 -0700194.. method:: AbstractEventLoop.create_future()
Yury Selivanov950204d2016-05-16 16:23:00 -0400195
196 Create an :class:`asyncio.Future` object attached to the loop.
197
198 This is a preferred way to create futures in asyncio, as event
199 loop implementations can provide alternative implementations
200 of the Future class (with better performance or instrumentation).
201
202 .. versionadded:: 3.5.2
203
204
Yury Selivanovbb961342015-06-25 11:54:34 -0400205Tasks
206-----
Victor Stinner530ef2f2014-07-08 12:39:10 +0200207
Guido van Rossumf68afd82016-08-08 09:41:21 -0700208.. method:: AbstractEventLoop.create_task(coro)
Victor Stinner530ef2f2014-07-08 12:39:10 +0200209
210 Schedule the execution of a :ref:`coroutine object <coroutine>`: wrap it in
211 a future. Return a :class:`Task` object.
212
213 Third-party event loops can use their own subclass of :class:`Task` for
214 interoperability. In this case, the result type is a subclass of
215 :class:`Task`.
216
Victor Stinner337e03f2014-08-11 01:11:13 +0200217 This method was added in Python 3.4.2. Use the :func:`async` function to
218 support also older Python versions.
Victor Stinner530ef2f2014-07-08 12:39:10 +0200219
220 .. versionadded:: 3.4.2
221
Guido van Rossumf68afd82016-08-08 09:41:21 -0700222.. method:: AbstractEventLoop.set_task_factory(factory)
Yury Selivanov71854612015-05-11 16:28:27 -0400223
224 Set a task factory that will be used by
Guido van Rossumf68afd82016-08-08 09:41:21 -0700225 :meth:`AbstractEventLoop.create_task`.
Yury Selivanov71854612015-05-11 16:28:27 -0400226
227 If *factory* is ``None`` the default task factory will be set.
228
229 If *factory* is a *callable*, it should have a signature matching
230 ``(loop, coro)``, where *loop* will be a reference to the active
231 event loop, *coro* will be a coroutine object. The callable
232 must return an :class:`asyncio.Future` compatible object.
233
234 .. versionadded:: 3.4.4
235
Guido van Rossumf68afd82016-08-08 09:41:21 -0700236.. method:: AbstractEventLoop.get_task_factory()
Yury Selivanov71854612015-05-11 16:28:27 -0400237
238 Return a task factory, or ``None`` if the default one is in use.
239
240 .. versionadded:: 3.4.4
241
Victor Stinner530ef2f2014-07-08 12:39:10 +0200242
Victor Stinnerea3183f2013-12-03 01:08:00 +0100243Creating connections
Victor Stinner0c6f1ca2013-12-03 01:46:39 +0100244--------------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100245
Guido van Rossumf68afd82016-08-08 09:41:21 -0700246.. 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 +0100247
248 Create a streaming transport connection to a given Internet *host* and
Victor Stinnera6919aa2014-02-19 13:32:34 +0100249 *port*: socket family :py:data:`~socket.AF_INET` or
250 :py:data:`~socket.AF_INET6` depending on *host* (or *family* if specified),
251 socket type :py:data:`~socket.SOCK_STREAM`. *protocol_factory* must be a
252 callable returning a :ref:`protocol <asyncio-protocol>` instance.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100253
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500254 This method is a :ref:`coroutine <coroutine>` which will try to
Victor Stinnerea3183f2013-12-03 01:08:00 +0100255 establish the connection in the background. When successful, the
256 coroutine returns a ``(transport, protocol)`` pair.
257
258 The chronological synopsis of the underlying operation is as follows:
259
Victor Stinner9592edb2014-02-02 15:03:02 +0100260 #. The connection is established, and a :ref:`transport <asyncio-transport>`
Victor Stinnerea3183f2013-12-03 01:08:00 +0100261 is created to represent it.
262
263 #. *protocol_factory* is called without arguments and must return a
Victor Stinner9592edb2014-02-02 15:03:02 +0100264 :ref:`protocol <asyncio-protocol>` instance.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100265
266 #. The protocol instance is tied to the transport, and its
267 :meth:`connection_made` method is called.
268
269 #. The coroutine returns successfully with the ``(transport, protocol)``
270 pair.
271
272 The created transport is an implementation-dependent bidirectional stream.
273
274 .. note::
275 *protocol_factory* can be any kind of callable, not necessarily
276 a class. For example, if you want to use a pre-created
277 protocol instance, you can pass ``lambda: my_protocol``.
278
Martin Panterc04fb562016-02-10 05:44:01 +0000279 Options that change how the connection is created:
Victor Stinnerea3183f2013-12-03 01:08:00 +0100280
281 * *ssl*: if given and not false, a SSL/TLS transport is created
282 (by default a plain TCP transport is created). If *ssl* is
283 a :class:`ssl.SSLContext` object, this context is used to create
284 the transport; if *ssl* is :const:`True`, a context with some
285 unspecified default settings is used.
286
Berker Peksag9c1dba22014-09-28 00:00:58 +0300287 .. seealso:: :ref:`SSL/TLS security considerations <ssl-security>`
Antoine Pitrouc5e075f2014-03-22 18:19:11 +0100288
Victor Stinnerea3183f2013-12-03 01:08:00 +0100289 * *server_hostname*, is only for use together with *ssl*,
290 and sets or overrides the hostname that the target server's certificate
291 will be matched against. By default the value of the *host* argument
292 is used. If *host* is empty, there is no default and you must pass a
293 value for *server_hostname*. If *server_hostname* is an empty
294 string, hostname matching is disabled (which is a serious security
295 risk, allowing for man-in-the-middle-attacks).
296
297 * *family*, *proto*, *flags* are the optional address family, protocol
298 and flags to be passed through to getaddrinfo() for *host* resolution.
299 If given, these should all be integers from the corresponding
300 :mod:`socket` module constants.
301
302 * *sock*, if given, should be an existing, already connected
303 :class:`socket.socket` object to be used by the transport.
304 If *sock* is given, none of *host*, *port*, *family*, *proto*, *flags*
305 and *local_addr* should be specified.
306
307 * *local_addr*, if given, is a ``(local_host, local_port)`` tuple used
308 to bind the socket to locally. The *local_host* and *local_port*
309 are looked up using getaddrinfo(), similarly to *host* and *port*.
310
Victor Stinner60208a12015-09-15 22:41:52 +0200311 .. versionchanged:: 3.5
312
313 On Windows with :class:`ProactorEventLoop`, SSL/TLS is now supported.
Victor Stinner41f3c3f2014-08-31 14:47:37 +0200314
Victor Stinnerc8ea8132014-01-23 11:02:09 +0100315 .. seealso::
316
317 The :func:`open_connection` function can be used to get a pair of
318 (:class:`StreamReader`, :class:`StreamWriter`) instead of a protocol.
319
Victor Stinnerea3183f2013-12-03 01:08:00 +0100320
Guido van Rossumf68afd82016-08-08 09:41:21 -0700321.. 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 +0100322
323 Create datagram connection: socket family :py:data:`~socket.AF_INET` or
324 :py:data:`~socket.AF_INET6` depending on *host* (or *family* if specified),
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700325 socket type :py:data:`~socket.SOCK_DGRAM`. *protocol_factory* must be a
326 callable returning a :ref:`protocol <asyncio-protocol>` instance.
Victor Stinnera6919aa2014-02-19 13:32:34 +0100327
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500328 This method is a :ref:`coroutine <coroutine>` which will try to
Victor Stinnera6919aa2014-02-19 13:32:34 +0100329 establish the connection in the background. When successful, the
330 coroutine returns a ``(transport, protocol)`` pair.
331
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700332 Options changing how the connection is created:
333
334 * *local_addr*, if given, is a ``(local_host, local_port)`` tuple used
335 to bind the socket to locally. The *local_host* and *local_port*
336 are looked up using :meth:`getaddrinfo`.
337
338 * *remote_addr*, if given, is a ``(remote_host, remote_port)`` tuple used
339 to connect the socket to a remote address. The *remote_host* and
340 *remote_port* are looked up using :meth:`getaddrinfo`.
341
342 * *family*, *proto*, *flags* are the optional address family, protocol
343 and flags to be passed through to :meth:`getaddrinfo` for *host*
344 resolution. If given, these should all be integers from the
345 corresponding :mod:`socket` module constants.
346
347 * *reuse_address* tells the kernel to reuse a local socket in
348 TIME_WAIT state, without waiting for its natural timeout to
349 expire. If not specified will automatically be set to True on
350 UNIX.
351
352 * *reuse_port* tells the kernel to allow this endpoint to be bound to the
353 same port as other existing endpoints are bound to, so long as they all
354 set this flag when being created. This option is not supported on Windows
355 and some UNIX's. If the :py:data:`~socket.SO_REUSEPORT` constant is not
356 defined then this capability is unsupported.
357
358 * *allow_broadcast* tells the kernel to allow this endpoint to send
359 messages to the broadcast address.
360
361 * *sock* can optionally be specified in order to use a preexisting,
362 already connected, :class:`socket.socket` object to be used by the
363 transport. If specified, *local_addr* and *remote_addr* should be omitted
364 (must be :const:`None`).
Victor Stinnera6919aa2014-02-19 13:32:34 +0100365
Victor Stinner41f3c3f2014-08-31 14:47:37 +0200366 On Windows with :class:`ProactorEventLoop`, this method is not supported.
367
Victor Stinnerc7edffd2014-10-12 11:24:26 +0200368 See :ref:`UDP echo client protocol <asyncio-udp-echo-client-protocol>` and
369 :ref:`UDP echo server protocol <asyncio-udp-echo-server-protocol>` examples.
370
Victor Stinnera6919aa2014-02-19 13:32:34 +0100371
Guido van Rossumf68afd82016-08-08 09:41:21 -0700372.. coroutinemethod:: AbstractEventLoop.create_unix_connection(protocol_factory, path, \*, ssl=None, sock=None, server_hostname=None)
Victor Stinnera6919aa2014-02-19 13:32:34 +0100373
374 Create UNIX connection: socket family :py:data:`~socket.AF_UNIX`, socket
375 type :py:data:`~socket.SOCK_STREAM`. The :py:data:`~socket.AF_UNIX` socket
376 family is used to communicate between processes on the same machine
377 efficiently.
378
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500379 This method is a :ref:`coroutine <coroutine>` which will try to
Victor Stinnera6919aa2014-02-19 13:32:34 +0100380 establish the connection in the background. When successful, the
381 coroutine returns a ``(transport, protocol)`` pair.
382
Guido van Rossumf68afd82016-08-08 09:41:21 -0700383 See the :meth:`AbstractEventLoop.create_connection` method for parameters.
Victor Stinnera6919aa2014-02-19 13:32:34 +0100384
385 Availability: UNIX.
386
387
Victor Stinnerea3183f2013-12-03 01:08:00 +0100388Creating listening connections
389------------------------------
390
Guido van Rossumf68afd82016-08-08 09:41:21 -0700391.. 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 +0100392
Victor Stinner33f6abe2014-10-12 20:36:04 +0200393 Create a TCP server (socket type :data:`~socket.SOCK_STREAM`) bound to
394 *host* and *port*.
395
396 Return a :class:`Server` object, its :attr:`~Server.sockets` attribute
397 contains created sockets. Use the :meth:`Server.close` method to stop the
398 server: close listening sockets.
399
400 Parameters:
401
Victor Stinner5e4a7d82015-09-21 18:33:43 +0200402 * The *host* parameter can be a string, in that case the TCP server is
403 bound to *host* and *port*. The *host* parameter can also be a sequence
404 of strings and in that case the TCP server is bound to all hosts of the
405 sequence. If *host* is an empty string or ``None``, all interfaces are
406 assumed and a list of multiple sockets will be returned (most likely one
407 for IPv4 and another one for IPv6).
Victor Stinner33f6abe2014-10-12 20:36:04 +0200408
409 * *family* can be set to either :data:`socket.AF_INET` or
410 :data:`~socket.AF_INET6` to force the socket to use IPv4 or IPv6. If not set
411 it will be determined from host (defaults to :data:`socket.AF_UNSPEC`).
412
413 * *flags* is a bitmask for :meth:`getaddrinfo`.
414
415 * *sock* can optionally be specified in order to use a preexisting
416 socket object. If specified, *host* and *port* should be omitted (must be
417 :const:`None`).
418
419 * *backlog* is the maximum number of queued connections passed to
420 :meth:`~socket.socket.listen` (defaults to 100).
421
422 * *ssl* can be set to an :class:`~ssl.SSLContext` to enable SSL over the
423 accepted connections.
424
425 * *reuse_address* tells the kernel to reuse a local socket in
426 TIME_WAIT state, without waiting for its natural timeout to
427 expire. If not specified will automatically be set to True on
428 UNIX.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100429
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700430 * *reuse_port* tells the kernel to allow this endpoint to be bound to the
431 same port as other existing endpoints are bound to, so long as they all
432 set this flag when being created. This option is not supported on
433 Windows.
434
Victor Stinnerd1432092014-06-19 17:11:49 +0200435 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100436
Victor Stinner60208a12015-09-15 22:41:52 +0200437 .. versionchanged:: 3.5
438
439 On Windows with :class:`ProactorEventLoop`, SSL/TLS is now supported.
Victor Stinner41f3c3f2014-08-31 14:47:37 +0200440
Victor Stinnerc8ea8132014-01-23 11:02:09 +0100441 .. seealso::
442
443 The function :func:`start_server` creates a (:class:`StreamReader`,
444 :class:`StreamWriter`) pair and calls back a function with this pair.
445
Victor Stinner7b58a2b2015-09-21 18:41:05 +0200446 .. versionchanged:: 3.5.1
Victor Stinner5e4a7d82015-09-21 18:33:43 +0200447
448 The *host* parameter can now be a sequence of strings.
449
Victor Stinnerea3183f2013-12-03 01:08:00 +0100450
Guido van Rossumf68afd82016-08-08 09:41:21 -0700451.. coroutinemethod:: AbstractEventLoop.create_unix_server(protocol_factory, path=None, \*, sock=None, backlog=100, ssl=None)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100452
Guido van Rossumf68afd82016-08-08 09:41:21 -0700453 Similar to :meth:`AbstractEventLoop.create_server`, but specific to the
Victor Stinnera6919aa2014-02-19 13:32:34 +0100454 socket family :py:data:`~socket.AF_UNIX`.
455
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100456 This method is a :ref:`coroutine <coroutine>`.
457
Victor Stinnera6919aa2014-02-19 13:32:34 +0100458 Availability: UNIX.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100459
460
Victor Stinnerc1567df2014-02-08 23:22:58 +0100461Watch file descriptors
462----------------------
463
Victor Stinner41f3c3f2014-08-31 14:47:37 +0200464On Windows with :class:`SelectorEventLoop`, only socket handles are supported
465(ex: pipe file descriptors are not supported).
466
467On Windows with :class:`ProactorEventLoop`, these methods are not supported.
468
Guido van Rossumf68afd82016-08-08 09:41:21 -0700469.. method:: AbstractEventLoop.add_reader(fd, callback, \*args)
Victor Stinnerc1567df2014-02-08 23:22:58 +0100470
471 Start watching the file descriptor for read availability and then call the
472 *callback* with specified arguments.
473
Victor Stinner8464c242014-11-28 13:15:41 +0100474 :ref:`Use functools.partial to pass keywords to the callback
475 <asyncio-pass-keywords>`.
476
Guido van Rossumf68afd82016-08-08 09:41:21 -0700477.. method:: AbstractEventLoop.remove_reader(fd)
Victor Stinnerc1567df2014-02-08 23:22:58 +0100478
479 Stop watching the file descriptor for read availability.
480
Guido van Rossumf68afd82016-08-08 09:41:21 -0700481.. method:: AbstractEventLoop.add_writer(fd, callback, \*args)
Victor Stinnerc1567df2014-02-08 23:22:58 +0100482
483 Start watching the file descriptor for write availability and then call the
484 *callback* with specified arguments.
485
Victor Stinner8464c242014-11-28 13:15:41 +0100486 :ref:`Use functools.partial to pass keywords to the callback
487 <asyncio-pass-keywords>`.
488
Guido van Rossumf68afd82016-08-08 09:41:21 -0700489.. method:: AbstractEventLoop.remove_writer(fd)
Victor Stinnerc1567df2014-02-08 23:22:58 +0100490
491 Stop watching the file descriptor for write availability.
492
Victor Stinner04e6df32014-10-11 16:16:27 +0200493The :ref:`watch a file descriptor for read events <asyncio-watch-read-event>`
Guido van Rossumf68afd82016-08-08 09:41:21 -0700494example uses the low-level :meth:`AbstractEventLoop.add_reader` method to register
Victor Stinner04e6df32014-10-11 16:16:27 +0200495the file descriptor of a socket.
496
Victor Stinnerc1567df2014-02-08 23:22:58 +0100497
498Low-level socket operations
499---------------------------
500
Guido van Rossumf68afd82016-08-08 09:41:21 -0700501.. coroutinemethod:: AbstractEventLoop.sock_recv(sock, nbytes)
Victor Stinnerc1567df2014-02-08 23:22:58 +0100502
Yury Selivanov55c50842016-06-08 12:48:15 -0400503 Receive data from the socket. Modeled after blocking
504 :meth:`socket.socket.recv` method.
505
506 The return value is a bytes object
Victor Stinnerc1567df2014-02-08 23:22:58 +0100507 representing the data received. The maximum amount of data to be received
508 at once is specified by *nbytes*.
509
Victor Stinnerd84fd732014-08-26 01:01:59 +0200510 With :class:`SelectorEventLoop` event loop, the socket *sock* must be
511 non-blocking.
Victor Stinnerec2ce092014-07-29 23:12:22 +0200512
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500513 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100514
Guido van Rossumf68afd82016-08-08 09:41:21 -0700515.. coroutinemethod:: AbstractEventLoop.sock_sendall(sock, data)
Victor Stinnerc1567df2014-02-08 23:22:58 +0100516
Yury Selivanov55c50842016-06-08 12:48:15 -0400517 Send data to the socket. Modeled after blocking
518 :meth:`socket.socket.sendall` method.
519
520 The socket must be connected to a remote socket.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100521 This method continues to send data from *data* until either all data has
522 been sent or an error occurs. ``None`` is returned on success. On error,
523 an exception is raised, and there is no way to determine how much data, if
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500524 any, was successfully processed by the receiving end of the connection.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100525
Victor Stinnerd84fd732014-08-26 01:01:59 +0200526 With :class:`SelectorEventLoop` event loop, the socket *sock* must be
527 non-blocking.
Victor Stinnerec2ce092014-07-29 23:12:22 +0200528
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500529 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100530
Guido van Rossumf68afd82016-08-08 09:41:21 -0700531.. coroutinemethod:: AbstractEventLoop.sock_connect(sock, address)
Victor Stinnerc1567df2014-02-08 23:22:58 +0100532
Yury Selivanov55c50842016-06-08 12:48:15 -0400533 Connect to a remote socket at *address*. Modeled after
534 blocking :meth:`socket.socket.connect` method.
Victor Stinner1b0580b2014-02-13 09:24:37 +0100535
Victor Stinnerd84fd732014-08-26 01:01:59 +0200536 With :class:`SelectorEventLoop` event loop, the socket *sock* must be
537 non-blocking.
Victor Stinnerec2ce092014-07-29 23:12:22 +0200538
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500539 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100540
Yury Selivanov55c50842016-06-08 12:48:15 -0400541 .. versionchanged:: 3.5.2
542 ``address`` no longer needs to be resolved. ``sock_connect``
543 will try to check if the *address* is already resolved by calling
544 :func:`socket.inet_pton`. If not,
Guido van Rossumf68afd82016-08-08 09:41:21 -0700545 :meth:`AbstractEventLoop.getaddrinfo` will be used to resolve the
Yury Selivanov55c50842016-06-08 12:48:15 -0400546 *address*.
547
Victor Stinnerc1567df2014-02-08 23:22:58 +0100548 .. seealso::
549
Guido van Rossumf68afd82016-08-08 09:41:21 -0700550 :meth:`AbstractEventLoop.create_connection`
Yury Selivanov55c50842016-06-08 12:48:15 -0400551 and :func:`asyncio.open_connection() <open_connection>`.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100552
553
Guido van Rossumf68afd82016-08-08 09:41:21 -0700554.. coroutinemethod:: AbstractEventLoop.sock_accept(sock)
Victor Stinnerc1567df2014-02-08 23:22:58 +0100555
Yury Selivanov55c50842016-06-08 12:48:15 -0400556 Accept a connection. Modeled after blocking
557 :meth:`socket.socket.accept`.
558
559 The socket must be bound to an address and listening
Victor Stinnerc1567df2014-02-08 23:22:58 +0100560 for connections. The return value is a pair ``(conn, address)`` where *conn*
561 is a *new* socket object usable to send and receive data on the connection,
562 and *address* is the address bound to the socket on the other end of the
563 connection.
564
Victor Stinnerec2ce092014-07-29 23:12:22 +0200565 The socket *sock* must be non-blocking.
566
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500567 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100568
569 .. seealso::
570
Guido van Rossumf68afd82016-08-08 09:41:21 -0700571 :meth:`AbstractEventLoop.create_server` and :func:`start_server`.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100572
573
574Resolve host name
575-----------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100576
Guido van Rossumf68afd82016-08-08 09:41:21 -0700577.. coroutinemethod:: AbstractEventLoop.getaddrinfo(host, port, \*, family=0, type=0, proto=0, flags=0)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100578
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500579 This method is a :ref:`coroutine <coroutine>`, similar to
580 :meth:`socket.getaddrinfo` function but non-blocking.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100581
Guido van Rossumf68afd82016-08-08 09:41:21 -0700582.. coroutinemethod:: AbstractEventLoop.getnameinfo(sockaddr, flags=0)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100583
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500584 This method is a :ref:`coroutine <coroutine>`, similar to
585 :meth:`socket.getnameinfo` function but non-blocking.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100586
587
Victor Stinner984600f2014-03-25 09:40:26 +0100588Connect pipes
589-------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100590
Victor Stinner41f3c3f2014-08-31 14:47:37 +0200591On Windows with :class:`SelectorEventLoop`, these methods are not supported.
592Use :class:`ProactorEventLoop` to support pipes on Windows.
593
Guido van Rossumf68afd82016-08-08 09:41:21 -0700594.. coroutinemethod:: AbstractEventLoop.connect_read_pipe(protocol_factory, pipe)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100595
Victor Stinnerd84fd732014-08-26 01:01:59 +0200596 Register read pipe in eventloop.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100597
598 *protocol_factory* should instantiate object with :class:`Protocol`
Victor Stinnera5b257a2014-05-29 00:14:03 +0200599 interface. *pipe* is a :term:`file-like object <file object>`.
600 Return pair ``(transport, protocol)``, where *transport* supports the
Victor Stinnerea3183f2013-12-03 01:08:00 +0100601 :class:`ReadTransport` interface.
602
Victor Stinnerd84fd732014-08-26 01:01:59 +0200603 With :class:`SelectorEventLoop` event loop, the *pipe* is set to
604 non-blocking mode.
605
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500606 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100607
Guido van Rossumf68afd82016-08-08 09:41:21 -0700608.. coroutinemethod:: AbstractEventLoop.connect_write_pipe(protocol_factory, pipe)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100609
610 Register write pipe in eventloop.
611
612 *protocol_factory* should instantiate object with :class:`BaseProtocol`
Victor Stinner2cef3002014-10-23 22:38:46 +0200613 interface. *pipe* is :term:`file-like object <file object>`.
614 Return pair ``(transport, protocol)``, where *transport* supports
Victor Stinnerea3183f2013-12-03 01:08:00 +0100615 :class:`WriteTransport` interface.
616
Victor Stinnerd84fd732014-08-26 01:01:59 +0200617 With :class:`SelectorEventLoop` event loop, the *pipe* is set to
618 non-blocking mode.
619
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500620 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100621
Victor Stinner08444382014-02-02 22:43:39 +0100622.. seealso::
623
Guido van Rossumf68afd82016-08-08 09:41:21 -0700624 The :meth:`AbstractEventLoop.subprocess_exec` and
625 :meth:`AbstractEventLoop.subprocess_shell` methods.
Victor Stinner08444382014-02-02 22:43:39 +0100626
Victor Stinnerea3183f2013-12-03 01:08:00 +0100627
Victor Stinner8b863482014-01-27 10:07:50 +0100628UNIX signals
629------------
630
631Availability: UNIX only.
632
Guido van Rossumf68afd82016-08-08 09:41:21 -0700633.. method:: AbstractEventLoop.add_signal_handler(signum, callback, \*args)
Victor Stinner8b863482014-01-27 10:07:50 +0100634
635 Add a handler for a signal.
636
637 Raise :exc:`ValueError` if the signal number is invalid or uncatchable.
638 Raise :exc:`RuntimeError` if there is a problem setting up the handler.
639
Victor Stinner8464c242014-11-28 13:15:41 +0100640 :ref:`Use functools.partial to pass keywords to the callback
641 <asyncio-pass-keywords>`.
642
Guido van Rossumf68afd82016-08-08 09:41:21 -0700643.. method:: AbstractEventLoop.remove_signal_handler(sig)
Victor Stinner8b863482014-01-27 10:07:50 +0100644
645 Remove a handler for a signal.
646
647 Return ``True`` if a signal handler was removed, ``False`` if not.
648
649.. seealso::
650
651 The :mod:`signal` module.
652
653
Victor Stinnerea3183f2013-12-03 01:08:00 +0100654Executor
655--------
656
657Call a function in an :class:`~concurrent.futures.Executor` (pool of threads or
658pool of processes). By default, an event loop uses a thread pool executor
659(:class:`~concurrent.futures.ThreadPoolExecutor`).
660
Guido van Rossumf68afd82016-08-08 09:41:21 -0700661.. coroutinemethod:: AbstractEventLoop.run_in_executor(executor, func, \*args)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100662
Andrew Svetlov1c62b522015-10-01 09:48:08 +0300663 Arrange for a *func* to be called in the specified executor.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100664
Larry Hastings3732ed22014-03-15 21:13:56 -0700665 The *executor* argument should be an :class:`~concurrent.futures.Executor`
666 instance. The default executor is used if *executor* is ``None``.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100667
Andrew Svetlov1c62b522015-10-01 09:48:08 +0300668 :ref:`Use functools.partial to pass keywords to the *func*
Victor Stinner8464c242014-11-28 13:15:41 +0100669 <asyncio-pass-keywords>`.
670
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500671 This method is a :ref:`coroutine <coroutine>`.
672
Guido van Rossumf68afd82016-08-08 09:41:21 -0700673.. method:: AbstractEventLoop.set_default_executor(executor)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100674
675 Set the default executor used by :meth:`run_in_executor`.
676
677
Yury Selivanov43ee1c12014-02-19 20:58:44 -0500678Error Handling API
679------------------
680
Martin Panterc04fb562016-02-10 05:44:01 +0000681Allows customizing how exceptions are handled in the event loop.
Yury Selivanov43ee1c12014-02-19 20:58:44 -0500682
Guido van Rossumf68afd82016-08-08 09:41:21 -0700683.. method:: AbstractEventLoop.set_exception_handler(handler)
Yury Selivanov43ee1c12014-02-19 20:58:44 -0500684
685 Set *handler* as the new event loop exception handler.
686
687 If *handler* is ``None``, the default exception handler will
688 be set.
689
690 If *handler* is a callable object, it should have a
691 matching signature to ``(loop, context)``, where ``loop``
692 will be a reference to the active event loop, ``context``
693 will be a ``dict`` object (see :meth:`call_exception_handler`
694 documentation for details about context).
695
Guido van Rossumf68afd82016-08-08 09:41:21 -0700696.. method:: AbstractEventLoop.get_exception_handler()
Yury Selivanov950204d2016-05-16 16:23:00 -0400697
698 Return the exception handler, or ``None`` if the default one
699 is in use.
700
701 .. versionadded:: 3.5.2
702
Guido van Rossumf68afd82016-08-08 09:41:21 -0700703.. method:: AbstractEventLoop.default_exception_handler(context)
Yury Selivanov43ee1c12014-02-19 20:58:44 -0500704
705 Default exception handler.
706
707 This is called when an exception occurs and no exception
708 handler is set, and can be called by a custom exception
709 handler that wants to defer to the default behavior.
710
711 *context* parameter has the same meaning as in
712 :meth:`call_exception_handler`.
713
Guido van Rossumf68afd82016-08-08 09:41:21 -0700714.. method:: AbstractEventLoop.call_exception_handler(context)
Yury Selivanov43ee1c12014-02-19 20:58:44 -0500715
716 Call the current event loop exception handler.
717
718 *context* is a ``dict`` object containing the following keys
719 (new keys may be introduced later):
720
721 * 'message': Error message;
722 * 'exception' (optional): Exception object;
723 * 'future' (optional): :class:`asyncio.Future` instance;
724 * 'handle' (optional): :class:`asyncio.Handle` instance;
725 * 'protocol' (optional): :ref:`Protocol <asyncio-protocol>` instance;
726 * 'transport' (optional): :ref:`Transport <asyncio-transport>` instance;
727 * 'socket' (optional): :class:`socket.socket` instance.
728
729 .. note::
730
731 Note: this method should not be overloaded in subclassed
732 event loops. For any custom exception handling, use
733 :meth:`set_exception_handler()` method.
734
Victor Stinner0f3e6bc2014-02-19 23:15:02 +0100735Debug mode
736----------
737
Guido van Rossumf68afd82016-08-08 09:41:21 -0700738.. method:: AbstractEventLoop.get_debug()
Victor Stinner0f3e6bc2014-02-19 23:15:02 +0100739
Victor Stinner7b7120e2014-06-23 00:12:14 +0200740 Get the debug mode (:class:`bool`) of the event loop.
741
742 The default value is ``True`` if the environment variable
743 :envvar:`PYTHONASYNCIODEBUG` is set to a non-empty string, ``False``
744 otherwise.
Victor Stinner0f3e6bc2014-02-19 23:15:02 +0100745
Victor Stinner64d750b2014-06-18 03:25:23 +0200746 .. versionadded:: 3.4.2
747
Guido van Rossumf68afd82016-08-08 09:41:21 -0700748.. method:: AbstractEventLoop.set_debug(enabled: bool)
Victor Stinner0f3e6bc2014-02-19 23:15:02 +0100749
750 Set the debug mode of the event loop.
751
Victor Stinner64d750b2014-06-18 03:25:23 +0200752 .. versionadded:: 3.4.2
753
Victor Stinner0f3e6bc2014-02-19 23:15:02 +0100754.. seealso::
755
Victor Stinner62511fd2014-06-23 00:36:11 +0200756 The :ref:`debug mode of asyncio <asyncio-debug-mode>`.
Victor Stinner0f3e6bc2014-02-19 23:15:02 +0100757
Victor Stinner8c462c52014-01-24 18:11:43 +0100758Server
759------
760
Victor Stinner8ebeb032014-07-11 23:47:40 +0200761.. class:: Server
Victor Stinner8c462c52014-01-24 18:11:43 +0100762
Victor Stinner8ebeb032014-07-11 23:47:40 +0200763 Server listening on sockets.
764
Guido van Rossumf68afd82016-08-08 09:41:21 -0700765 Object created by the :meth:`AbstractEventLoop.create_server` method and the
R David Murray756f0b12015-01-29 19:53:33 -0500766 :func:`start_server` function. Don't instantiate the class directly.
Victor Stinner8c462c52014-01-24 18:11:43 +0100767
768 .. method:: close()
769
Victor Stinner4bfb14a2014-07-12 03:20:24 +0200770 Stop serving: close listening sockets and set the :attr:`sockets`
771 attribute to ``None``.
772
Berker Peksag49c9edf2016-01-20 07:14:22 +0200773 The sockets that represent existing incoming client connections are left
774 open.
Victor Stinner8ebeb032014-07-11 23:47:40 +0200775
Berker Peksag49c9edf2016-01-20 07:14:22 +0200776 The server is closed asynchronously, use the :meth:`wait_closed`
777 coroutine to wait until the server is closed.
Victor Stinner8c462c52014-01-24 18:11:43 +0100778
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100779 .. coroutinemethod:: wait_closed()
Victor Stinner8c462c52014-01-24 18:11:43 +0100780
Victor Stinner8ebeb032014-07-11 23:47:40 +0200781 Wait until the :meth:`close` method completes.
782
783 This method is a :ref:`coroutine <coroutine>`.
784
785 .. attribute:: sockets
786
787 List of :class:`socket.socket` objects the server is listening to, or
788 ``None`` if the server is closed.
Victor Stinner8c462c52014-01-24 18:11:43 +0100789
790
Yury Selivanov43ee1c12014-02-19 20:58:44 -0500791Handle
792------
793
794.. class:: Handle
795
Guido van Rossumf68afd82016-08-08 09:41:21 -0700796 A callback wrapper object returned by :func:`AbstractEventLoop.call_soon`,
797 :func:`AbstractEventLoop.call_soon_threadsafe`, :func:`AbstractEventLoop.call_later`,
798 and :func:`AbstractEventLoop.call_at`.
Yury Selivanov43ee1c12014-02-19 20:58:44 -0500799
800 .. method:: cancel()
801
Yury Selivanov1096f762015-06-25 13:49:52 -0400802 Cancel the call. If the callback is already canceled or executed,
803 this method has no effect.
Victor Stinneraea82292014-07-08 23:42:38 +0200804
Yury Selivanov43ee1c12014-02-19 20:58:44 -0500805
Victor Stinner6888b962014-10-11 16:15:58 +0200806Event loop examples
Victor Stinnera092a612015-01-09 15:58:41 +0100807-------------------
Yury Selivanov43ee1c12014-02-19 20:58:44 -0500808
Victor Stinner3e09e322013-12-03 01:22:06 +0100809.. _asyncio-hello-world-callback:
Victor Stinnerea3183f2013-12-03 01:08:00 +0100810
Victor Stinner7f314ed2014-10-15 18:49:16 +0200811Hello World with call_soon()
Victor Stinnera092a612015-01-09 15:58:41 +0100812^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Victor Stinnerea3183f2013-12-03 01:08:00 +0100813
Guido van Rossumf68afd82016-08-08 09:41:21 -0700814Example using the :meth:`AbstractEventLoop.call_soon` method to schedule a
Victor Stinner7f314ed2014-10-15 18:49:16 +0200815callback. The callback displays ``"Hello World"`` and then stops the event
816loop::
Victor Stinnerea3183f2013-12-03 01:08:00 +0100817
818 import asyncio
819
Victor Stinner7f314ed2014-10-15 18:49:16 +0200820 def hello_world(loop):
Victor Stinnerea3183f2013-12-03 01:08:00 +0100821 print('Hello World')
Victor Stinner7f314ed2014-10-15 18:49:16 +0200822 loop.stop()
Victor Stinnerea3183f2013-12-03 01:08:00 +0100823
824 loop = asyncio.get_event_loop()
Victor Stinner7f314ed2014-10-15 18:49:16 +0200825
826 # Schedule a call to hello_world()
827 loop.call_soon(hello_world, loop)
828
829 # Blocking call interrupted by loop.stop()
830 loop.run_forever()
831 loop.close()
Victor Stinnerea3183f2013-12-03 01:08:00 +0100832
Victor Stinner3e09e322013-12-03 01:22:06 +0100833.. seealso::
Victor Stinnerea3183f2013-12-03 01:08:00 +0100834
Victor Stinner6888b962014-10-11 16:15:58 +0200835 The :ref:`Hello World coroutine <asyncio-hello-world-coroutine>` example
836 uses a :ref:`coroutine <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100837
Victor Stinner8b863482014-01-27 10:07:50 +0100838
Victor Stinner7f314ed2014-10-15 18:49:16 +0200839.. _asyncio-date-callback:
840
841Display the current date with call_later()
Victor Stinnera092a612015-01-09 15:58:41 +0100842^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Victor Stinner7f314ed2014-10-15 18:49:16 +0200843
844Example of callback displaying the current date every second. The callback uses
Guido van Rossumf68afd82016-08-08 09:41:21 -0700845the :meth:`AbstractEventLoop.call_later` method to reschedule itself during 5
Victor Stinner7f314ed2014-10-15 18:49:16 +0200846seconds, and then stops the event loop::
847
848 import asyncio
849 import datetime
850
851 def display_date(end_time, loop):
852 print(datetime.datetime.now())
853 if (loop.time() + 1.0) < end_time:
854 loop.call_later(1, display_date, end_time, loop)
855 else:
856 loop.stop()
857
858 loop = asyncio.get_event_loop()
859
860 # Schedule the first call to display_date()
861 end_time = loop.time() + 5.0
862 loop.call_soon(display_date, end_time, loop)
863
864 # Blocking call interrupted by loop.stop()
865 loop.run_forever()
866 loop.close()
867
868.. seealso::
869
870 The :ref:`coroutine displaying the current date
871 <asyncio-date-coroutine>` example uses a :ref:`coroutine
872 <coroutine>`.
873
874
Victor Stinner04e6df32014-10-11 16:16:27 +0200875.. _asyncio-watch-read-event:
Victor Stinner8b863482014-01-27 10:07:50 +0100876
Victor Stinner04e6df32014-10-11 16:16:27 +0200877Watch a file descriptor for read events
Victor Stinnera092a612015-01-09 15:58:41 +0100878^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Victor Stinner04e6df32014-10-11 16:16:27 +0200879
880Wait until a file descriptor received some data using the
Guido van Rossumf68afd82016-08-08 09:41:21 -0700881:meth:`AbstractEventLoop.add_reader` method and then close the event loop::
Victor Stinner04e6df32014-10-11 16:16:27 +0200882
883 import asyncio
Victor Stinnerccd8e342014-10-11 16:30:02 +0200884 try:
885 from socket import socketpair
886 except ImportError:
887 from asyncio.windows_utils import socketpair
Victor Stinner04e6df32014-10-11 16:16:27 +0200888
889 # Create a pair of connected file descriptors
Victor Stinnerccd8e342014-10-11 16:30:02 +0200890 rsock, wsock = socketpair()
Victor Stinner04e6df32014-10-11 16:16:27 +0200891 loop = asyncio.get_event_loop()
892
893 def reader():
894 data = rsock.recv(100)
895 print("Received:", data.decode())
Victor Stinner2cef3002014-10-23 22:38:46 +0200896 # We are done: unregister the file descriptor
Victor Stinner04e6df32014-10-11 16:16:27 +0200897 loop.remove_reader(rsock)
898 # Stop the event loop
899 loop.stop()
900
Victor Stinner2cef3002014-10-23 22:38:46 +0200901 # Register the file descriptor for read event
Victor Stinner04e6df32014-10-11 16:16:27 +0200902 loop.add_reader(rsock, reader)
903
904 # Simulate the reception of data from the network
905 loop.call_soon(wsock.send, 'abc'.encode())
906
907 # Run the event loop
908 loop.run_forever()
909
910 # We are done, close sockets and the event loop
911 rsock.close()
912 wsock.close()
913 loop.close()
914
915.. seealso::
916
917 The :ref:`register an open socket to wait for data using a protocol
918 <asyncio-register-socket>` example uses a low-level protocol created by the
Guido van Rossumf68afd82016-08-08 09:41:21 -0700919 :meth:`AbstractEventLoop.create_connection` method.
Victor Stinner04e6df32014-10-11 16:16:27 +0200920
921 The :ref:`register an open socket to wait for data using streams
922 <asyncio-register-socket-streams>` example uses high-level streams
923 created by the :func:`open_connection` function in a coroutine.
924
925
926Set signal handlers for SIGINT and SIGTERM
Victor Stinnera092a612015-01-09 15:58:41 +0100927^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Victor Stinner04e6df32014-10-11 16:16:27 +0200928
929Register handlers for signals :py:data:`SIGINT` and :py:data:`SIGTERM` using
Guido van Rossumf68afd82016-08-08 09:41:21 -0700930the :meth:`AbstractEventLoop.add_signal_handler` method::
Victor Stinner8b863482014-01-27 10:07:50 +0100931
932 import asyncio
933 import functools
934 import os
935 import signal
936
937 def ask_exit(signame):
938 print("got signal %s: exit" % signame)
939 loop.stop()
940
941 loop = asyncio.get_event_loop()
942 for signame in ('SIGINT', 'SIGTERM'):
943 loop.add_signal_handler(getattr(signal, signame),
944 functools.partial(ask_exit, signame))
945
Serhiy Storchaka0424eaf2015-09-12 17:45:25 +0300946 print("Event loop running forever, press Ctrl+C to interrupt.")
Victor Stinner8b863482014-01-27 10:07:50 +0100947 print("pid %s: send SIGINT or SIGTERM to exit." % os.getpid())
Victor Stinner63b21a82014-07-05 15:38:59 +0200948 try:
949 loop.run_forever()
950 finally:
951 loop.close()
Victor Stinner2cef3002014-10-23 22:38:46 +0200952
953This example only works on UNIX.