blob: 6c3c2df7cc54b51df89c4171fb6abb748aa51548 [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
5Event loops
6===========
7
8The event loop is the central execution device provided by :mod:`asyncio`.
9It provides multiple facilities, amongst which:
10
11* Registering, executing and cancelling delayed calls (timeouts)
12
Victor Stinner9592edb2014-02-02 15:03:02 +010013* Creating client and server :ref:`transports <asyncio-transport>` for various
Victor Stinnerea3183f2013-12-03 01:08:00 +010014 kinds of communication
15
Victor Stinner9592edb2014-02-02 15:03:02 +010016* Launching subprocesses and the associated :ref:`transports <asyncio-transport>`
Victor Stinnerea3183f2013-12-03 01:08:00 +010017 for communication with an external program
18
19* Delegating costly function calls to a pool of threads
20
21Event loop functions
22--------------------
23
24The easiest way to get an event loop is to call the :func:`get_event_loop`
25function.
26
27.. function:: get_event_loop()
28
29 Get the event loop for current context. Returns an event loop object
30 implementing :class:`BaseEventLoop` interface, or raises an exception in case no
31 event loop has been set for the current context and the current policy does
32 not specify to create one. It should never return ``None``.
33
34.. function:: set_event_loop(loop)
35
36 XXX
37
38.. function:: new_event_loop()
39
40 XXX
41
42
43Event loop policy
44-----------------
45
46.. function:: get_event_loop_policy()
47
48 XXX
49
50.. function:: set_event_loop_policy(policy)
51
52 XXX
53
54
55Run an event loop
56-----------------
57
58.. method:: BaseEventLoop.run_forever()
59
60 Run until :meth:`stop` is called.
61
62.. method:: BaseEventLoop.run_until_complete(future)
63
Victor Stinner99c2ab42013-12-03 19:17:25 +010064 Run until the :class:`Future` is done.
Victor Stinnerea3183f2013-12-03 01:08:00 +010065
66 If the argument is a coroutine, it is wrapped in a :class:`Task`.
67
68 Return the Future's result, or raise its exception.
69
70.. method:: BaseEventLoop.is_running()
71
72 Returns running status of event loop.
73
Victor Stinnerafbf8272013-12-03 02:05:42 +010074.. method:: BaseEventLoop.stop()
Victor Stinnerea3183f2013-12-03 01:08:00 +010075
76 Stop running the event loop.
77
78 Every callback scheduled before :meth:`stop` is called will run.
79 Callback scheduled after :meth:`stop` is called won't. However, those
80 callbacks will run if :meth:`run_forever` is called again later.
81
82.. method:: BaseEventLoop.close()
83
84 Close the event loop. The loop should not be running.
85
86 This clears the queues and shuts down the executor, but does not wait for
87 the executor to finish.
88
89 This is idempotent and irreversible. No other methods should be called after
90 this one.
91
92
93Calls
94-----
95
96.. method:: BaseEventLoop.call_soon(callback, \*args)
97
98 Arrange for a callback to be called as soon as possible.
99
100 This operates as a FIFO queue, callbacks are called in the order in
101 which they are registered. Each callback will be called exactly once.
102
103 Any positional arguments after the callback will be passed to the
104 callback when it is called.
105
106.. method:: BaseEventLoop.call_soon_threadsafe(callback, \*args)
107
108 Like :meth:`call_soon`, but thread safe.
109
110
Victor Stinner45b27ed2014-02-01 02:36:43 +0100111.. _asyncio-delayed-calls:
112
Victor Stinnerea3183f2013-12-03 01:08:00 +0100113Delayed calls
114-------------
115
116The event loop has its own internal clock for computing timeouts.
117Which clock is used depends on the (platform-specific) event loop
118implementation; ideally it is a monotonic clock. This will generally be
119a different clock than :func:`time.time`.
120
Victor Stinner45b27ed2014-02-01 02:36:43 +0100121The granularity of the event loop depends on the resolution of the
122:meth:`~BaseEventLoop.time` method and the resolution of the selector. It is
123usually between 1 ms and 16 ms. For example, a granularity of 1 ms means that
124in the best case, the difference between the expected delay and the real
125elapsed time is between -1 ms and +1 ms: a call scheduled in 1 nanosecond may
126be called in 1 ms, and a call scheduled in 100 ms may be called in 99 ms.
127
128The granularity is the best difference in theory. In practice, it depends on
129the system load and the the time taken by tasks executed by the event loop.
130For example, if a task blocks the event loop for 1 second, all tasks scheduled
131in this second will be delayed. The :ref:`Handle correctly blocking functions
132<asyncio-handle-blocking>` section explains how to avoid such issue.
133
134
Victor Stinnerea3183f2013-12-03 01:08:00 +0100135.. method:: BaseEventLoop.call_later(delay, callback, *args)
136
137 Arrange for the *callback* to be called after the given *delay*
138 seconds (either an int or float).
139
140 A "handle" is returned: an opaque object with a :meth:`cancel` method
141 that can be used to cancel the call.
142
143 *callback* will be called exactly once per call to :meth:`call_later`.
144 If two callbacks are scheduled for exactly the same time, it is
145 undefined which will be called first.
146
147 The optional positional *args* will be passed to the callback when it
148 is called. If you want the callback to be called with some named
149 arguments, use a closure or :func:`functools.partial`.
150
151.. method:: BaseEventLoop.call_at(when, callback, *args)
152
153 Arrange for the *callback* to be called at the given absolute timestamp
154 *when* (an int or float), using the same time reference as :meth:`time`.
155
156 This method's behavior is the same as :meth:`call_later`.
157
158.. method:: BaseEventLoop.time()
159
160 Return the current time, as a :class:`float` value, according to the
161 event loop's internal clock.
162
Victor Stinner3e09e322013-12-03 01:22:06 +0100163.. seealso::
164
165 The :func:`asyncio.sleep` function.
166
Victor Stinnerea3183f2013-12-03 01:08:00 +0100167
168Creating connections
Victor Stinner0c6f1ca2013-12-03 01:46:39 +0100169--------------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100170
171.. method:: 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)
172
173 Create a streaming transport connection to a given Internet *host* and
174 *port*. *protocol_factory* must be a callable returning a
Victor Stinner9592edb2014-02-02 15:03:02 +0100175 :ref:`protocol <asyncio-protocol>` instance.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100176
Victor Stinner59759ff2014-01-16 19:30:21 +0100177 This method returns a :ref:`coroutine object <coroutine>` which will try to
Victor Stinnerea3183f2013-12-03 01:08:00 +0100178 establish the connection in the background. When successful, the
179 coroutine returns a ``(transport, protocol)`` pair.
180
181 The chronological synopsis of the underlying operation is as follows:
182
Victor Stinner9592edb2014-02-02 15:03:02 +0100183 #. The connection is established, and a :ref:`transport <asyncio-transport>`
Victor Stinnerea3183f2013-12-03 01:08:00 +0100184 is created to represent it.
185
186 #. *protocol_factory* is called without arguments and must return a
Victor Stinner9592edb2014-02-02 15:03:02 +0100187 :ref:`protocol <asyncio-protocol>` instance.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100188
189 #. The protocol instance is tied to the transport, and its
190 :meth:`connection_made` method is called.
191
192 #. The coroutine returns successfully with the ``(transport, protocol)``
193 pair.
194
195 The created transport is an implementation-dependent bidirectional stream.
196
197 .. note::
198 *protocol_factory* can be any kind of callable, not necessarily
199 a class. For example, if you want to use a pre-created
200 protocol instance, you can pass ``lambda: my_protocol``.
201
202 Options allowing to change how the connection is created:
203
204 * *ssl*: if given and not false, a SSL/TLS transport is created
205 (by default a plain TCP transport is created). If *ssl* is
206 a :class:`ssl.SSLContext` object, this context is used to create
207 the transport; if *ssl* is :const:`True`, a context with some
208 unspecified default settings is used.
209
210 * *server_hostname*, is only for use together with *ssl*,
211 and sets or overrides the hostname that the target server's certificate
212 will be matched against. By default the value of the *host* argument
213 is used. If *host* is empty, there is no default and you must pass a
214 value for *server_hostname*. If *server_hostname* is an empty
215 string, hostname matching is disabled (which is a serious security
216 risk, allowing for man-in-the-middle-attacks).
217
218 * *family*, *proto*, *flags* are the optional address family, protocol
219 and flags to be passed through to getaddrinfo() for *host* resolution.
220 If given, these should all be integers from the corresponding
221 :mod:`socket` module constants.
222
223 * *sock*, if given, should be an existing, already connected
224 :class:`socket.socket` object to be used by the transport.
225 If *sock* is given, none of *host*, *port*, *family*, *proto*, *flags*
226 and *local_addr* should be specified.
227
228 * *local_addr*, if given, is a ``(local_host, local_port)`` tuple used
229 to bind the socket to locally. The *local_host* and *local_port*
230 are looked up using getaddrinfo(), similarly to *host* and *port*.
231
Victor Stinnerc8ea8132014-01-23 11:02:09 +0100232 .. seealso::
233
234 The :func:`open_connection` function can be used to get a pair of
235 (:class:`StreamReader`, :class:`StreamWriter`) instead of a protocol.
236
Victor Stinnerea3183f2013-12-03 01:08:00 +0100237
238Creating listening connections
239------------------------------
240
241.. method:: 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)
242
Victor Stinner59759ff2014-01-16 19:30:21 +0100243 A :ref:`coroutine function <coroutine>` which creates a TCP server bound to host and
Victor Stinnerea3183f2013-12-03 01:08:00 +0100244 port.
245
246 The return value is a :class:`AbstractServer` object which can be used to stop
247 the service.
248
249 If *host* is an empty string or None all interfaces are assumed
250 and a list of multiple sockets will be returned (most likely
251 one for IPv4 and another one for IPv6).
252
253 *family* can be set to either :data:`~socket.AF_INET` or
254 :data:`~socket.AF_INET6` to force the socket to use IPv4 or IPv6. If not set
255 it will be determined from host (defaults to :data:`~socket.AF_UNSPEC`).
256
257 *flags* is a bitmask for :meth:`getaddrinfo`.
258
259 *sock* can optionally be specified in order to use a preexisting
260 socket object.
261
262 *backlog* is the maximum number of queued connections passed to
263 :meth:`~socket.socket.listen` (defaults to 100).
264
265 ssl can be set to an :class:`~ssl.SSLContext` to enable SSL over the
266 accepted connections.
267
268 *reuse_address* tells the kernel to reuse a local socket in
269 TIME_WAIT state, without waiting for its natural timeout to
270 expire. If not specified will automatically be set to True on
271 UNIX.
272
Victor Stinner59759ff2014-01-16 19:30:21 +0100273 This method returns a :ref:`coroutine object <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100274
Victor Stinnerc8ea8132014-01-23 11:02:09 +0100275 .. seealso::
276
277 The function :func:`start_server` creates a (:class:`StreamReader`,
278 :class:`StreamWriter`) pair and calls back a function with this pair.
279
Victor Stinnerea3183f2013-12-03 01:08:00 +0100280.. method:: BaseEventLoop.create_datagram_endpoint(protocol_factory, local_addr=None, remote_addr=None, \*, family=0, proto=0, flags=0)
281
282 Create datagram connection.
283
Victor Stinner59759ff2014-01-16 19:30:21 +0100284 This method returns a :ref:`coroutine object <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100285
286
287
288Resolve name
289------------
290
291.. method:: BaseEventLoop.getaddrinfo(host, port, \*, family=0, type=0, proto=0, flags=0)
292
293 XXX
294
295.. method:: BaseEventLoop.getnameinfo(sockaddr, flags=0)
296
297 XXX
298
299
300Running subprocesses
301--------------------
302
303Run subprocesses asynchronously using the :mod:`subprocess` module.
304
Victor Stinner041ff9b2014-01-28 02:24:22 +0100305.. note::
306
307 On Windows, the default event loop uses
308 :class:`selectors.SelectSelector` which only supports sockets. The
Victor Stinner45b27ed2014-02-01 02:36:43 +0100309 :class:`ProactorEventLoop` should be used to support subprocesses.
Victor Stinner041ff9b2014-01-28 02:24:22 +0100310
311.. note::
312
Ned Deilyeecbbad2014-01-27 19:03:07 -0700313 On Mac OS X older than 10.9 (Mavericks), :class:`selectors.KqueueSelector`
Victor Stinner041ff9b2014-01-28 02:24:22 +0100314 does not support character devices like PTY, whereas it is used by the
315 default event loop. The :class:`SelectorEventLoop` can be used with
Victor Stinner3bc647c2014-02-03 00:35:46 +0100316 :class:`SelectSelector` or :class:`PollSelector` to handle character devices
317 on Mac OS X 10.6 (Snow Leopard) and later.
Victor Stinner041ff9b2014-01-28 02:24:22 +0100318
Victor Stinnerea3183f2013-12-03 01:08:00 +0100319.. method:: BaseEventLoop.subprocess_exec(protocol_factory, \*args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=False, shell=False, bufsize=0, \*\*kwargs)
320
321 XXX
322
Victor Stinner59759ff2014-01-16 19:30:21 +0100323 This method returns a :ref:`coroutine object <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100324
325 See the constructor of the :class:`subprocess.Popen` class for parameters.
326
327.. method:: BaseEventLoop.subprocess_shell(protocol_factory, cmd, \*, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=False, shell=True, bufsize=0, \*\*kwargs)
328
329 XXX
330
Victor Stinner59759ff2014-01-16 19:30:21 +0100331 This method returns a :ref:`coroutine object <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100332
333 See the constructor of the :class:`subprocess.Popen` class for parameters.
334
335.. method:: BaseEventLoop.connect_read_pipe(protocol_factory, pipe)
336
337 Register read pipe in eventloop.
338
339 *protocol_factory* should instantiate object with :class:`Protocol`
340 interface. pipe is file-like object already switched to nonblocking.
341 Return pair (transport, protocol), where transport support
342 :class:`ReadTransport` interface.
343
Victor Stinner59759ff2014-01-16 19:30:21 +0100344 This method returns a :ref:`coroutine object <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100345
346.. method:: BaseEventLoop.connect_write_pipe(protocol_factory, pipe)
347
348 Register write pipe in eventloop.
349
350 *protocol_factory* should instantiate object with :class:`BaseProtocol`
351 interface. Pipe is file-like object already switched to nonblocking.
352 Return pair (transport, protocol), where transport support
353 :class:`WriteTransport` interface.
354
Victor Stinner59759ff2014-01-16 19:30:21 +0100355 This method returns a :ref:`coroutine object <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100356
Victor Stinner08444382014-02-02 22:43:39 +0100357.. seealso::
358
359 The :func:`create_subprocess_exec` and :func:`create_subprocess_shell`
360 functions.
361
Victor Stinnerea3183f2013-12-03 01:08:00 +0100362
Victor Stinner8b863482014-01-27 10:07:50 +0100363UNIX signals
364------------
365
366Availability: UNIX only.
367
368.. method:: BaseEventLoop.add_signal_handler(signum, callback, \*args)
369
370 Add a handler for a signal.
371
372 Raise :exc:`ValueError` if the signal number is invalid or uncatchable.
373 Raise :exc:`RuntimeError` if there is a problem setting up the handler.
374
375.. method:: BaseEventLoop.remove_signal_handler(sig)
376
377 Remove a handler for a signal.
378
379 Return ``True`` if a signal handler was removed, ``False`` if not.
380
381.. seealso::
382
383 The :mod:`signal` module.
384
385
Victor Stinnerea3183f2013-12-03 01:08:00 +0100386Executor
387--------
388
389Call a function in an :class:`~concurrent.futures.Executor` (pool of threads or
390pool of processes). By default, an event loop uses a thread pool executor
391(:class:`~concurrent.futures.ThreadPoolExecutor`).
392
393.. method:: BaseEventLoop.run_in_executor(executor, callback, \*args)
394
395 Arrange for a callback to be called in the specified executor.
396
397 *executor* is a :class:`~concurrent.futures.Executor` instance,
398 the default executor is used if *executor* is ``None``.
399
400.. method:: BaseEventLoop.set_default_executor(executor)
401
402 Set the default executor used by :meth:`run_in_executor`.
403
404
Victor Stinner8c462c52014-01-24 18:11:43 +0100405Server
406------
407
408.. class:: AbstractServer
409
410 Abstract server returned by :func:`BaseEventLoop.create_server`.
411
412 .. method:: close()
413
414 Stop serving. This leaves existing connections open.
415
416 .. method:: wait_closed()
417
418 Coroutine to wait until service is closed.
419
420
Victor Stinner3e09e322013-12-03 01:22:06 +0100421.. _asyncio-hello-world-callback:
Victor Stinnerea3183f2013-12-03 01:08:00 +0100422
Victor Stinner3e09e322013-12-03 01:22:06 +0100423Example: Hello World (callback)
424-------------------------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100425
426Print ``Hello World`` every two seconds, using a callback::
427
428 import asyncio
429
430 def print_and_repeat(loop):
431 print('Hello World')
432 loop.call_later(2, print_and_repeat, loop)
433
434 loop = asyncio.get_event_loop()
Victor Stinnerdbd89502013-12-10 02:47:22 +0100435 loop.call_soon(print_and_repeat, loop)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100436 loop.run_forever()
437
Victor Stinner3e09e322013-12-03 01:22:06 +0100438.. seealso::
Victor Stinnerea3183f2013-12-03 01:08:00 +0100439
Victor Stinner3e09e322013-12-03 01:22:06 +0100440 :ref:`Hello World example using a coroutine <asyncio-hello-world-coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100441
Victor Stinner8b863482014-01-27 10:07:50 +0100442
443Example: Set signal handlers for SIGINT and SIGTERM
444---------------------------------------------------
445
446Register handlers for signals :py:data:`SIGINT` and :py:data:`SIGTERM`::
447
448 import asyncio
449 import functools
450 import os
451 import signal
452
453 def ask_exit(signame):
454 print("got signal %s: exit" % signame)
455 loop.stop()
456
457 loop = asyncio.get_event_loop()
458 for signame in ('SIGINT', 'SIGTERM'):
459 loop.add_signal_handler(getattr(signal, signame),
460 functools.partial(ask_exit, signame))
461
462 print("Event loop running forever, press CTRL+c to interrupt.")
463 print("pid %s: send SIGINT or SIGTERM to exit." % os.getpid())
464 loop.run_forever()
465