blob: f68b19d8676e5b3fa2770eea234c54e3896089bc [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
104 This operates as a FIFO queue, callbacks are called in the order in
105 which they are registered. Each callback will be called exactly once.
106
107 Any positional arguments after the callback will be passed to the
108 callback when it is called.
109
Yury Selivanov1096f762015-06-25 13:49:52 -0400110 An instance of :class:`asyncio.Handle` is returned, which can be
111 used to cancel the callback.
Yury Selivanov43ee1c12014-02-19 20:58:44 -0500112
Victor Stinner8464c242014-11-28 13:15:41 +0100113 :ref:`Use functools.partial to pass keywords to the callback
114 <asyncio-pass-keywords>`.
115
Victor Stinnerea3183f2013-12-03 01:08:00 +0100116.. method:: BaseEventLoop.call_soon_threadsafe(callback, \*args)
117
118 Like :meth:`call_soon`, but thread safe.
119
Victor Stinner83704962015-02-25 14:24:15 +0100120 See the :ref:`concurrency and multithreading <asyncio-multithreading>`
121 section of the documentation.
122
Victor Stinnerea3183f2013-12-03 01:08:00 +0100123
Victor Stinner45b27ed2014-02-01 02:36:43 +0100124.. _asyncio-delayed-calls:
125
Victor Stinnerea3183f2013-12-03 01:08:00 +0100126Delayed calls
127-------------
128
129The event loop has its own internal clock for computing timeouts.
130Which clock is used depends on the (platform-specific) event loop
131implementation; ideally it is a monotonic clock. This will generally be
132a different clock than :func:`time.time`.
133
Victor Stinnerfd9d3742014-02-18 09:37:43 +0100134.. note::
135
136 Timeouts (relative *delay* or absolute *when*) should not exceed one day.
137
Victor Stinner45b27ed2014-02-01 02:36:43 +0100138
Victor Stinnerea3183f2013-12-03 01:08:00 +0100139.. method:: BaseEventLoop.call_later(delay, callback, *args)
140
141 Arrange for the *callback* to be called after the given *delay*
142 seconds (either an int or float).
143
Yury Selivanov1096f762015-06-25 13:49:52 -0400144 An instance of :class:`asyncio.Handle` is returned, which can be
145 used to cancel the callback.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100146
147 *callback* will be called exactly once per call to :meth:`call_later`.
148 If two callbacks are scheduled for exactly the same time, it is
149 undefined which will be called first.
150
151 The optional positional *args* will be passed to the callback when it
152 is called. If you want the callback to be called with some named
153 arguments, use a closure or :func:`functools.partial`.
154
Victor Stinner8464c242014-11-28 13:15:41 +0100155 :ref:`Use functools.partial to pass keywords to the callback
156 <asyncio-pass-keywords>`.
157
Victor Stinnerea3183f2013-12-03 01:08:00 +0100158.. method:: BaseEventLoop.call_at(when, callback, *args)
159
160 Arrange for the *callback* to be called at the given absolute timestamp
Berker Peksagb5563992014-11-07 19:51:07 +0200161 *when* (an int or float), using the same time reference as
162 :meth:`BaseEventLoop.time`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100163
164 This method's behavior is the same as :meth:`call_later`.
165
Yury Selivanov1096f762015-06-25 13:49:52 -0400166 An instance of :class:`asyncio.Handle` is returned, which can be
167 used to cancel the callback.
168
Victor Stinner8464c242014-11-28 13:15:41 +0100169 :ref:`Use functools.partial to pass keywords to the callback
170 <asyncio-pass-keywords>`.
171
Victor Stinnerea3183f2013-12-03 01:08:00 +0100172.. method:: BaseEventLoop.time()
173
174 Return the current time, as a :class:`float` value, according to the
175 event loop's internal clock.
176
Victor Stinner3e09e322013-12-03 01:22:06 +0100177.. seealso::
178
179 The :func:`asyncio.sleep` function.
180
Victor Stinnerea3183f2013-12-03 01:08:00 +0100181
Yury Selivanovbb961342015-06-25 11:54:34 -0400182Tasks
183-----
Victor Stinner530ef2f2014-07-08 12:39:10 +0200184
185.. method:: BaseEventLoop.create_task(coro)
186
187 Schedule the execution of a :ref:`coroutine object <coroutine>`: wrap it in
188 a future. Return a :class:`Task` object.
189
190 Third-party event loops can use their own subclass of :class:`Task` for
191 interoperability. In this case, the result type is a subclass of
192 :class:`Task`.
193
Victor Stinner337e03f2014-08-11 01:11:13 +0200194 This method was added in Python 3.4.2. Use the :func:`async` function to
195 support also older Python versions.
Victor Stinner530ef2f2014-07-08 12:39:10 +0200196
197 .. versionadded:: 3.4.2
198
Yury Selivanov71854612015-05-11 16:28:27 -0400199.. method:: BaseEventLoop.set_task_factory(factory)
200
201 Set a task factory that will be used by
202 :meth:`BaseEventLoop.create_task`.
203
204 If *factory* is ``None`` the default task factory will be set.
205
206 If *factory* is a *callable*, it should have a signature matching
207 ``(loop, coro)``, where *loop* will be a reference to the active
208 event loop, *coro* will be a coroutine object. The callable
209 must return an :class:`asyncio.Future` compatible object.
210
211 .. versionadded:: 3.4.4
212
213.. method:: BaseEventLoop.get_task_factory()
214
215 Return a task factory, or ``None`` if the default one is in use.
216
217 .. versionadded:: 3.4.4
218
Victor Stinner530ef2f2014-07-08 12:39:10 +0200219
Victor Stinnerea3183f2013-12-03 01:08:00 +0100220Creating connections
Victor Stinner0c6f1ca2013-12-03 01:46:39 +0100221--------------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100222
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100223.. 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 +0100224
225 Create a streaming transport connection to a given Internet *host* and
Victor Stinnera6919aa2014-02-19 13:32:34 +0100226 *port*: socket family :py:data:`~socket.AF_INET` or
227 :py:data:`~socket.AF_INET6` depending on *host* (or *family* if specified),
228 socket type :py:data:`~socket.SOCK_STREAM`. *protocol_factory* must be a
229 callable returning a :ref:`protocol <asyncio-protocol>` instance.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100230
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500231 This method is a :ref:`coroutine <coroutine>` which will try to
Victor Stinnerea3183f2013-12-03 01:08:00 +0100232 establish the connection in the background. When successful, the
233 coroutine returns a ``(transport, protocol)`` pair.
234
235 The chronological synopsis of the underlying operation is as follows:
236
Victor Stinner9592edb2014-02-02 15:03:02 +0100237 #. The connection is established, and a :ref:`transport <asyncio-transport>`
Victor Stinnerea3183f2013-12-03 01:08:00 +0100238 is created to represent it.
239
240 #. *protocol_factory* is called without arguments and must return a
Victor Stinner9592edb2014-02-02 15:03:02 +0100241 :ref:`protocol <asyncio-protocol>` instance.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100242
243 #. The protocol instance is tied to the transport, and its
244 :meth:`connection_made` method is called.
245
246 #. The coroutine returns successfully with the ``(transport, protocol)``
247 pair.
248
249 The created transport is an implementation-dependent bidirectional stream.
250
251 .. note::
252 *protocol_factory* can be any kind of callable, not necessarily
253 a class. For example, if you want to use a pre-created
254 protocol instance, you can pass ``lambda: my_protocol``.
255
Martin Panterc04fb562016-02-10 05:44:01 +0000256 Options that change how the connection is created:
Victor Stinnerea3183f2013-12-03 01:08:00 +0100257
258 * *ssl*: if given and not false, a SSL/TLS transport is created
259 (by default a plain TCP transport is created). If *ssl* is
260 a :class:`ssl.SSLContext` object, this context is used to create
261 the transport; if *ssl* is :const:`True`, a context with some
262 unspecified default settings is used.
263
Berker Peksag9c1dba22014-09-28 00:00:58 +0300264 .. seealso:: :ref:`SSL/TLS security considerations <ssl-security>`
Antoine Pitrouc5e075f2014-03-22 18:19:11 +0100265
Victor Stinnerea3183f2013-12-03 01:08:00 +0100266 * *server_hostname*, is only for use together with *ssl*,
267 and sets or overrides the hostname that the target server's certificate
268 will be matched against. By default the value of the *host* argument
269 is used. If *host* is empty, there is no default and you must pass a
270 value for *server_hostname*. If *server_hostname* is an empty
271 string, hostname matching is disabled (which is a serious security
272 risk, allowing for man-in-the-middle-attacks).
273
274 * *family*, *proto*, *flags* are the optional address family, protocol
275 and flags to be passed through to getaddrinfo() for *host* resolution.
276 If given, these should all be integers from the corresponding
277 :mod:`socket` module constants.
278
279 * *sock*, if given, should be an existing, already connected
280 :class:`socket.socket` object to be used by the transport.
281 If *sock* is given, none of *host*, *port*, *family*, *proto*, *flags*
282 and *local_addr* should be specified.
283
284 * *local_addr*, if given, is a ``(local_host, local_port)`` tuple used
285 to bind the socket to locally. The *local_host* and *local_port*
286 are looked up using getaddrinfo(), similarly to *host* and *port*.
287
Victor Stinner60208a12015-09-15 22:41:52 +0200288 .. versionchanged:: 3.5
289
290 On Windows with :class:`ProactorEventLoop`, SSL/TLS is now supported.
Victor Stinner41f3c3f2014-08-31 14:47:37 +0200291
Victor Stinnerc8ea8132014-01-23 11:02:09 +0100292 .. seealso::
293
294 The :func:`open_connection` function can be used to get a pair of
295 (:class:`StreamReader`, :class:`StreamWriter`) instead of a protocol.
296
Victor Stinnerea3183f2013-12-03 01:08:00 +0100297
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700298.. 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 +0100299
300 Create datagram connection: socket family :py:data:`~socket.AF_INET` or
301 :py:data:`~socket.AF_INET6` depending on *host* (or *family* if specified),
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700302 socket type :py:data:`~socket.SOCK_DGRAM`. *protocol_factory* must be a
303 callable returning a :ref:`protocol <asyncio-protocol>` instance.
Victor Stinnera6919aa2014-02-19 13:32:34 +0100304
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500305 This method is a :ref:`coroutine <coroutine>` which will try to
Victor Stinnera6919aa2014-02-19 13:32:34 +0100306 establish the connection in the background. When successful, the
307 coroutine returns a ``(transport, protocol)`` pair.
308
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700309 Options changing how the connection is created:
310
311 * *local_addr*, if given, is a ``(local_host, local_port)`` tuple used
312 to bind the socket to locally. The *local_host* and *local_port*
313 are looked up using :meth:`getaddrinfo`.
314
315 * *remote_addr*, if given, is a ``(remote_host, remote_port)`` tuple used
316 to connect the socket to a remote address. The *remote_host* and
317 *remote_port* are looked up using :meth:`getaddrinfo`.
318
319 * *family*, *proto*, *flags* are the optional address family, protocol
320 and flags to be passed through to :meth:`getaddrinfo` for *host*
321 resolution. If given, these should all be integers from the
322 corresponding :mod:`socket` module constants.
323
324 * *reuse_address* tells the kernel to reuse a local socket in
325 TIME_WAIT state, without waiting for its natural timeout to
326 expire. If not specified will automatically be set to True on
327 UNIX.
328
329 * *reuse_port* tells the kernel to allow this endpoint to be bound to the
330 same port as other existing endpoints are bound to, so long as they all
331 set this flag when being created. This option is not supported on Windows
332 and some UNIX's. If the :py:data:`~socket.SO_REUSEPORT` constant is not
333 defined then this capability is unsupported.
334
335 * *allow_broadcast* tells the kernel to allow this endpoint to send
336 messages to the broadcast address.
337
338 * *sock* can optionally be specified in order to use a preexisting,
339 already connected, :class:`socket.socket` object to be used by the
340 transport. If specified, *local_addr* and *remote_addr* should be omitted
341 (must be :const:`None`).
Victor Stinnera6919aa2014-02-19 13:32:34 +0100342
Victor Stinner41f3c3f2014-08-31 14:47:37 +0200343 On Windows with :class:`ProactorEventLoop`, this method is not supported.
344
Victor Stinnerc7edffd2014-10-12 11:24:26 +0200345 See :ref:`UDP echo client protocol <asyncio-udp-echo-client-protocol>` and
346 :ref:`UDP echo server protocol <asyncio-udp-echo-server-protocol>` examples.
347
Victor Stinnera6919aa2014-02-19 13:32:34 +0100348
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100349.. coroutinemethod:: BaseEventLoop.create_unix_connection(protocol_factory, path, \*, ssl=None, sock=None, server_hostname=None)
Victor Stinnera6919aa2014-02-19 13:32:34 +0100350
351 Create UNIX connection: socket family :py:data:`~socket.AF_UNIX`, socket
352 type :py:data:`~socket.SOCK_STREAM`. The :py:data:`~socket.AF_UNIX` socket
353 family is used to communicate between processes on the same machine
354 efficiently.
355
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500356 This method is a :ref:`coroutine <coroutine>` which will try to
Victor Stinnera6919aa2014-02-19 13:32:34 +0100357 establish the connection in the background. When successful, the
358 coroutine returns a ``(transport, protocol)`` pair.
359
360 See the :meth:`BaseEventLoop.create_connection` method for parameters.
361
362 Availability: UNIX.
363
364
Victor Stinnerea3183f2013-12-03 01:08:00 +0100365Creating listening connections
366------------------------------
367
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700368.. 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 +0100369
Victor Stinner33f6abe2014-10-12 20:36:04 +0200370 Create a TCP server (socket type :data:`~socket.SOCK_STREAM`) bound to
371 *host* and *port*.
372
373 Return a :class:`Server` object, its :attr:`~Server.sockets` attribute
374 contains created sockets. Use the :meth:`Server.close` method to stop the
375 server: close listening sockets.
376
377 Parameters:
378
Victor Stinner5e4a7d82015-09-21 18:33:43 +0200379 * The *host* parameter can be a string, in that case the TCP server is
380 bound to *host* and *port*. The *host* parameter can also be a sequence
381 of strings and in that case the TCP server is bound to all hosts of the
382 sequence. If *host* is an empty string or ``None``, all interfaces are
383 assumed and a list of multiple sockets will be returned (most likely one
384 for IPv4 and another one for IPv6).
Victor Stinner33f6abe2014-10-12 20:36:04 +0200385
386 * *family* can be set to either :data:`socket.AF_INET` or
387 :data:`~socket.AF_INET6` to force the socket to use IPv4 or IPv6. If not set
388 it will be determined from host (defaults to :data:`socket.AF_UNSPEC`).
389
390 * *flags* is a bitmask for :meth:`getaddrinfo`.
391
392 * *sock* can optionally be specified in order to use a preexisting
393 socket object. If specified, *host* and *port* should be omitted (must be
394 :const:`None`).
395
396 * *backlog* is the maximum number of queued connections passed to
397 :meth:`~socket.socket.listen` (defaults to 100).
398
399 * *ssl* can be set to an :class:`~ssl.SSLContext` to enable SSL over the
400 accepted connections.
401
402 * *reuse_address* tells the kernel to reuse a local socket in
403 TIME_WAIT state, without waiting for its natural timeout to
404 expire. If not specified will automatically be set to True on
405 UNIX.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100406
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700407 * *reuse_port* tells the kernel to allow this endpoint to be bound to the
408 same port as other existing endpoints are bound to, so long as they all
409 set this flag when being created. This option is not supported on
410 Windows.
411
Victor Stinnerd1432092014-06-19 17:11:49 +0200412 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100413
Victor Stinner60208a12015-09-15 22:41:52 +0200414 .. versionchanged:: 3.5
415
416 On Windows with :class:`ProactorEventLoop`, SSL/TLS is now supported.
Victor Stinner41f3c3f2014-08-31 14:47:37 +0200417
Victor Stinnerc8ea8132014-01-23 11:02:09 +0100418 .. seealso::
419
420 The function :func:`start_server` creates a (:class:`StreamReader`,
421 :class:`StreamWriter`) pair and calls back a function with this pair.
422
Victor Stinner7b58a2b2015-09-21 18:41:05 +0200423 .. versionchanged:: 3.5.1
Victor Stinner5e4a7d82015-09-21 18:33:43 +0200424
425 The *host* parameter can now be a sequence of strings.
426
Victor Stinnerea3183f2013-12-03 01:08:00 +0100427
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100428.. coroutinemethod:: BaseEventLoop.create_unix_server(protocol_factory, path=None, \*, sock=None, backlog=100, ssl=None)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100429
Victor Stinnera6919aa2014-02-19 13:32:34 +0100430 Similar to :meth:`BaseEventLoop.create_server`, but specific to the
431 socket family :py:data:`~socket.AF_UNIX`.
432
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100433 This method is a :ref:`coroutine <coroutine>`.
434
Victor Stinnera6919aa2014-02-19 13:32:34 +0100435 Availability: UNIX.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100436
437
Victor Stinnerc1567df2014-02-08 23:22:58 +0100438Watch file descriptors
439----------------------
440
Victor Stinner41f3c3f2014-08-31 14:47:37 +0200441On Windows with :class:`SelectorEventLoop`, only socket handles are supported
442(ex: pipe file descriptors are not supported).
443
444On Windows with :class:`ProactorEventLoop`, these methods are not supported.
445
Victor Stinnerc1567df2014-02-08 23:22:58 +0100446.. method:: BaseEventLoop.add_reader(fd, callback, \*args)
447
448 Start watching the file descriptor for read availability and then call the
449 *callback* with specified arguments.
450
Victor Stinner8464c242014-11-28 13:15:41 +0100451 :ref:`Use functools.partial to pass keywords to the callback
452 <asyncio-pass-keywords>`.
453
Victor Stinnerc1567df2014-02-08 23:22:58 +0100454.. method:: BaseEventLoop.remove_reader(fd)
455
456 Stop watching the file descriptor for read availability.
457
458.. method:: BaseEventLoop.add_writer(fd, callback, \*args)
459
460 Start watching the file descriptor for write availability and then call the
461 *callback* with specified arguments.
462
Victor Stinner8464c242014-11-28 13:15:41 +0100463 :ref:`Use functools.partial to pass keywords to the callback
464 <asyncio-pass-keywords>`.
465
Victor Stinnerc1567df2014-02-08 23:22:58 +0100466.. method:: BaseEventLoop.remove_writer(fd)
467
468 Stop watching the file descriptor for write availability.
469
Victor Stinner04e6df32014-10-11 16:16:27 +0200470The :ref:`watch a file descriptor for read events <asyncio-watch-read-event>`
471example uses the low-level :meth:`BaseEventLoop.add_reader` method to register
472the file descriptor of a socket.
473
Victor Stinnerc1567df2014-02-08 23:22:58 +0100474
475Low-level socket operations
476---------------------------
477
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100478.. coroutinemethod:: BaseEventLoop.sock_recv(sock, nbytes)
Victor Stinnerc1567df2014-02-08 23:22:58 +0100479
480 Receive data from the socket. The return value is a bytes object
481 representing the data received. The maximum amount of data to be received
482 at once is specified by *nbytes*.
483
Victor Stinnerd84fd732014-08-26 01:01:59 +0200484 With :class:`SelectorEventLoop` event loop, the socket *sock* must be
485 non-blocking.
Victor Stinnerec2ce092014-07-29 23:12:22 +0200486
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500487 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100488
489 .. seealso::
490
491 The :meth:`socket.socket.recv` method.
492
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100493.. coroutinemethod:: BaseEventLoop.sock_sendall(sock, data)
Victor Stinnerc1567df2014-02-08 23:22:58 +0100494
495 Send data to the socket. The socket must be connected to a remote socket.
496 This method continues to send data from *data* until either all data has
497 been sent or an error occurs. ``None`` is returned on success. On error,
498 an exception is raised, and there is no way to determine how much data, if
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500499 any, was successfully processed by the receiving end of the connection.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100500
Victor Stinnerd84fd732014-08-26 01:01:59 +0200501 With :class:`SelectorEventLoop` event loop, the socket *sock* must be
502 non-blocking.
Victor Stinnerec2ce092014-07-29 23:12:22 +0200503
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500504 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100505
506 .. seealso::
507
508 The :meth:`socket.socket.sendall` method.
509
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100510.. coroutinemethod:: BaseEventLoop.sock_connect(sock, address)
Victor Stinnerc1567df2014-02-08 23:22:58 +0100511
512 Connect to a remote socket at *address*.
513
Victor Stinner1b0580b2014-02-13 09:24:37 +0100514 The *address* must be already resolved to avoid the trap of hanging the
515 entire event loop when the address requires doing a DNS lookup. For
Serhiy Storchaka6a7b3a72016-04-17 08:32:47 +0300516 example, it must be an IP address, not a hostname, for
Victor Stinner1b0580b2014-02-13 09:24:37 +0100517 :py:data:`~socket.AF_INET` and :py:data:`~socket.AF_INET6` address families.
518 Use :meth:`getaddrinfo` to resolve the hostname asynchronously.
519
Victor Stinnerd84fd732014-08-26 01:01:59 +0200520 With :class:`SelectorEventLoop` event loop, the socket *sock* must be
521 non-blocking.
Victor Stinnerec2ce092014-07-29 23:12:22 +0200522
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500523 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100524
525 .. seealso::
526
527 The :meth:`BaseEventLoop.create_connection` method, the
528 :func:`open_connection` function and the :meth:`socket.socket.connect`
529 method.
530
531
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100532.. coroutinemethod:: BaseEventLoop.sock_accept(sock)
Victor Stinnerc1567df2014-02-08 23:22:58 +0100533
534 Accept a connection. The socket must be bound to an address and listening
535 for connections. The return value is a pair ``(conn, address)`` where *conn*
536 is a *new* socket object usable to send and receive data on the connection,
537 and *address* is the address bound to the socket on the other end of the
538 connection.
539
Victor Stinnerec2ce092014-07-29 23:12:22 +0200540 The socket *sock* must be non-blocking.
541
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500542 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100543
544 .. seealso::
545
546 The :meth:`BaseEventLoop.create_server` method, the :func:`start_server`
547 function and the :meth:`socket.socket.accept` method.
548
549
550Resolve host name
551-----------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100552
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100553.. coroutinemethod:: BaseEventLoop.getaddrinfo(host, port, \*, family=0, type=0, proto=0, flags=0)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100554
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500555 This method is a :ref:`coroutine <coroutine>`, similar to
556 :meth:`socket.getaddrinfo` function but non-blocking.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100557
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100558.. coroutinemethod:: BaseEventLoop.getnameinfo(sockaddr, flags=0)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100559
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500560 This method is a :ref:`coroutine <coroutine>`, similar to
561 :meth:`socket.getnameinfo` function but non-blocking.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100562
563
Victor Stinner984600f2014-03-25 09:40:26 +0100564Connect pipes
565-------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100566
Victor Stinner41f3c3f2014-08-31 14:47:37 +0200567On Windows with :class:`SelectorEventLoop`, these methods are not supported.
568Use :class:`ProactorEventLoop` to support pipes on Windows.
569
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100570.. coroutinemethod:: BaseEventLoop.connect_read_pipe(protocol_factory, pipe)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100571
Victor Stinnerd84fd732014-08-26 01:01:59 +0200572 Register read pipe in eventloop.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100573
574 *protocol_factory* should instantiate object with :class:`Protocol`
Victor Stinnera5b257a2014-05-29 00:14:03 +0200575 interface. *pipe* is a :term:`file-like object <file object>`.
576 Return pair ``(transport, protocol)``, where *transport* supports the
Victor Stinnerea3183f2013-12-03 01:08:00 +0100577 :class:`ReadTransport` interface.
578
Victor Stinnerd84fd732014-08-26 01:01:59 +0200579 With :class:`SelectorEventLoop` event loop, the *pipe* is set to
580 non-blocking mode.
581
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500582 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100583
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100584.. coroutinemethod:: BaseEventLoop.connect_write_pipe(protocol_factory, pipe)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100585
586 Register write pipe in eventloop.
587
588 *protocol_factory* should instantiate object with :class:`BaseProtocol`
Victor Stinner2cef3002014-10-23 22:38:46 +0200589 interface. *pipe* is :term:`file-like object <file object>`.
590 Return pair ``(transport, protocol)``, where *transport* supports
Victor Stinnerea3183f2013-12-03 01:08:00 +0100591 :class:`WriteTransport` interface.
592
Victor Stinnerd84fd732014-08-26 01:01:59 +0200593 With :class:`SelectorEventLoop` event loop, the *pipe* is set to
594 non-blocking mode.
595
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500596 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100597
Victor Stinner08444382014-02-02 22:43:39 +0100598.. seealso::
599
Victor Stinner984600f2014-03-25 09:40:26 +0100600 The :meth:`BaseEventLoop.subprocess_exec` and
601 :meth:`BaseEventLoop.subprocess_shell` methods.
Victor Stinner08444382014-02-02 22:43:39 +0100602
Victor Stinnerea3183f2013-12-03 01:08:00 +0100603
Victor Stinner8b863482014-01-27 10:07:50 +0100604UNIX signals
605------------
606
607Availability: UNIX only.
608
609.. method:: BaseEventLoop.add_signal_handler(signum, callback, \*args)
610
611 Add a handler for a signal.
612
613 Raise :exc:`ValueError` if the signal number is invalid or uncatchable.
614 Raise :exc:`RuntimeError` if there is a problem setting up the handler.
615
Victor Stinner8464c242014-11-28 13:15:41 +0100616 :ref:`Use functools.partial to pass keywords to the callback
617 <asyncio-pass-keywords>`.
618
Victor Stinner8b863482014-01-27 10:07:50 +0100619.. method:: BaseEventLoop.remove_signal_handler(sig)
620
621 Remove a handler for a signal.
622
623 Return ``True`` if a signal handler was removed, ``False`` if not.
624
625.. seealso::
626
627 The :mod:`signal` module.
628
629
Victor Stinnerea3183f2013-12-03 01:08:00 +0100630Executor
631--------
632
633Call a function in an :class:`~concurrent.futures.Executor` (pool of threads or
634pool of processes). By default, an event loop uses a thread pool executor
635(:class:`~concurrent.futures.ThreadPoolExecutor`).
636
Andrew Svetlov1c62b522015-10-01 09:48:08 +0300637.. coroutinemethod:: BaseEventLoop.run_in_executor(executor, func, \*args)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100638
Andrew Svetlov1c62b522015-10-01 09:48:08 +0300639 Arrange for a *func* to be called in the specified executor.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100640
Larry Hastings3732ed22014-03-15 21:13:56 -0700641 The *executor* argument should be an :class:`~concurrent.futures.Executor`
642 instance. The default executor is used if *executor* is ``None``.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100643
Andrew Svetlov1c62b522015-10-01 09:48:08 +0300644 :ref:`Use functools.partial to pass keywords to the *func*
Victor Stinner8464c242014-11-28 13:15:41 +0100645 <asyncio-pass-keywords>`.
646
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500647 This method is a :ref:`coroutine <coroutine>`.
648
Victor Stinnerea3183f2013-12-03 01:08:00 +0100649.. method:: BaseEventLoop.set_default_executor(executor)
650
651 Set the default executor used by :meth:`run_in_executor`.
652
653
Yury Selivanov43ee1c12014-02-19 20:58:44 -0500654Error Handling API
655------------------
656
Martin Panterc04fb562016-02-10 05:44:01 +0000657Allows customizing how exceptions are handled in the event loop.
Yury Selivanov43ee1c12014-02-19 20:58:44 -0500658
659.. method:: BaseEventLoop.set_exception_handler(handler)
660
661 Set *handler* as the new event loop exception handler.
662
663 If *handler* is ``None``, the default exception handler will
664 be set.
665
666 If *handler* is a callable object, it should have a
667 matching signature to ``(loop, context)``, where ``loop``
668 will be a reference to the active event loop, ``context``
669 will be a ``dict`` object (see :meth:`call_exception_handler`
670 documentation for details about context).
671
672.. method:: BaseEventLoop.default_exception_handler(context)
673
674 Default exception handler.
675
676 This is called when an exception occurs and no exception
677 handler is set, and can be called by a custom exception
678 handler that wants to defer to the default behavior.
679
680 *context* parameter has the same meaning as in
681 :meth:`call_exception_handler`.
682
683.. method:: BaseEventLoop.call_exception_handler(context)
684
685 Call the current event loop exception handler.
686
687 *context* is a ``dict`` object containing the following keys
688 (new keys may be introduced later):
689
690 * 'message': Error message;
691 * 'exception' (optional): Exception object;
692 * 'future' (optional): :class:`asyncio.Future` instance;
693 * 'handle' (optional): :class:`asyncio.Handle` instance;
694 * 'protocol' (optional): :ref:`Protocol <asyncio-protocol>` instance;
695 * 'transport' (optional): :ref:`Transport <asyncio-transport>` instance;
696 * 'socket' (optional): :class:`socket.socket` instance.
697
698 .. note::
699
700 Note: this method should not be overloaded in subclassed
701 event loops. For any custom exception handling, use
702 :meth:`set_exception_handler()` method.
703
Victor Stinner0f3e6bc2014-02-19 23:15:02 +0100704Debug mode
705----------
706
707.. method:: BaseEventLoop.get_debug()
708
Victor Stinner7b7120e2014-06-23 00:12:14 +0200709 Get the debug mode (:class:`bool`) of the event loop.
710
711 The default value is ``True`` if the environment variable
712 :envvar:`PYTHONASYNCIODEBUG` is set to a non-empty string, ``False``
713 otherwise.
Victor Stinner0f3e6bc2014-02-19 23:15:02 +0100714
Victor Stinner64d750b2014-06-18 03:25:23 +0200715 .. versionadded:: 3.4.2
716
Victor Stinner0f3e6bc2014-02-19 23:15:02 +0100717.. method:: BaseEventLoop.set_debug(enabled: bool)
718
719 Set the debug mode of the event loop.
720
Victor Stinner64d750b2014-06-18 03:25:23 +0200721 .. versionadded:: 3.4.2
722
Victor Stinner0f3e6bc2014-02-19 23:15:02 +0100723.. seealso::
724
Victor Stinner62511fd2014-06-23 00:36:11 +0200725 The :ref:`debug mode of asyncio <asyncio-debug-mode>`.
Victor Stinner0f3e6bc2014-02-19 23:15:02 +0100726
Victor Stinner8c462c52014-01-24 18:11:43 +0100727Server
728------
729
Victor Stinner8ebeb032014-07-11 23:47:40 +0200730.. class:: Server
Victor Stinner8c462c52014-01-24 18:11:43 +0100731
Victor Stinner8ebeb032014-07-11 23:47:40 +0200732 Server listening on sockets.
733
734 Object created by the :meth:`BaseEventLoop.create_server` method and the
R David Murray756f0b12015-01-29 19:53:33 -0500735 :func:`start_server` function. Don't instantiate the class directly.
Victor Stinner8c462c52014-01-24 18:11:43 +0100736
737 .. method:: close()
738
Victor Stinner4bfb14a2014-07-12 03:20:24 +0200739 Stop serving: close listening sockets and set the :attr:`sockets`
740 attribute to ``None``.
741
Berker Peksag49c9edf2016-01-20 07:14:22 +0200742 The sockets that represent existing incoming client connections are left
743 open.
Victor Stinner8ebeb032014-07-11 23:47:40 +0200744
Berker Peksag49c9edf2016-01-20 07:14:22 +0200745 The server is closed asynchronously, use the :meth:`wait_closed`
746 coroutine to wait until the server is closed.
Victor Stinner8c462c52014-01-24 18:11:43 +0100747
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100748 .. coroutinemethod:: wait_closed()
Victor Stinner8c462c52014-01-24 18:11:43 +0100749
Victor Stinner8ebeb032014-07-11 23:47:40 +0200750 Wait until the :meth:`close` method completes.
751
752 This method is a :ref:`coroutine <coroutine>`.
753
754 .. attribute:: sockets
755
756 List of :class:`socket.socket` objects the server is listening to, or
757 ``None`` if the server is closed.
Victor Stinner8c462c52014-01-24 18:11:43 +0100758
759
Yury Selivanov43ee1c12014-02-19 20:58:44 -0500760Handle
761------
762
763.. class:: Handle
764
765 A callback wrapper object returned by :func:`BaseEventLoop.call_soon`,
766 :func:`BaseEventLoop.call_soon_threadsafe`, :func:`BaseEventLoop.call_later`,
767 and :func:`BaseEventLoop.call_at`.
768
769 .. method:: cancel()
770
Yury Selivanov1096f762015-06-25 13:49:52 -0400771 Cancel the call. If the callback is already canceled or executed,
772 this method has no effect.
Victor Stinneraea82292014-07-08 23:42:38 +0200773
Yury Selivanov43ee1c12014-02-19 20:58:44 -0500774
Victor Stinner6888b962014-10-11 16:15:58 +0200775Event loop examples
Victor Stinnera092a612015-01-09 15:58:41 +0100776-------------------
Yury Selivanov43ee1c12014-02-19 20:58:44 -0500777
Victor Stinner3e09e322013-12-03 01:22:06 +0100778.. _asyncio-hello-world-callback:
Victor Stinnerea3183f2013-12-03 01:08:00 +0100779
Victor Stinner7f314ed2014-10-15 18:49:16 +0200780Hello World with call_soon()
Victor Stinnera092a612015-01-09 15:58:41 +0100781^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Victor Stinnerea3183f2013-12-03 01:08:00 +0100782
Victor Stinner7f314ed2014-10-15 18:49:16 +0200783Example using the :meth:`BaseEventLoop.call_soon` method to schedule a
784callback. The callback displays ``"Hello World"`` and then stops the event
785loop::
Victor Stinnerea3183f2013-12-03 01:08:00 +0100786
787 import asyncio
788
Victor Stinner7f314ed2014-10-15 18:49:16 +0200789 def hello_world(loop):
Victor Stinnerea3183f2013-12-03 01:08:00 +0100790 print('Hello World')
Victor Stinner7f314ed2014-10-15 18:49:16 +0200791 loop.stop()
Victor Stinnerea3183f2013-12-03 01:08:00 +0100792
793 loop = asyncio.get_event_loop()
Victor Stinner7f314ed2014-10-15 18:49:16 +0200794
795 # Schedule a call to hello_world()
796 loop.call_soon(hello_world, loop)
797
798 # Blocking call interrupted by loop.stop()
799 loop.run_forever()
800 loop.close()
Victor Stinnerea3183f2013-12-03 01:08:00 +0100801
Victor Stinner3e09e322013-12-03 01:22:06 +0100802.. seealso::
Victor Stinnerea3183f2013-12-03 01:08:00 +0100803
Victor Stinner6888b962014-10-11 16:15:58 +0200804 The :ref:`Hello World coroutine <asyncio-hello-world-coroutine>` example
805 uses a :ref:`coroutine <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100806
Victor Stinner8b863482014-01-27 10:07:50 +0100807
Victor Stinner7f314ed2014-10-15 18:49:16 +0200808.. _asyncio-date-callback:
809
810Display the current date with call_later()
Victor Stinnera092a612015-01-09 15:58:41 +0100811^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Victor Stinner7f314ed2014-10-15 18:49:16 +0200812
813Example of callback displaying the current date every second. The callback uses
814the :meth:`BaseEventLoop.call_later` method to reschedule itself during 5
815seconds, and then stops the event loop::
816
817 import asyncio
818 import datetime
819
820 def display_date(end_time, loop):
821 print(datetime.datetime.now())
822 if (loop.time() + 1.0) < end_time:
823 loop.call_later(1, display_date, end_time, loop)
824 else:
825 loop.stop()
826
827 loop = asyncio.get_event_loop()
828
829 # Schedule the first call to display_date()
830 end_time = loop.time() + 5.0
831 loop.call_soon(display_date, end_time, loop)
832
833 # Blocking call interrupted by loop.stop()
834 loop.run_forever()
835 loop.close()
836
837.. seealso::
838
839 The :ref:`coroutine displaying the current date
840 <asyncio-date-coroutine>` example uses a :ref:`coroutine
841 <coroutine>`.
842
843
Victor Stinner04e6df32014-10-11 16:16:27 +0200844.. _asyncio-watch-read-event:
Victor Stinner8b863482014-01-27 10:07:50 +0100845
Victor Stinner04e6df32014-10-11 16:16:27 +0200846Watch a file descriptor for read events
Victor Stinnera092a612015-01-09 15:58:41 +0100847^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Victor Stinner04e6df32014-10-11 16:16:27 +0200848
849Wait until a file descriptor received some data using the
850:meth:`BaseEventLoop.add_reader` method and then close the event loop::
851
852 import asyncio
Victor Stinnerccd8e342014-10-11 16:30:02 +0200853 try:
854 from socket import socketpair
855 except ImportError:
856 from asyncio.windows_utils import socketpair
Victor Stinner04e6df32014-10-11 16:16:27 +0200857
858 # Create a pair of connected file descriptors
Victor Stinnerccd8e342014-10-11 16:30:02 +0200859 rsock, wsock = socketpair()
Victor Stinner04e6df32014-10-11 16:16:27 +0200860 loop = asyncio.get_event_loop()
861
862 def reader():
863 data = rsock.recv(100)
864 print("Received:", data.decode())
Victor Stinner2cef3002014-10-23 22:38:46 +0200865 # We are done: unregister the file descriptor
Victor Stinner04e6df32014-10-11 16:16:27 +0200866 loop.remove_reader(rsock)
867 # Stop the event loop
868 loop.stop()
869
Victor Stinner2cef3002014-10-23 22:38:46 +0200870 # Register the file descriptor for read event
Victor Stinner04e6df32014-10-11 16:16:27 +0200871 loop.add_reader(rsock, reader)
872
873 # Simulate the reception of data from the network
874 loop.call_soon(wsock.send, 'abc'.encode())
875
876 # Run the event loop
877 loop.run_forever()
878
879 # We are done, close sockets and the event loop
880 rsock.close()
881 wsock.close()
882 loop.close()
883
884.. seealso::
885
886 The :ref:`register an open socket to wait for data using a protocol
887 <asyncio-register-socket>` example uses a low-level protocol created by the
888 :meth:`BaseEventLoop.create_connection` method.
889
890 The :ref:`register an open socket to wait for data using streams
891 <asyncio-register-socket-streams>` example uses high-level streams
892 created by the :func:`open_connection` function in a coroutine.
893
894
895Set signal handlers for SIGINT and SIGTERM
Victor Stinnera092a612015-01-09 15:58:41 +0100896^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Victor Stinner04e6df32014-10-11 16:16:27 +0200897
898Register handlers for signals :py:data:`SIGINT` and :py:data:`SIGTERM` using
899the :meth:`BaseEventLoop.add_signal_handler` method::
Victor Stinner8b863482014-01-27 10:07:50 +0100900
901 import asyncio
902 import functools
903 import os
904 import signal
905
906 def ask_exit(signame):
907 print("got signal %s: exit" % signame)
908 loop.stop()
909
910 loop = asyncio.get_event_loop()
911 for signame in ('SIGINT', 'SIGTERM'):
912 loop.add_signal_handler(getattr(signal, signame),
913 functools.partial(ask_exit, signame))
914
Serhiy Storchaka0424eaf2015-09-12 17:45:25 +0300915 print("Event loop running forever, press Ctrl+C to interrupt.")
Victor Stinner8b863482014-01-27 10:07:50 +0100916 print("pid %s: send SIGINT or SIGTERM to exit." % os.getpid())
Victor Stinner63b21a82014-07-05 15:38:59 +0200917 try:
918 loop.run_forever()
919 finally:
920 loop.close()
Victor Stinner2cef3002014-10-23 22:38:46 +0200921
922This example only works on UNIX.