blob: 809a3e77d51ea0f9e176e4fa8169a69e4047e0e4 [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
Victor Stinneraea82292014-07-08 23:42:38 +020023 Base class of event loops.
Victor Stinnerea3183f2013-12-03 01:08:00 +010024
Victor Stinner83704962015-02-25 14:24:15 +010025 This class is :ref:`not thread safe <asyncio-multithreading>`.
26
Victor Stinnerea3183f2013-12-03 01:08:00 +010027Run an event loop
28-----------------
29
30.. method:: BaseEventLoop.run_forever()
31
Guido van Rossum41f69f42015-11-19 13:28:47 -080032 Run until :meth:`stop` is called. If :meth:`stop` is called before
33 :meth:`run_forever()` is called, this polls the I/O selector once
34 with a timeout of zero, runs all callbacks scheduled in response to
35 I/O events (and those that were already scheduled), and then exits.
36 If :meth:`stop` is called while :meth:`run_forever` is running,
37 this will run the current batch of callbacks and then exit. Note
38 that callbacks scheduled by callbacks will not run in that case;
39 they will run the next time :meth:`run_forever` is called.
40
Guido van Rossum82f9fea2015-11-19 13:33:34 -080041 .. versionchanged:: 3.5.1
Victor Stinnerea3183f2013-12-03 01:08:00 +010042
43.. method:: BaseEventLoop.run_until_complete(future)
44
Victor Stinner99c2ab42013-12-03 19:17:25 +010045 Run until the :class:`Future` is done.
Victor Stinnerea3183f2013-12-03 01:08:00 +010046
Victor Stinner530ef2f2014-07-08 12:39:10 +020047 If the argument is a :ref:`coroutine object <coroutine>`, it is wrapped by
Yury Selivanov04356e12015-06-30 22:13:22 -040048 :func:`ensure_future`.
Victor Stinnerea3183f2013-12-03 01:08:00 +010049
50 Return the Future's result, or raise its exception.
51
52.. method:: BaseEventLoop.is_running()
53
54 Returns running status of event loop.
55
Victor Stinnerafbf8272013-12-03 02:05:42 +010056.. method:: BaseEventLoop.stop()
Victor Stinnerea3183f2013-12-03 01:08:00 +010057
58 Stop running the event loop.
59
Guido van Rossum41f69f42015-11-19 13:28:47 -080060 This causes :meth:`run_forever` to exit at the next suitable
61 opportunity (see there for more details).
62
Guido van Rossum82f9fea2015-11-19 13:33:34 -080063 .. versionchanged:: 3.5.1
Victor Stinnerea3183f2013-12-03 01:08:00 +010064
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +020065.. method:: BaseEventLoop.is_closed()
66
67 Returns ``True`` if the event loop was closed.
68
69 .. versionadded:: 3.4.2
70
Victor Stinnerea3183f2013-12-03 01:08:00 +010071.. method:: BaseEventLoop.close()
72
Guido van Rossum41f69f42015-11-19 13:28:47 -080073 Close the event loop. The loop must not be running. Pending
74 callbacks will be lost.
Victor Stinnerea3183f2013-12-03 01:08:00 +010075
76 This clears the queues and shuts down the executor, but does not wait for
77 the executor to finish.
78
79 This is idempotent and irreversible. No other methods should be called after
80 this one.
81
Victor Stinner8464c242014-11-28 13:15:41 +010082.. _asyncio-pass-keywords:
Victor Stinnerea3183f2013-12-03 01:08:00 +010083
84Calls
85-----
86
Victor Stinner8464c242014-11-28 13:15:41 +010087Most :mod:`asyncio` functions don't accept keywords. If you want to pass
88keywords to your callback, use :func:`functools.partial`. For example,
89``loop.call_soon(functools.partial(print, "Hello", flush=True))`` will call
90``print("Hello", flush=True)``.
91
92.. note::
93 :func:`functools.partial` is better than ``lambda`` functions, because
94 :mod:`asyncio` can inspect :func:`functools.partial` object to display
95 parameters in debug mode, whereas ``lambda`` functions have a poor
96 representation.
97
Victor Stinnerea3183f2013-12-03 01:08:00 +010098.. method:: BaseEventLoop.call_soon(callback, \*args)
99
Victor Stinner4d5115c2014-12-15 17:50:55 +0100100 Arrange for a callback to be called as soon as possible. The callback is
101 called after :meth:`call_soon` returns, when control returns to the event
102 loop.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100103
Serhiy Storchaka4ecfa452016-05-16 09:31:54 +0300104 This operates as a :abbr:`FIFO (first-in, first-out)` queue, callbacks
105 are called in the order in which they are registered. Each callback
106 will be called exactly once.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100107
108 Any positional arguments after the callback will be passed to the
109 callback when it is called.
110
Yury Selivanov1096f762015-06-25 13:49:52 -0400111 An instance of :class:`asyncio.Handle` is returned, which can be
112 used to cancel the callback.
Yury Selivanov43ee1c12014-02-19 20:58:44 -0500113
Victor Stinner8464c242014-11-28 13:15:41 +0100114 :ref:`Use functools.partial to pass keywords to the callback
115 <asyncio-pass-keywords>`.
116
Victor Stinnerea3183f2013-12-03 01:08:00 +0100117.. method:: BaseEventLoop.call_soon_threadsafe(callback, \*args)
118
119 Like :meth:`call_soon`, but thread safe.
120
Victor Stinner83704962015-02-25 14:24:15 +0100121 See the :ref:`concurrency and multithreading <asyncio-multithreading>`
122 section of the documentation.
123
Victor Stinnerea3183f2013-12-03 01:08:00 +0100124
Victor Stinner45b27ed2014-02-01 02:36:43 +0100125.. _asyncio-delayed-calls:
126
Victor Stinnerea3183f2013-12-03 01:08:00 +0100127Delayed calls
128-------------
129
130The event loop has its own internal clock for computing timeouts.
131Which clock is used depends on the (platform-specific) event loop
132implementation; ideally it is a monotonic clock. This will generally be
133a different clock than :func:`time.time`.
134
Victor Stinnerfd9d3742014-02-18 09:37:43 +0100135.. note::
136
137 Timeouts (relative *delay* or absolute *when*) should not exceed one day.
138
Victor Stinner45b27ed2014-02-01 02:36:43 +0100139
Victor Stinnerea3183f2013-12-03 01:08:00 +0100140.. method:: BaseEventLoop.call_later(delay, callback, *args)
141
142 Arrange for the *callback* to be called after the given *delay*
143 seconds (either an int or float).
144
Yury Selivanov1096f762015-06-25 13:49:52 -0400145 An instance of :class:`asyncio.Handle` is returned, which can be
146 used to cancel the callback.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100147
148 *callback* will be called exactly once per call to :meth:`call_later`.
149 If two callbacks are scheduled for exactly the same time, it is
150 undefined which will be called first.
151
152 The optional positional *args* will be passed to the callback when it
153 is called. If you want the callback to be called with some named
154 arguments, use a closure or :func:`functools.partial`.
155
Victor Stinner8464c242014-11-28 13:15:41 +0100156 :ref:`Use functools.partial to pass keywords to the callback
157 <asyncio-pass-keywords>`.
158
Victor Stinnerea3183f2013-12-03 01:08:00 +0100159.. method:: BaseEventLoop.call_at(when, callback, *args)
160
161 Arrange for the *callback* to be called at the given absolute timestamp
Berker Peksagb5563992014-11-07 19:51:07 +0200162 *when* (an int or float), using the same time reference as
163 :meth:`BaseEventLoop.time`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100164
165 This method's behavior is the same as :meth:`call_later`.
166
Yury Selivanov1096f762015-06-25 13:49:52 -0400167 An instance of :class:`asyncio.Handle` is returned, which can be
168 used to cancel the callback.
169
Victor Stinner8464c242014-11-28 13:15:41 +0100170 :ref:`Use functools.partial to pass keywords to the callback
171 <asyncio-pass-keywords>`.
172
Victor Stinnerea3183f2013-12-03 01:08:00 +0100173.. method:: BaseEventLoop.time()
174
175 Return the current time, as a :class:`float` value, according to the
176 event loop's internal clock.
177
Victor Stinner3e09e322013-12-03 01:22:06 +0100178.. seealso::
179
180 The :func:`asyncio.sleep` function.
181
Victor Stinnerea3183f2013-12-03 01:08:00 +0100182
Yury Selivanov950204d2016-05-16 16:23:00 -0400183Futures
184-------
185
186.. method:: BaseEventLoop.create_future()
187
188 Create an :class:`asyncio.Future` object attached to the loop.
189
190 This is a preferred way to create futures in asyncio, as event
191 loop implementations can provide alternative implementations
192 of the Future class (with better performance or instrumentation).
193
194 .. versionadded:: 3.5.2
195
196
Yury Selivanovbb961342015-06-25 11:54:34 -0400197Tasks
198-----
Victor Stinner530ef2f2014-07-08 12:39:10 +0200199
200.. method:: BaseEventLoop.create_task(coro)
201
202 Schedule the execution of a :ref:`coroutine object <coroutine>`: wrap it in
203 a future. Return a :class:`Task` object.
204
205 Third-party event loops can use their own subclass of :class:`Task` for
206 interoperability. In this case, the result type is a subclass of
207 :class:`Task`.
208
Victor Stinner337e03f2014-08-11 01:11:13 +0200209 This method was added in Python 3.4.2. Use the :func:`async` function to
210 support also older Python versions.
Victor Stinner530ef2f2014-07-08 12:39:10 +0200211
212 .. versionadded:: 3.4.2
213
Yury Selivanov71854612015-05-11 16:28:27 -0400214.. method:: BaseEventLoop.set_task_factory(factory)
215
216 Set a task factory that will be used by
217 :meth:`BaseEventLoop.create_task`.
218
219 If *factory* is ``None`` the default task factory will be set.
220
221 If *factory* is a *callable*, it should have a signature matching
222 ``(loop, coro)``, where *loop* will be a reference to the active
223 event loop, *coro* will be a coroutine object. The callable
224 must return an :class:`asyncio.Future` compatible object.
225
226 .. versionadded:: 3.4.4
227
228.. method:: BaseEventLoop.get_task_factory()
229
230 Return a task factory, or ``None`` if the default one is in use.
231
232 .. versionadded:: 3.4.4
233
Victor Stinner530ef2f2014-07-08 12:39:10 +0200234
Victor Stinnerea3183f2013-12-03 01:08:00 +0100235Creating connections
Victor Stinner0c6f1ca2013-12-03 01:46:39 +0100236--------------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100237
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100238.. coroutinemethod:: BaseEventLoop.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 +0100239
240 Create a streaming transport connection to a given Internet *host* and
Victor Stinnera6919aa2014-02-19 13:32:34 +0100241 *port*: socket family :py:data:`~socket.AF_INET` or
242 :py:data:`~socket.AF_INET6` depending on *host* (or *family* if specified),
243 socket type :py:data:`~socket.SOCK_STREAM`. *protocol_factory* must be a
244 callable returning a :ref:`protocol <asyncio-protocol>` instance.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100245
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500246 This method is a :ref:`coroutine <coroutine>` which will try to
Victor Stinnerea3183f2013-12-03 01:08:00 +0100247 establish the connection in the background. When successful, the
248 coroutine returns a ``(transport, protocol)`` pair.
249
250 The chronological synopsis of the underlying operation is as follows:
251
Victor Stinner9592edb2014-02-02 15:03:02 +0100252 #. The connection is established, and a :ref:`transport <asyncio-transport>`
Victor Stinnerea3183f2013-12-03 01:08:00 +0100253 is created to represent it.
254
255 #. *protocol_factory* is called without arguments and must return a
Victor Stinner9592edb2014-02-02 15:03:02 +0100256 :ref:`protocol <asyncio-protocol>` instance.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100257
258 #. The protocol instance is tied to the transport, and its
259 :meth:`connection_made` method is called.
260
261 #. The coroutine returns successfully with the ``(transport, protocol)``
262 pair.
263
264 The created transport is an implementation-dependent bidirectional stream.
265
266 .. note::
267 *protocol_factory* can be any kind of callable, not necessarily
268 a class. For example, if you want to use a pre-created
269 protocol instance, you can pass ``lambda: my_protocol``.
270
Martin Panterc04fb562016-02-10 05:44:01 +0000271 Options that change how the connection is created:
Victor Stinnerea3183f2013-12-03 01:08:00 +0100272
273 * *ssl*: if given and not false, a SSL/TLS transport is created
274 (by default a plain TCP transport is created). If *ssl* is
275 a :class:`ssl.SSLContext` object, this context is used to create
276 the transport; if *ssl* is :const:`True`, a context with some
277 unspecified default settings is used.
278
Berker Peksag9c1dba22014-09-28 00:00:58 +0300279 .. seealso:: :ref:`SSL/TLS security considerations <ssl-security>`
Antoine Pitrouc5e075f2014-03-22 18:19:11 +0100280
Victor Stinnerea3183f2013-12-03 01:08:00 +0100281 * *server_hostname*, is only for use together with *ssl*,
282 and sets or overrides the hostname that the target server's certificate
283 will be matched against. By default the value of the *host* argument
284 is used. If *host* is empty, there is no default and you must pass a
285 value for *server_hostname*. If *server_hostname* is an empty
286 string, hostname matching is disabled (which is a serious security
287 risk, allowing for man-in-the-middle-attacks).
288
289 * *family*, *proto*, *flags* are the optional address family, protocol
290 and flags to be passed through to getaddrinfo() for *host* resolution.
291 If given, these should all be integers from the corresponding
292 :mod:`socket` module constants.
293
294 * *sock*, if given, should be an existing, already connected
295 :class:`socket.socket` object to be used by the transport.
296 If *sock* is given, none of *host*, *port*, *family*, *proto*, *flags*
297 and *local_addr* should be specified.
298
299 * *local_addr*, if given, is a ``(local_host, local_port)`` tuple used
300 to bind the socket to locally. The *local_host* and *local_port*
301 are looked up using getaddrinfo(), similarly to *host* and *port*.
302
Victor Stinner60208a12015-09-15 22:41:52 +0200303 .. versionchanged:: 3.5
304
305 On Windows with :class:`ProactorEventLoop`, SSL/TLS is now supported.
Victor Stinner41f3c3f2014-08-31 14:47:37 +0200306
Victor Stinnerc8ea8132014-01-23 11:02:09 +0100307 .. seealso::
308
309 The :func:`open_connection` function can be used to get a pair of
310 (:class:`StreamReader`, :class:`StreamWriter`) instead of a protocol.
311
Victor Stinnerea3183f2013-12-03 01:08:00 +0100312
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700313.. coroutinemethod:: BaseEventLoop.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 +0100314
315 Create datagram connection: socket family :py:data:`~socket.AF_INET` or
316 :py:data:`~socket.AF_INET6` depending on *host* (or *family* if specified),
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700317 socket type :py:data:`~socket.SOCK_DGRAM`. *protocol_factory* must be a
318 callable returning a :ref:`protocol <asyncio-protocol>` instance.
Victor Stinnera6919aa2014-02-19 13:32:34 +0100319
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500320 This method is a :ref:`coroutine <coroutine>` which will try to
Victor Stinnera6919aa2014-02-19 13:32:34 +0100321 establish the connection in the background. When successful, the
322 coroutine returns a ``(transport, protocol)`` pair.
323
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700324 Options changing how the connection is created:
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 :meth:`getaddrinfo`.
329
330 * *remote_addr*, if given, is a ``(remote_host, remote_port)`` tuple used
331 to connect the socket to a remote address. The *remote_host* and
332 *remote_port* are looked up using :meth:`getaddrinfo`.
333
334 * *family*, *proto*, *flags* are the optional address family, protocol
335 and flags to be passed through to :meth:`getaddrinfo` for *host*
336 resolution. If given, these should all be integers from the
337 corresponding :mod:`socket` module constants.
338
339 * *reuse_address* tells the kernel to reuse a local socket in
340 TIME_WAIT state, without waiting for its natural timeout to
341 expire. If not specified will automatically be set to True on
342 UNIX.
343
344 * *reuse_port* tells the kernel to allow this endpoint to be bound to the
345 same port as other existing endpoints are bound to, so long as they all
346 set this flag when being created. This option is not supported on Windows
347 and some UNIX's. If the :py:data:`~socket.SO_REUSEPORT` constant is not
348 defined then this capability is unsupported.
349
350 * *allow_broadcast* tells the kernel to allow this endpoint to send
351 messages to the broadcast address.
352
353 * *sock* can optionally be specified in order to use a preexisting,
354 already connected, :class:`socket.socket` object to be used by the
355 transport. If specified, *local_addr* and *remote_addr* should be omitted
356 (must be :const:`None`).
Victor Stinnera6919aa2014-02-19 13:32:34 +0100357
Victor Stinner41f3c3f2014-08-31 14:47:37 +0200358 On Windows with :class:`ProactorEventLoop`, this method is not supported.
359
Victor Stinnerc7edffd2014-10-12 11:24:26 +0200360 See :ref:`UDP echo client protocol <asyncio-udp-echo-client-protocol>` and
361 :ref:`UDP echo server protocol <asyncio-udp-echo-server-protocol>` examples.
362
Victor Stinnera6919aa2014-02-19 13:32:34 +0100363
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100364.. coroutinemethod:: BaseEventLoop.create_unix_connection(protocol_factory, path, \*, ssl=None, sock=None, server_hostname=None)
Victor Stinnera6919aa2014-02-19 13:32:34 +0100365
366 Create UNIX connection: socket family :py:data:`~socket.AF_UNIX`, socket
367 type :py:data:`~socket.SOCK_STREAM`. The :py:data:`~socket.AF_UNIX` socket
368 family is used to communicate between processes on the same machine
369 efficiently.
370
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500371 This method is a :ref:`coroutine <coroutine>` which will try to
Victor Stinnera6919aa2014-02-19 13:32:34 +0100372 establish the connection in the background. When successful, the
373 coroutine returns a ``(transport, protocol)`` pair.
374
375 See the :meth:`BaseEventLoop.create_connection` method for parameters.
376
377 Availability: UNIX.
378
379
Victor Stinnerea3183f2013-12-03 01:08:00 +0100380Creating listening connections
381------------------------------
382
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700383.. coroutinemethod:: BaseEventLoop.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 +0100384
Victor Stinner33f6abe2014-10-12 20:36:04 +0200385 Create a TCP server (socket type :data:`~socket.SOCK_STREAM`) bound to
386 *host* and *port*.
387
388 Return a :class:`Server` object, its :attr:`~Server.sockets` attribute
389 contains created sockets. Use the :meth:`Server.close` method to stop the
390 server: close listening sockets.
391
392 Parameters:
393
Victor Stinner5e4a7d82015-09-21 18:33:43 +0200394 * The *host* parameter can be a string, in that case the TCP server is
395 bound to *host* and *port*. The *host* parameter can also be a sequence
396 of strings and in that case the TCP server is bound to all hosts of the
397 sequence. If *host* is an empty string or ``None``, all interfaces are
398 assumed and a list of multiple sockets will be returned (most likely one
399 for IPv4 and another one for IPv6).
Victor Stinner33f6abe2014-10-12 20:36:04 +0200400
401 * *family* can be set to either :data:`socket.AF_INET` or
402 :data:`~socket.AF_INET6` to force the socket to use IPv4 or IPv6. If not set
403 it will be determined from host (defaults to :data:`socket.AF_UNSPEC`).
404
405 * *flags* is a bitmask for :meth:`getaddrinfo`.
406
407 * *sock* can optionally be specified in order to use a preexisting
408 socket object. If specified, *host* and *port* should be omitted (must be
409 :const:`None`).
410
411 * *backlog* is the maximum number of queued connections passed to
412 :meth:`~socket.socket.listen` (defaults to 100).
413
414 * *ssl* can be set to an :class:`~ssl.SSLContext` to enable SSL over the
415 accepted connections.
416
417 * *reuse_address* tells the kernel to reuse a local socket in
418 TIME_WAIT state, without waiting for its natural timeout to
419 expire. If not specified will automatically be set to True on
420 UNIX.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100421
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700422 * *reuse_port* tells the kernel to allow this endpoint to be bound to the
423 same port as other existing endpoints are bound to, so long as they all
424 set this flag when being created. This option is not supported on
425 Windows.
426
Victor Stinnerd1432092014-06-19 17:11:49 +0200427 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100428
Victor Stinner60208a12015-09-15 22:41:52 +0200429 .. versionchanged:: 3.5
430
431 On Windows with :class:`ProactorEventLoop`, SSL/TLS is now supported.
Victor Stinner41f3c3f2014-08-31 14:47:37 +0200432
Victor Stinnerc8ea8132014-01-23 11:02:09 +0100433 .. seealso::
434
435 The function :func:`start_server` creates a (:class:`StreamReader`,
436 :class:`StreamWriter`) pair and calls back a function with this pair.
437
Victor Stinner7b58a2b2015-09-21 18:41:05 +0200438 .. versionchanged:: 3.5.1
Victor Stinner5e4a7d82015-09-21 18:33:43 +0200439
440 The *host* parameter can now be a sequence of strings.
441
Victor Stinnerea3183f2013-12-03 01:08:00 +0100442
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100443.. coroutinemethod:: BaseEventLoop.create_unix_server(protocol_factory, path=None, \*, sock=None, backlog=100, ssl=None)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100444
Victor Stinnera6919aa2014-02-19 13:32:34 +0100445 Similar to :meth:`BaseEventLoop.create_server`, but specific to the
446 socket family :py:data:`~socket.AF_UNIX`.
447
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100448 This method is a :ref:`coroutine <coroutine>`.
449
Victor Stinnera6919aa2014-02-19 13:32:34 +0100450 Availability: UNIX.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100451
452
Victor Stinnerc1567df2014-02-08 23:22:58 +0100453Watch file descriptors
454----------------------
455
Victor Stinner41f3c3f2014-08-31 14:47:37 +0200456On Windows with :class:`SelectorEventLoop`, only socket handles are supported
457(ex: pipe file descriptors are not supported).
458
459On Windows with :class:`ProactorEventLoop`, these methods are not supported.
460
Victor Stinnerc1567df2014-02-08 23:22:58 +0100461.. method:: BaseEventLoop.add_reader(fd, callback, \*args)
462
463 Start watching the file descriptor for read availability and then call the
464 *callback* with specified arguments.
465
Victor Stinner8464c242014-11-28 13:15:41 +0100466 :ref:`Use functools.partial to pass keywords to the callback
467 <asyncio-pass-keywords>`.
468
Victor Stinnerc1567df2014-02-08 23:22:58 +0100469.. method:: BaseEventLoop.remove_reader(fd)
470
471 Stop watching the file descriptor for read availability.
472
473.. method:: BaseEventLoop.add_writer(fd, callback, \*args)
474
475 Start watching the file descriptor for write availability and then call the
476 *callback* with specified arguments.
477
Victor Stinner8464c242014-11-28 13:15:41 +0100478 :ref:`Use functools.partial to pass keywords to the callback
479 <asyncio-pass-keywords>`.
480
Victor Stinnerc1567df2014-02-08 23:22:58 +0100481.. method:: BaseEventLoop.remove_writer(fd)
482
483 Stop watching the file descriptor for write availability.
484
Victor Stinner04e6df32014-10-11 16:16:27 +0200485The :ref:`watch a file descriptor for read events <asyncio-watch-read-event>`
486example uses the low-level :meth:`BaseEventLoop.add_reader` method to register
487the file descriptor of a socket.
488
Victor Stinnerc1567df2014-02-08 23:22:58 +0100489
490Low-level socket operations
491---------------------------
492
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100493.. coroutinemethod:: BaseEventLoop.sock_recv(sock, nbytes)
Victor Stinnerc1567df2014-02-08 23:22:58 +0100494
Yury Selivanov55c50842016-06-08 12:48:15 -0400495 Receive data from the socket. Modeled after blocking
496 :meth:`socket.socket.recv` method.
497
498 The return value is a bytes object
Victor Stinnerc1567df2014-02-08 23:22:58 +0100499 representing the data received. The maximum amount of data to be received
500 at once is specified by *nbytes*.
501
Victor Stinnerd84fd732014-08-26 01:01:59 +0200502 With :class:`SelectorEventLoop` event loop, the socket *sock* must be
503 non-blocking.
Victor Stinnerec2ce092014-07-29 23:12:22 +0200504
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500505 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100506
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100507.. coroutinemethod:: BaseEventLoop.sock_sendall(sock, data)
Victor Stinnerc1567df2014-02-08 23:22:58 +0100508
Yury Selivanov55c50842016-06-08 12:48:15 -0400509 Send data to the socket. Modeled after blocking
510 :meth:`socket.socket.sendall` method.
511
512 The socket must be connected to a remote socket.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100513 This method continues to send data from *data* until either all data has
514 been sent or an error occurs. ``None`` is returned on success. On error,
515 an exception is raised, and there is no way to determine how much data, if
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500516 any, was successfully processed by the receiving end of the connection.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100517
Victor Stinnerd84fd732014-08-26 01:01:59 +0200518 With :class:`SelectorEventLoop` event loop, the socket *sock* must be
519 non-blocking.
Victor Stinnerec2ce092014-07-29 23:12:22 +0200520
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500521 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100522
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100523.. coroutinemethod:: BaseEventLoop.sock_connect(sock, address)
Victor Stinnerc1567df2014-02-08 23:22:58 +0100524
Yury Selivanov55c50842016-06-08 12:48:15 -0400525 Connect to a remote socket at *address*. Modeled after
526 blocking :meth:`socket.socket.connect` method.
Victor Stinner1b0580b2014-02-13 09:24:37 +0100527
Victor Stinnerd84fd732014-08-26 01:01:59 +0200528 With :class:`SelectorEventLoop` event loop, the socket *sock* must be
529 non-blocking.
Victor Stinnerec2ce092014-07-29 23:12:22 +0200530
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500531 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100532
Yury Selivanov55c50842016-06-08 12:48:15 -0400533 .. versionchanged:: 3.5.2
534 ``address`` no longer needs to be resolved. ``sock_connect``
535 will try to check if the *address* is already resolved by calling
536 :func:`socket.inet_pton`. If not,
537 :meth:`BaseEventLoop.getaddrinfo` will be used to resolve the
538 *address*.
539
Victor Stinnerc1567df2014-02-08 23:22:58 +0100540 .. seealso::
541
Yury Selivanov55c50842016-06-08 12:48:15 -0400542 :meth:`BaseEventLoop.create_connection`
543 and :func:`asyncio.open_connection() <open_connection>`.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100544
545
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100546.. coroutinemethod:: BaseEventLoop.sock_accept(sock)
Victor Stinnerc1567df2014-02-08 23:22:58 +0100547
Yury Selivanov55c50842016-06-08 12:48:15 -0400548 Accept a connection. Modeled after blocking
549 :meth:`socket.socket.accept`.
550
551 The socket must be bound to an address and listening
Victor Stinnerc1567df2014-02-08 23:22:58 +0100552 for connections. The return value is a pair ``(conn, address)`` where *conn*
553 is a *new* socket object usable to send and receive data on the connection,
554 and *address* is the address bound to the socket on the other end of the
555 connection.
556
Victor Stinnerec2ce092014-07-29 23:12:22 +0200557 The socket *sock* must be non-blocking.
558
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500559 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100560
561 .. seealso::
562
Yury Selivanov55c50842016-06-08 12:48:15 -0400563 :meth:`BaseEventLoop.create_server` and :func:`start_server`.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100564
565
566Resolve host name
567-----------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100568
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100569.. coroutinemethod:: BaseEventLoop.getaddrinfo(host, port, \*, family=0, type=0, proto=0, flags=0)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100570
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500571 This method is a :ref:`coroutine <coroutine>`, similar to
572 :meth:`socket.getaddrinfo` function but non-blocking.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100573
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100574.. coroutinemethod:: BaseEventLoop.getnameinfo(sockaddr, flags=0)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100575
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500576 This method is a :ref:`coroutine <coroutine>`, similar to
577 :meth:`socket.getnameinfo` function but non-blocking.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100578
579
Victor Stinner984600f2014-03-25 09:40:26 +0100580Connect pipes
581-------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100582
Victor Stinner41f3c3f2014-08-31 14:47:37 +0200583On Windows with :class:`SelectorEventLoop`, these methods are not supported.
584Use :class:`ProactorEventLoop` to support pipes on Windows.
585
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100586.. coroutinemethod:: BaseEventLoop.connect_read_pipe(protocol_factory, pipe)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100587
Victor Stinnerd84fd732014-08-26 01:01:59 +0200588 Register read pipe in eventloop.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100589
590 *protocol_factory* should instantiate object with :class:`Protocol`
Victor Stinnera5b257a2014-05-29 00:14:03 +0200591 interface. *pipe* is a :term:`file-like object <file object>`.
592 Return pair ``(transport, protocol)``, where *transport* supports the
Victor Stinnerea3183f2013-12-03 01:08:00 +0100593 :class:`ReadTransport` interface.
594
Victor Stinnerd84fd732014-08-26 01:01:59 +0200595 With :class:`SelectorEventLoop` event loop, the *pipe* is set to
596 non-blocking mode.
597
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500598 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100599
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100600.. coroutinemethod:: BaseEventLoop.connect_write_pipe(protocol_factory, pipe)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100601
602 Register write pipe in eventloop.
603
604 *protocol_factory* should instantiate object with :class:`BaseProtocol`
Victor Stinner2cef3002014-10-23 22:38:46 +0200605 interface. *pipe* is :term:`file-like object <file object>`.
606 Return pair ``(transport, protocol)``, where *transport* supports
Victor Stinnerea3183f2013-12-03 01:08:00 +0100607 :class:`WriteTransport` interface.
608
Victor Stinnerd84fd732014-08-26 01:01:59 +0200609 With :class:`SelectorEventLoop` event loop, the *pipe* is set to
610 non-blocking mode.
611
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500612 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100613
Victor Stinner08444382014-02-02 22:43:39 +0100614.. seealso::
615
Victor Stinner984600f2014-03-25 09:40:26 +0100616 The :meth:`BaseEventLoop.subprocess_exec` and
617 :meth:`BaseEventLoop.subprocess_shell` methods.
Victor Stinner08444382014-02-02 22:43:39 +0100618
Victor Stinnerea3183f2013-12-03 01:08:00 +0100619
Victor Stinner8b863482014-01-27 10:07:50 +0100620UNIX signals
621------------
622
623Availability: UNIX only.
624
625.. method:: BaseEventLoop.add_signal_handler(signum, callback, \*args)
626
627 Add a handler for a signal.
628
629 Raise :exc:`ValueError` if the signal number is invalid or uncatchable.
630 Raise :exc:`RuntimeError` if there is a problem setting up the handler.
631
Victor Stinner8464c242014-11-28 13:15:41 +0100632 :ref:`Use functools.partial to pass keywords to the callback
633 <asyncio-pass-keywords>`.
634
Victor Stinner8b863482014-01-27 10:07:50 +0100635.. method:: BaseEventLoop.remove_signal_handler(sig)
636
637 Remove a handler for a signal.
638
639 Return ``True`` if a signal handler was removed, ``False`` if not.
640
641.. seealso::
642
643 The :mod:`signal` module.
644
645
Victor Stinnerea3183f2013-12-03 01:08:00 +0100646Executor
647--------
648
649Call a function in an :class:`~concurrent.futures.Executor` (pool of threads or
650pool of processes). By default, an event loop uses a thread pool executor
651(:class:`~concurrent.futures.ThreadPoolExecutor`).
652
Andrew Svetlov1c62b522015-10-01 09:48:08 +0300653.. coroutinemethod:: BaseEventLoop.run_in_executor(executor, func, \*args)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100654
Andrew Svetlov1c62b522015-10-01 09:48:08 +0300655 Arrange for a *func* to be called in the specified executor.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100656
Larry Hastings3732ed22014-03-15 21:13:56 -0700657 The *executor* argument should be an :class:`~concurrent.futures.Executor`
658 instance. The default executor is used if *executor* is ``None``.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100659
Andrew Svetlov1c62b522015-10-01 09:48:08 +0300660 :ref:`Use functools.partial to pass keywords to the *func*
Victor Stinner8464c242014-11-28 13:15:41 +0100661 <asyncio-pass-keywords>`.
662
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500663 This method is a :ref:`coroutine <coroutine>`.
664
Victor Stinnerea3183f2013-12-03 01:08:00 +0100665.. method:: BaseEventLoop.set_default_executor(executor)
666
667 Set the default executor used by :meth:`run_in_executor`.
668
669
Yury Selivanov43ee1c12014-02-19 20:58:44 -0500670Error Handling API
671------------------
672
Martin Panterc04fb562016-02-10 05:44:01 +0000673Allows customizing how exceptions are handled in the event loop.
Yury Selivanov43ee1c12014-02-19 20:58:44 -0500674
675.. method:: BaseEventLoop.set_exception_handler(handler)
676
677 Set *handler* as the new event loop exception handler.
678
679 If *handler* is ``None``, the default exception handler will
680 be set.
681
682 If *handler* is a callable object, it should have a
683 matching signature to ``(loop, context)``, where ``loop``
684 will be a reference to the active event loop, ``context``
685 will be a ``dict`` object (see :meth:`call_exception_handler`
686 documentation for details about context).
687
Yury Selivanov950204d2016-05-16 16:23:00 -0400688.. method:: BaseEventLoop.get_exception_handler()
689
690 Return the exception handler, or ``None`` if the default one
691 is in use.
692
693 .. versionadded:: 3.5.2
694
Yury Selivanov43ee1c12014-02-19 20:58:44 -0500695.. method:: BaseEventLoop.default_exception_handler(context)
696
697 Default exception handler.
698
699 This is called when an exception occurs and no exception
700 handler is set, and can be called by a custom exception
701 handler that wants to defer to the default behavior.
702
703 *context* parameter has the same meaning as in
704 :meth:`call_exception_handler`.
705
706.. method:: BaseEventLoop.call_exception_handler(context)
707
708 Call the current event loop exception handler.
709
710 *context* is a ``dict`` object containing the following keys
711 (new keys may be introduced later):
712
713 * 'message': Error message;
714 * 'exception' (optional): Exception object;
715 * 'future' (optional): :class:`asyncio.Future` instance;
716 * 'handle' (optional): :class:`asyncio.Handle` instance;
717 * 'protocol' (optional): :ref:`Protocol <asyncio-protocol>` instance;
718 * 'transport' (optional): :ref:`Transport <asyncio-transport>` instance;
719 * 'socket' (optional): :class:`socket.socket` instance.
720
721 .. note::
722
723 Note: this method should not be overloaded in subclassed
724 event loops. For any custom exception handling, use
725 :meth:`set_exception_handler()` method.
726
Victor Stinner0f3e6bc2014-02-19 23:15:02 +0100727Debug mode
728----------
729
730.. method:: BaseEventLoop.get_debug()
731
Victor Stinner7b7120e2014-06-23 00:12:14 +0200732 Get the debug mode (:class:`bool`) of the event loop.
733
734 The default value is ``True`` if the environment variable
735 :envvar:`PYTHONASYNCIODEBUG` is set to a non-empty string, ``False``
736 otherwise.
Victor Stinner0f3e6bc2014-02-19 23:15:02 +0100737
Victor Stinner64d750b2014-06-18 03:25:23 +0200738 .. versionadded:: 3.4.2
739
Victor Stinner0f3e6bc2014-02-19 23:15:02 +0100740.. method:: BaseEventLoop.set_debug(enabled: bool)
741
742 Set the debug mode of the event loop.
743
Victor Stinner64d750b2014-06-18 03:25:23 +0200744 .. versionadded:: 3.4.2
745
Victor Stinner0f3e6bc2014-02-19 23:15:02 +0100746.. seealso::
747
Victor Stinner62511fd2014-06-23 00:36:11 +0200748 The :ref:`debug mode of asyncio <asyncio-debug-mode>`.
Victor Stinner0f3e6bc2014-02-19 23:15:02 +0100749
Victor Stinner8c462c52014-01-24 18:11:43 +0100750Server
751------
752
Victor Stinner8ebeb032014-07-11 23:47:40 +0200753.. class:: Server
Victor Stinner8c462c52014-01-24 18:11:43 +0100754
Victor Stinner8ebeb032014-07-11 23:47:40 +0200755 Server listening on sockets.
756
757 Object created by the :meth:`BaseEventLoop.create_server` method and the
R David Murray756f0b12015-01-29 19:53:33 -0500758 :func:`start_server` function. Don't instantiate the class directly.
Victor Stinner8c462c52014-01-24 18:11:43 +0100759
760 .. method:: close()
761
Victor Stinner4bfb14a2014-07-12 03:20:24 +0200762 Stop serving: close listening sockets and set the :attr:`sockets`
763 attribute to ``None``.
764
Berker Peksag49c9edf2016-01-20 07:14:22 +0200765 The sockets that represent existing incoming client connections are left
766 open.
Victor Stinner8ebeb032014-07-11 23:47:40 +0200767
Berker Peksag49c9edf2016-01-20 07:14:22 +0200768 The server is closed asynchronously, use the :meth:`wait_closed`
769 coroutine to wait until the server is closed.
Victor Stinner8c462c52014-01-24 18:11:43 +0100770
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100771 .. coroutinemethod:: wait_closed()
Victor Stinner8c462c52014-01-24 18:11:43 +0100772
Victor Stinner8ebeb032014-07-11 23:47:40 +0200773 Wait until the :meth:`close` method completes.
774
775 This method is a :ref:`coroutine <coroutine>`.
776
777 .. attribute:: sockets
778
779 List of :class:`socket.socket` objects the server is listening to, or
780 ``None`` if the server is closed.
Victor Stinner8c462c52014-01-24 18:11:43 +0100781
782
Yury Selivanov43ee1c12014-02-19 20:58:44 -0500783Handle
784------
785
786.. class:: Handle
787
788 A callback wrapper object returned by :func:`BaseEventLoop.call_soon`,
789 :func:`BaseEventLoop.call_soon_threadsafe`, :func:`BaseEventLoop.call_later`,
790 and :func:`BaseEventLoop.call_at`.
791
792 .. method:: cancel()
793
Yury Selivanov1096f762015-06-25 13:49:52 -0400794 Cancel the call. If the callback is already canceled or executed,
795 this method has no effect.
Victor Stinneraea82292014-07-08 23:42:38 +0200796
Yury Selivanov43ee1c12014-02-19 20:58:44 -0500797
Victor Stinner6888b962014-10-11 16:15:58 +0200798Event loop examples
Victor Stinnera092a612015-01-09 15:58:41 +0100799-------------------
Yury Selivanov43ee1c12014-02-19 20:58:44 -0500800
Victor Stinner3e09e322013-12-03 01:22:06 +0100801.. _asyncio-hello-world-callback:
Victor Stinnerea3183f2013-12-03 01:08:00 +0100802
Victor Stinner7f314ed2014-10-15 18:49:16 +0200803Hello World with call_soon()
Victor Stinnera092a612015-01-09 15:58:41 +0100804^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Victor Stinnerea3183f2013-12-03 01:08:00 +0100805
Victor Stinner7f314ed2014-10-15 18:49:16 +0200806Example using the :meth:`BaseEventLoop.call_soon` method to schedule a
807callback. The callback displays ``"Hello World"`` and then stops the event
808loop::
Victor Stinnerea3183f2013-12-03 01:08:00 +0100809
810 import asyncio
811
Victor Stinner7f314ed2014-10-15 18:49:16 +0200812 def hello_world(loop):
Victor Stinnerea3183f2013-12-03 01:08:00 +0100813 print('Hello World')
Victor Stinner7f314ed2014-10-15 18:49:16 +0200814 loop.stop()
Victor Stinnerea3183f2013-12-03 01:08:00 +0100815
816 loop = asyncio.get_event_loop()
Victor Stinner7f314ed2014-10-15 18:49:16 +0200817
818 # Schedule a call to hello_world()
819 loop.call_soon(hello_world, loop)
820
821 # Blocking call interrupted by loop.stop()
822 loop.run_forever()
823 loop.close()
Victor Stinnerea3183f2013-12-03 01:08:00 +0100824
Victor Stinner3e09e322013-12-03 01:22:06 +0100825.. seealso::
Victor Stinnerea3183f2013-12-03 01:08:00 +0100826
Victor Stinner6888b962014-10-11 16:15:58 +0200827 The :ref:`Hello World coroutine <asyncio-hello-world-coroutine>` example
828 uses a :ref:`coroutine <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100829
Victor Stinner8b863482014-01-27 10:07:50 +0100830
Victor Stinner7f314ed2014-10-15 18:49:16 +0200831.. _asyncio-date-callback:
832
833Display the current date with call_later()
Victor Stinnera092a612015-01-09 15:58:41 +0100834^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Victor Stinner7f314ed2014-10-15 18:49:16 +0200835
836Example of callback displaying the current date every second. The callback uses
837the :meth:`BaseEventLoop.call_later` method to reschedule itself during 5
838seconds, and then stops the event loop::
839
840 import asyncio
841 import datetime
842
843 def display_date(end_time, loop):
844 print(datetime.datetime.now())
845 if (loop.time() + 1.0) < end_time:
846 loop.call_later(1, display_date, end_time, loop)
847 else:
848 loop.stop()
849
850 loop = asyncio.get_event_loop()
851
852 # Schedule the first call to display_date()
853 end_time = loop.time() + 5.0
854 loop.call_soon(display_date, end_time, loop)
855
856 # Blocking call interrupted by loop.stop()
857 loop.run_forever()
858 loop.close()
859
860.. seealso::
861
862 The :ref:`coroutine displaying the current date
863 <asyncio-date-coroutine>` example uses a :ref:`coroutine
864 <coroutine>`.
865
866
Victor Stinner04e6df32014-10-11 16:16:27 +0200867.. _asyncio-watch-read-event:
Victor Stinner8b863482014-01-27 10:07:50 +0100868
Victor Stinner04e6df32014-10-11 16:16:27 +0200869Watch a file descriptor for read events
Victor Stinnera092a612015-01-09 15:58:41 +0100870^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Victor Stinner04e6df32014-10-11 16:16:27 +0200871
872Wait until a file descriptor received some data using the
873:meth:`BaseEventLoop.add_reader` method and then close the event loop::
874
875 import asyncio
Victor Stinnerccd8e342014-10-11 16:30:02 +0200876 try:
877 from socket import socketpair
878 except ImportError:
879 from asyncio.windows_utils import socketpair
Victor Stinner04e6df32014-10-11 16:16:27 +0200880
881 # Create a pair of connected file descriptors
Victor Stinnerccd8e342014-10-11 16:30:02 +0200882 rsock, wsock = socketpair()
Victor Stinner04e6df32014-10-11 16:16:27 +0200883 loop = asyncio.get_event_loop()
884
885 def reader():
886 data = rsock.recv(100)
887 print("Received:", data.decode())
Victor Stinner2cef3002014-10-23 22:38:46 +0200888 # We are done: unregister the file descriptor
Victor Stinner04e6df32014-10-11 16:16:27 +0200889 loop.remove_reader(rsock)
890 # Stop the event loop
891 loop.stop()
892
Victor Stinner2cef3002014-10-23 22:38:46 +0200893 # Register the file descriptor for read event
Victor Stinner04e6df32014-10-11 16:16:27 +0200894 loop.add_reader(rsock, reader)
895
896 # Simulate the reception of data from the network
897 loop.call_soon(wsock.send, 'abc'.encode())
898
899 # Run the event loop
900 loop.run_forever()
901
902 # We are done, close sockets and the event loop
903 rsock.close()
904 wsock.close()
905 loop.close()
906
907.. seealso::
908
909 The :ref:`register an open socket to wait for data using a protocol
910 <asyncio-register-socket>` example uses a low-level protocol created by the
911 :meth:`BaseEventLoop.create_connection` method.
912
913 The :ref:`register an open socket to wait for data using streams
914 <asyncio-register-socket-streams>` example uses high-level streams
915 created by the :func:`open_connection` function in a coroutine.
916
917
918Set signal handlers for SIGINT and SIGTERM
Victor Stinnera092a612015-01-09 15:58:41 +0100919^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Victor Stinner04e6df32014-10-11 16:16:27 +0200920
921Register handlers for signals :py:data:`SIGINT` and :py:data:`SIGTERM` using
922the :meth:`BaseEventLoop.add_signal_handler` method::
Victor Stinner8b863482014-01-27 10:07:50 +0100923
924 import asyncio
925 import functools
926 import os
927 import signal
928
929 def ask_exit(signame):
930 print("got signal %s: exit" % signame)
931 loop.stop()
932
933 loop = asyncio.get_event_loop()
934 for signame in ('SIGINT', 'SIGTERM'):
935 loop.add_signal_handler(getattr(signal, signame),
936 functools.partial(ask_exit, signame))
937
Serhiy Storchaka0424eaf2015-09-12 17:45:25 +0300938 print("Event loop running forever, press Ctrl+C to interrupt.")
Victor Stinner8b863482014-01-27 10:07:50 +0100939 print("pid %s: send SIGINT or SIGTERM to exit." % os.getpid())
Victor Stinner63b21a82014-07-05 15:38:59 +0200940 try:
941 loop.run_forever()
942 finally:
943 loop.close()
Victor Stinner2cef3002014-10-23 22:38:46 +0200944
945This example only works on UNIX.