blob: 04b182b9c0c31557d0ce9414d927561e62933b17 [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
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
Eli Bendersky136fea22014-02-09 06:55:58 -080021Event loop policies and the default policy
22------------------------------------------
23
24Event loop management is abstracted with a *policy* pattern, to provide maximal
25flexibility for custom platforms and frameworks. Throughout the execution of a
26process, a single global policy object manages the event loops available to the
27process based on the calling context. A policy is an object implementing the
28:class:`AbstractEventLoopPolicy` interface.
29
30For most users of :mod:`asyncio`, policies never have to be dealt with
31explicitly, since the default global policy is sufficient.
32
33The default policy defines context as the current thread, and manages an event
34loop per thread that interacts with :mod:`asyncio`. The module-level functions
35:func:`get_event_loop` and :func:`set_event_loop` provide convenient access to
36event loops managed by the default policy.
37
Victor Stinnerea3183f2013-12-03 01:08:00 +010038Event loop functions
39--------------------
40
Eli Bendersky136fea22014-02-09 06:55:58 -080041The following functions are convenient shortcuts to accessing the methods of the
42global policy. Note that this provides access to the default policy, unless an
43alternative policy was set by calling :func:`set_event_loop_policy` earlier in
44the execution of the process.
Victor Stinnerea3183f2013-12-03 01:08:00 +010045
46.. function:: get_event_loop()
47
Eli Bendersky136fea22014-02-09 06:55:58 -080048 Equivalent to calling ``get_event_loop_policy().get_event_loop()``.
Victor Stinnerea3183f2013-12-03 01:08:00 +010049
50.. function:: set_event_loop(loop)
51
Eli Bendersky136fea22014-02-09 06:55:58 -080052 Equivalent to calling ``get_event_loop_policy().set_event_loop(loop)``.
Victor Stinnerea3183f2013-12-03 01:08:00 +010053
54.. function:: new_event_loop()
55
Eli Bendersky136fea22014-02-09 06:55:58 -080056 Equivalent to calling ``get_event_loop_policy().new_event_loop()``.
Victor Stinnerea3183f2013-12-03 01:08:00 +010057
Eli Bendersky136fea22014-02-09 06:55:58 -080058Event loop policy interface
59---------------------------
Victor Stinnerea3183f2013-12-03 01:08:00 +010060
Eli Bendersky136fea22014-02-09 06:55:58 -080061An event loop policy must implement the following interface:
62
63.. class:: AbstractEventLoopPolicy
64
65 .. method:: get_event_loop()
66
67 Get the event loop for current context. Returns an event loop object
68 implementing :class:`BaseEventLoop` interface, or raises an exception in case
69 no event loop has been set for the current context and the current policy
70 does not specify to create one. It should never return ``None``.
71
72 .. method:: set_event_loop(loop)
73
74 Set the event loop of the current context to *loop*.
75
76 .. method:: new_event_loop()
77
78 Create and return a new event loop object according to this policy's rules.
79 If there's need to set this loop as the event loop of the current context,
Larry Hastingsad88d7a2014-02-10 04:26:10 -080080 :meth:`set_event_loop` must be called explicitly.
Eli Bendersky136fea22014-02-09 06:55:58 -080081
82Access to the global loop policy
83--------------------------------
Victor Stinnerea3183f2013-12-03 01:08:00 +010084
85.. function:: get_event_loop_policy()
86
Eli Bendersky136fea22014-02-09 06:55:58 -080087 Get the current event loop policy.
Victor Stinnerea3183f2013-12-03 01:08:00 +010088
89.. function:: set_event_loop_policy(policy)
90
Eli Bendersky136fea22014-02-09 06:55:58 -080091 Set the current event loop policy. If *policy* is ``None``, the default
92 policy is restored.
Victor Stinnerea3183f2013-12-03 01:08:00 +010093
94Run an event loop
95-----------------
96
97.. method:: BaseEventLoop.run_forever()
98
99 Run until :meth:`stop` is called.
100
101.. method:: BaseEventLoop.run_until_complete(future)
102
Victor Stinner99c2ab42013-12-03 19:17:25 +0100103 Run until the :class:`Future` is done.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100104
105 If the argument is a coroutine, it is wrapped in a :class:`Task`.
106
107 Return the Future's result, or raise its exception.
108
109.. method:: BaseEventLoop.is_running()
110
111 Returns running status of event loop.
112
Victor Stinnerafbf8272013-12-03 02:05:42 +0100113.. method:: BaseEventLoop.stop()
Victor Stinnerea3183f2013-12-03 01:08:00 +0100114
115 Stop running the event loop.
116
117 Every callback scheduled before :meth:`stop` is called will run.
118 Callback scheduled after :meth:`stop` is called won't. However, those
119 callbacks will run if :meth:`run_forever` is called again later.
120
121.. method:: BaseEventLoop.close()
122
123 Close the event loop. The loop should not be running.
124
125 This clears the queues and shuts down the executor, but does not wait for
126 the executor to finish.
127
128 This is idempotent and irreversible. No other methods should be called after
129 this one.
130
131
132Calls
133-----
134
135.. method:: BaseEventLoop.call_soon(callback, \*args)
136
137 Arrange for a callback to be called as soon as possible.
138
139 This operates as a FIFO queue, callbacks are called in the order in
140 which they are registered. Each callback will be called exactly once.
141
142 Any positional arguments after the callback will be passed to the
143 callback when it is called.
144
145.. method:: BaseEventLoop.call_soon_threadsafe(callback, \*args)
146
147 Like :meth:`call_soon`, but thread safe.
148
149
Victor Stinner45b27ed2014-02-01 02:36:43 +0100150.. _asyncio-delayed-calls:
151
Victor Stinnerea3183f2013-12-03 01:08:00 +0100152Delayed calls
153-------------
154
155The event loop has its own internal clock for computing timeouts.
156Which clock is used depends on the (platform-specific) event loop
157implementation; ideally it is a monotonic clock. This will generally be
158a different clock than :func:`time.time`.
159
Victor Stinner8b21d912014-02-18 09:37:43 +0100160.. note::
161
162 Timeouts (relative *delay* or absolute *when*) should not exceed one day.
163
Victor Stinner45b27ed2014-02-01 02:36:43 +0100164
Victor Stinnerea3183f2013-12-03 01:08:00 +0100165.. method:: BaseEventLoop.call_later(delay, callback, *args)
166
167 Arrange for the *callback* to be called after the given *delay*
168 seconds (either an int or float).
169
170 A "handle" is returned: an opaque object with a :meth:`cancel` method
171 that can be used to cancel the call.
172
173 *callback* will be called exactly once per call to :meth:`call_later`.
174 If two callbacks are scheduled for exactly the same time, it is
175 undefined which will be called first.
176
177 The optional positional *args* will be passed to the callback when it
178 is called. If you want the callback to be called with some named
179 arguments, use a closure or :func:`functools.partial`.
180
181.. method:: BaseEventLoop.call_at(when, callback, *args)
182
183 Arrange for the *callback* to be called at the given absolute timestamp
184 *when* (an int or float), using the same time reference as :meth:`time`.
185
186 This method's behavior is the same as :meth:`call_later`.
187
188.. method:: BaseEventLoop.time()
189
190 Return the current time, as a :class:`float` value, according to the
191 event loop's internal clock.
192
Victor Stinner3e09e322013-12-03 01:22:06 +0100193.. seealso::
194
195 The :func:`asyncio.sleep` function.
196
Victor Stinnerea3183f2013-12-03 01:08:00 +0100197
198Creating connections
Victor Stinner0c6f1ca2013-12-03 01:46:39 +0100199--------------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100200
201.. 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)
202
203 Create a streaming transport connection to a given Internet *host* and
Victor Stinner03e9cb22014-02-19 13:32:34 +0100204 *port*: socket family :py:data:`~socket.AF_INET` or
205 :py:data:`~socket.AF_INET6` depending on *host* (or *family* if specified),
206 socket type :py:data:`~socket.SOCK_STREAM`. *protocol_factory* must be a
207 callable returning a :ref:`protocol <asyncio-protocol>` instance.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100208
Victor Stinner59759ff2014-01-16 19:30:21 +0100209 This method returns a :ref:`coroutine object <coroutine>` which will try to
Victor Stinnerea3183f2013-12-03 01:08:00 +0100210 establish the connection in the background. When successful, the
211 coroutine returns a ``(transport, protocol)`` pair.
212
213 The chronological synopsis of the underlying operation is as follows:
214
Victor Stinner9592edb2014-02-02 15:03:02 +0100215 #. The connection is established, and a :ref:`transport <asyncio-transport>`
Victor Stinnerea3183f2013-12-03 01:08:00 +0100216 is created to represent it.
217
218 #. *protocol_factory* is called without arguments and must return a
Victor Stinner9592edb2014-02-02 15:03:02 +0100219 :ref:`protocol <asyncio-protocol>` instance.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100220
221 #. The protocol instance is tied to the transport, and its
222 :meth:`connection_made` method is called.
223
224 #. The coroutine returns successfully with the ``(transport, protocol)``
225 pair.
226
227 The created transport is an implementation-dependent bidirectional stream.
228
229 .. note::
230 *protocol_factory* can be any kind of callable, not necessarily
231 a class. For example, if you want to use a pre-created
232 protocol instance, you can pass ``lambda: my_protocol``.
233
234 Options allowing to change how the connection is created:
235
236 * *ssl*: if given and not false, a SSL/TLS transport is created
237 (by default a plain TCP transport is created). If *ssl* is
238 a :class:`ssl.SSLContext` object, this context is used to create
239 the transport; if *ssl* is :const:`True`, a context with some
240 unspecified default settings is used.
241
242 * *server_hostname*, is only for use together with *ssl*,
243 and sets or overrides the hostname that the target server's certificate
244 will be matched against. By default the value of the *host* argument
245 is used. If *host* is empty, there is no default and you must pass a
246 value for *server_hostname*. If *server_hostname* is an empty
247 string, hostname matching is disabled (which is a serious security
248 risk, allowing for man-in-the-middle-attacks).
249
250 * *family*, *proto*, *flags* are the optional address family, protocol
251 and flags to be passed through to getaddrinfo() for *host* resolution.
252 If given, these should all be integers from the corresponding
253 :mod:`socket` module constants.
254
255 * *sock*, if given, should be an existing, already connected
256 :class:`socket.socket` object to be used by the transport.
257 If *sock* is given, none of *host*, *port*, *family*, *proto*, *flags*
258 and *local_addr* should be specified.
259
260 * *local_addr*, if given, is a ``(local_host, local_port)`` tuple used
261 to bind the socket to locally. The *local_host* and *local_port*
262 are looked up using getaddrinfo(), similarly to *host* and *port*.
263
Victor Stinnerc8ea8132014-01-23 11:02:09 +0100264 .. seealso::
265
266 The :func:`open_connection` function can be used to get a pair of
267 (:class:`StreamReader`, :class:`StreamWriter`) instead of a protocol.
268
Victor Stinnerea3183f2013-12-03 01:08:00 +0100269
Victor Stinner03e9cb22014-02-19 13:32:34 +0100270.. method:: BaseEventLoop.create_datagram_endpoint(protocol_factory, local_addr=None, remote_addr=None, \*, family=0, proto=0, flags=0)
271
272 Create datagram connection: socket family :py:data:`~socket.AF_INET` or
273 :py:data:`~socket.AF_INET6` depending on *host* (or *family* if specified),
274 socket type :py:data:`~socket.SOCK_DGRAM`.
275
276 This method returns a :ref:`coroutine object <coroutine>` which will try to
277 establish the connection in the background. When successful, the
278 coroutine returns a ``(transport, protocol)`` pair.
279
280 See the :meth:`BaseEventLoop.create_connection` method for parameters.
281
282
283.. method:: BaseEventLoop.create_unix_connection(protocol_factory, path, \*, ssl=None, sock=None, server_hostname=None)
284
285 Create UNIX connection: socket family :py:data:`~socket.AF_UNIX`, socket
286 type :py:data:`~socket.SOCK_STREAM`. The :py:data:`~socket.AF_UNIX` socket
287 family is used to communicate between processes on the same machine
288 efficiently.
289
290 This method returns a :ref:`coroutine object <coroutine>` which will try to
291 establish the connection in the background. When successful, the
292 coroutine returns a ``(transport, protocol)`` pair.
293
294 See the :meth:`BaseEventLoop.create_connection` method for parameters.
295
296 Availability: UNIX.
297
298
Victor Stinnerea3183f2013-12-03 01:08:00 +0100299Creating listening connections
300------------------------------
301
302.. 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)
303
Victor Stinner59759ff2014-01-16 19:30:21 +0100304 A :ref:`coroutine function <coroutine>` which creates a TCP server bound to host and
Victor Stinnerea3183f2013-12-03 01:08:00 +0100305 port.
306
307 The return value is a :class:`AbstractServer` object which can be used to stop
308 the service.
309
310 If *host* is an empty string or None all interfaces are assumed
311 and a list of multiple sockets will be returned (most likely
312 one for IPv4 and another one for IPv6).
313
314 *family* can be set to either :data:`~socket.AF_INET` or
315 :data:`~socket.AF_INET6` to force the socket to use IPv4 or IPv6. If not set
316 it will be determined from host (defaults to :data:`~socket.AF_UNSPEC`).
317
318 *flags* is a bitmask for :meth:`getaddrinfo`.
319
320 *sock* can optionally be specified in order to use a preexisting
321 socket object.
322
323 *backlog* is the maximum number of queued connections passed to
324 :meth:`~socket.socket.listen` (defaults to 100).
325
326 ssl can be set to an :class:`~ssl.SSLContext` to enable SSL over the
327 accepted connections.
328
329 *reuse_address* tells the kernel to reuse a local socket in
330 TIME_WAIT state, without waiting for its natural timeout to
331 expire. If not specified will automatically be set to True on
332 UNIX.
333
Victor Stinner59759ff2014-01-16 19:30:21 +0100334 This method returns a :ref:`coroutine object <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100335
Victor Stinnerc8ea8132014-01-23 11:02:09 +0100336 .. seealso::
337
338 The function :func:`start_server` creates a (:class:`StreamReader`,
339 :class:`StreamWriter`) pair and calls back a function with this pair.
340
Victor Stinnerea3183f2013-12-03 01:08:00 +0100341
Victor Stinner03e9cb22014-02-19 13:32:34 +0100342.. method:: BaseEventLoop.create_unix_server(protocol_factory, path=None, \*, sock=None, backlog=100, ssl=None)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100343
Victor Stinner03e9cb22014-02-19 13:32:34 +0100344 Similar to :meth:`BaseEventLoop.create_server`, but specific to the
345 socket family :py:data:`~socket.AF_UNIX`.
346
347 Availability: UNIX.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100348
349
350
Victor Stinnerc1567df2014-02-08 23:22:58 +0100351Watch file descriptors
352----------------------
353
354.. method:: BaseEventLoop.add_reader(fd, callback, \*args)
355
356 Start watching the file descriptor for read availability and then call the
357 *callback* with specified arguments.
358
359.. method:: BaseEventLoop.remove_reader(fd)
360
361 Stop watching the file descriptor for read availability.
362
363.. method:: BaseEventLoop.add_writer(fd, callback, \*args)
364
365 Start watching the file descriptor for write availability and then call the
366 *callback* with specified arguments.
367
368.. method:: BaseEventLoop.remove_writer(fd)
369
370 Stop watching the file descriptor for write availability.
371
372
373Low-level socket operations
374---------------------------
375
376.. method:: BaseEventLoop.sock_recv(sock, nbytes)
377
378 Receive data from the socket. The return value is a bytes object
379 representing the data received. The maximum amount of data to be received
380 at once is specified by *nbytes*.
381
382 This method returns a :ref:`coroutine object <coroutine>`.
383
384 .. seealso::
385
386 The :meth:`socket.socket.recv` method.
387
388.. method:: BaseEventLoop.sock_sendall(sock, data)
389
390 Send data to the socket. The socket must be connected to a remote socket.
391 This method continues to send data from *data* until either all data has
392 been sent or an error occurs. ``None`` is returned on success. On error,
393 an exception is raised, and there is no way to determine how much data, if
394 any, was successfully sent.
395
396 This method returns a :ref:`coroutine object <coroutine>`.
397
398 .. seealso::
399
400 The :meth:`socket.socket.sendall` method.
401
402.. method:: BaseEventLoop.sock_connect(sock, address)
403
404 Connect to a remote socket at *address*.
405
Victor Stinner28773462014-02-13 09:24:37 +0100406 The *address* must be already resolved to avoid the trap of hanging the
407 entire event loop when the address requires doing a DNS lookup. For
408 example, it must be an IP address, not an hostname, for
409 :py:data:`~socket.AF_INET` and :py:data:`~socket.AF_INET6` address families.
410 Use :meth:`getaddrinfo` to resolve the hostname asynchronously.
411
Victor Stinnerc1567df2014-02-08 23:22:58 +0100412 This method returns a :ref:`coroutine object <coroutine>`.
413
414 .. seealso::
415
416 The :meth:`BaseEventLoop.create_connection` method, the
417 :func:`open_connection` function and the :meth:`socket.socket.connect`
418 method.
419
420
421.. method:: BaseEventLoop.sock_accept(sock)
422
423 Accept a connection. The socket must be bound to an address and listening
424 for connections. The return value is a pair ``(conn, address)`` where *conn*
425 is a *new* socket object usable to send and receive data on the connection,
426 and *address* is the address bound to the socket on the other end of the
427 connection.
428
429 This method returns a :ref:`coroutine object <coroutine>`.
430
431 .. seealso::
432
433 The :meth:`BaseEventLoop.create_server` method, the :func:`start_server`
434 function and the :meth:`socket.socket.accept` method.
435
436
437Resolve host name
438-----------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100439
440.. method:: BaseEventLoop.getaddrinfo(host, port, \*, family=0, type=0, proto=0, flags=0)
441
Victor Stinnerc1567df2014-02-08 23:22:58 +0100442 Similar to the :meth:`socket.getaddrinfo` function, but return a
443 :ref:`coroutine object <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100444
445.. method:: BaseEventLoop.getnameinfo(sockaddr, flags=0)
446
Victor Stinnerc1567df2014-02-08 23:22:58 +0100447 Similar to the :meth:`socket.getnameinfo` function, but return a
448 :ref:`coroutine object <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100449
450
451Running subprocesses
452--------------------
453
454Run subprocesses asynchronously using the :mod:`subprocess` module.
455
Victor Stinner041ff9b2014-01-28 02:24:22 +0100456.. note::
457
458 On Windows, the default event loop uses
459 :class:`selectors.SelectSelector` which only supports sockets. The
Victor Stinner45b27ed2014-02-01 02:36:43 +0100460 :class:`ProactorEventLoop` should be used to support subprocesses.
Victor Stinner041ff9b2014-01-28 02:24:22 +0100461
462.. note::
463
Ned Deilyeecbbad2014-01-27 19:03:07 -0700464 On Mac OS X older than 10.9 (Mavericks), :class:`selectors.KqueueSelector`
Victor Stinner041ff9b2014-01-28 02:24:22 +0100465 does not support character devices like PTY, whereas it is used by the
466 default event loop. The :class:`SelectorEventLoop` can be used with
Victor Stinner3bc647c2014-02-03 00:35:46 +0100467 :class:`SelectSelector` or :class:`PollSelector` to handle character devices
468 on Mac OS X 10.6 (Snow Leopard) and later.
Victor Stinner041ff9b2014-01-28 02:24:22 +0100469
Victor Stinnerea3183f2013-12-03 01:08:00 +0100470.. method:: BaseEventLoop.subprocess_exec(protocol_factory, \*args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=False, shell=False, bufsize=0, \*\*kwargs)
471
472 XXX
473
Victor Stinner59759ff2014-01-16 19:30:21 +0100474 This method returns a :ref:`coroutine object <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100475
476 See the constructor of the :class:`subprocess.Popen` class for parameters.
477
478.. method:: BaseEventLoop.subprocess_shell(protocol_factory, cmd, \*, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=False, shell=True, bufsize=0, \*\*kwargs)
479
480 XXX
481
Victor Stinner59759ff2014-01-16 19:30:21 +0100482 This method returns a :ref:`coroutine object <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100483
484 See the constructor of the :class:`subprocess.Popen` class for parameters.
485
486.. method:: BaseEventLoop.connect_read_pipe(protocol_factory, pipe)
487
488 Register read pipe in eventloop.
489
490 *protocol_factory* should instantiate object with :class:`Protocol`
491 interface. pipe is file-like object already switched to nonblocking.
492 Return pair (transport, protocol), where transport support
493 :class:`ReadTransport` interface.
494
Victor Stinner59759ff2014-01-16 19:30:21 +0100495 This method returns a :ref:`coroutine object <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100496
497.. method:: BaseEventLoop.connect_write_pipe(protocol_factory, pipe)
498
499 Register write pipe in eventloop.
500
501 *protocol_factory* should instantiate object with :class:`BaseProtocol`
502 interface. Pipe is file-like object already switched to nonblocking.
503 Return pair (transport, protocol), where transport support
504 :class:`WriteTransport` interface.
505
Victor Stinner59759ff2014-01-16 19:30:21 +0100506 This method returns a :ref:`coroutine object <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100507
Victor Stinner08444382014-02-02 22:43:39 +0100508.. seealso::
509
510 The :func:`create_subprocess_exec` and :func:`create_subprocess_shell`
511 functions.
512
Victor Stinnerea3183f2013-12-03 01:08:00 +0100513
Victor Stinner8b863482014-01-27 10:07:50 +0100514UNIX signals
515------------
516
517Availability: UNIX only.
518
519.. method:: BaseEventLoop.add_signal_handler(signum, callback, \*args)
520
521 Add a handler for a signal.
522
523 Raise :exc:`ValueError` if the signal number is invalid or uncatchable.
524 Raise :exc:`RuntimeError` if there is a problem setting up the handler.
525
526.. method:: BaseEventLoop.remove_signal_handler(sig)
527
528 Remove a handler for a signal.
529
530 Return ``True`` if a signal handler was removed, ``False`` if not.
531
532.. seealso::
533
534 The :mod:`signal` module.
535
536
Victor Stinnerea3183f2013-12-03 01:08:00 +0100537Executor
538--------
539
540Call a function in an :class:`~concurrent.futures.Executor` (pool of threads or
541pool of processes). By default, an event loop uses a thread pool executor
542(:class:`~concurrent.futures.ThreadPoolExecutor`).
543
544.. method:: BaseEventLoop.run_in_executor(executor, callback, \*args)
545
546 Arrange for a callback to be called in the specified executor.
547
548 *executor* is a :class:`~concurrent.futures.Executor` instance,
549 the default executor is used if *executor* is ``None``.
550
551.. method:: BaseEventLoop.set_default_executor(executor)
552
553 Set the default executor used by :meth:`run_in_executor`.
554
555
Victor Stinner7ef60cd2014-02-19 23:15:02 +0100556Debug mode
557----------
558
559.. method:: BaseEventLoop.get_debug()
560
561 Get the debug mode (:class:`bool`) of the event loop.
562
563.. method:: BaseEventLoop.set_debug(enabled: bool)
564
565 Set the debug mode of the event loop.
566
567.. seealso::
568
569 The :ref:`Develop with asyncio <asyncio-dev>` section.
570
571
Victor Stinner8c462c52014-01-24 18:11:43 +0100572Server
573------
574
575.. class:: AbstractServer
576
577 Abstract server returned by :func:`BaseEventLoop.create_server`.
578
579 .. method:: close()
580
581 Stop serving. This leaves existing connections open.
582
583 .. method:: wait_closed()
584
585 Coroutine to wait until service is closed.
586
587
Victor Stinner3e09e322013-12-03 01:22:06 +0100588.. _asyncio-hello-world-callback:
Victor Stinnerea3183f2013-12-03 01:08:00 +0100589
Victor Stinner3e09e322013-12-03 01:22:06 +0100590Example: Hello World (callback)
591-------------------------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100592
593Print ``Hello World`` every two seconds, using a callback::
594
595 import asyncio
596
597 def print_and_repeat(loop):
598 print('Hello World')
599 loop.call_later(2, print_and_repeat, loop)
600
601 loop = asyncio.get_event_loop()
Victor Stinnerdbd89502013-12-10 02:47:22 +0100602 loop.call_soon(print_and_repeat, loop)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100603 loop.run_forever()
604
Victor Stinner3e09e322013-12-03 01:22:06 +0100605.. seealso::
Victor Stinnerea3183f2013-12-03 01:08:00 +0100606
Victor Stinner3e09e322013-12-03 01:22:06 +0100607 :ref:`Hello World example using a coroutine <asyncio-hello-world-coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100608
Victor Stinner8b863482014-01-27 10:07:50 +0100609
610Example: Set signal handlers for SIGINT and SIGTERM
611---------------------------------------------------
612
613Register handlers for signals :py:data:`SIGINT` and :py:data:`SIGTERM`::
614
615 import asyncio
616 import functools
617 import os
618 import signal
619
620 def ask_exit(signame):
621 print("got signal %s: exit" % signame)
622 loop.stop()
623
624 loop = asyncio.get_event_loop()
625 for signame in ('SIGINT', 'SIGTERM'):
626 loop.add_signal_handler(getattr(signal, signame),
627 functools.partial(ask_exit, signame))
628
629 print("Event loop running forever, press CTRL+c to interrupt.")
630 print("pid %s: send SIGINT or SIGTERM to exit." % os.getpid())
631 loop.run_forever()
632