blob: c9721b46c0666815df130c75be40b5ab2ba0cfe6 [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 Stinner45b27ed2014-02-01 02:36:43 +0100160
Victor Stinnerea3183f2013-12-03 01:08:00 +0100161.. method:: BaseEventLoop.call_later(delay, callback, *args)
162
163 Arrange for the *callback* to be called after the given *delay*
164 seconds (either an int or float).
165
166 A "handle" is returned: an opaque object with a :meth:`cancel` method
167 that can be used to cancel the call.
168
169 *callback* will be called exactly once per call to :meth:`call_later`.
170 If two callbacks are scheduled for exactly the same time, it is
171 undefined which will be called first.
172
173 The optional positional *args* will be passed to the callback when it
174 is called. If you want the callback to be called with some named
175 arguments, use a closure or :func:`functools.partial`.
176
177.. method:: BaseEventLoop.call_at(when, callback, *args)
178
179 Arrange for the *callback* to be called at the given absolute timestamp
180 *when* (an int or float), using the same time reference as :meth:`time`.
181
182 This method's behavior is the same as :meth:`call_later`.
183
184.. method:: BaseEventLoop.time()
185
186 Return the current time, as a :class:`float` value, according to the
187 event loop's internal clock.
188
Victor Stinner3e09e322013-12-03 01:22:06 +0100189.. seealso::
190
191 The :func:`asyncio.sleep` function.
192
Victor Stinnerea3183f2013-12-03 01:08:00 +0100193
194Creating connections
Victor Stinner0c6f1ca2013-12-03 01:46:39 +0100195--------------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100196
197.. 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)
198
199 Create a streaming transport connection to a given Internet *host* and
200 *port*. *protocol_factory* must be a callable returning a
Victor Stinner9592edb2014-02-02 15:03:02 +0100201 :ref:`protocol <asyncio-protocol>` instance.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100202
Victor Stinner59759ff2014-01-16 19:30:21 +0100203 This method returns a :ref:`coroutine object <coroutine>` which will try to
Victor Stinnerea3183f2013-12-03 01:08:00 +0100204 establish the connection in the background. When successful, the
205 coroutine returns a ``(transport, protocol)`` pair.
206
207 The chronological synopsis of the underlying operation is as follows:
208
Victor Stinner9592edb2014-02-02 15:03:02 +0100209 #. The connection is established, and a :ref:`transport <asyncio-transport>`
Victor Stinnerea3183f2013-12-03 01:08:00 +0100210 is created to represent it.
211
212 #. *protocol_factory* is called without arguments and must return a
Victor Stinner9592edb2014-02-02 15:03:02 +0100213 :ref:`protocol <asyncio-protocol>` instance.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100214
215 #. The protocol instance is tied to the transport, and its
216 :meth:`connection_made` method is called.
217
218 #. The coroutine returns successfully with the ``(transport, protocol)``
219 pair.
220
221 The created transport is an implementation-dependent bidirectional stream.
222
223 .. note::
224 *protocol_factory* can be any kind of callable, not necessarily
225 a class. For example, if you want to use a pre-created
226 protocol instance, you can pass ``lambda: my_protocol``.
227
228 Options allowing to change how the connection is created:
229
230 * *ssl*: if given and not false, a SSL/TLS transport is created
231 (by default a plain TCP transport is created). If *ssl* is
232 a :class:`ssl.SSLContext` object, this context is used to create
233 the transport; if *ssl* is :const:`True`, a context with some
234 unspecified default settings is used.
235
236 * *server_hostname*, is only for use together with *ssl*,
237 and sets or overrides the hostname that the target server's certificate
238 will be matched against. By default the value of the *host* argument
239 is used. If *host* is empty, there is no default and you must pass a
240 value for *server_hostname*. If *server_hostname* is an empty
241 string, hostname matching is disabled (which is a serious security
242 risk, allowing for man-in-the-middle-attacks).
243
244 * *family*, *proto*, *flags* are the optional address family, protocol
245 and flags to be passed through to getaddrinfo() for *host* resolution.
246 If given, these should all be integers from the corresponding
247 :mod:`socket` module constants.
248
249 * *sock*, if given, should be an existing, already connected
250 :class:`socket.socket` object to be used by the transport.
251 If *sock* is given, none of *host*, *port*, *family*, *proto*, *flags*
252 and *local_addr* should be specified.
253
254 * *local_addr*, if given, is a ``(local_host, local_port)`` tuple used
255 to bind the socket to locally. The *local_host* and *local_port*
256 are looked up using getaddrinfo(), similarly to *host* and *port*.
257
Victor Stinnerc8ea8132014-01-23 11:02:09 +0100258 .. seealso::
259
260 The :func:`open_connection` function can be used to get a pair of
261 (:class:`StreamReader`, :class:`StreamWriter`) instead of a protocol.
262
Victor Stinnerea3183f2013-12-03 01:08:00 +0100263
264Creating listening connections
265------------------------------
266
267.. 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)
268
Victor Stinner59759ff2014-01-16 19:30:21 +0100269 A :ref:`coroutine function <coroutine>` which creates a TCP server bound to host and
Victor Stinnerea3183f2013-12-03 01:08:00 +0100270 port.
271
272 The return value is a :class:`AbstractServer` object which can be used to stop
273 the service.
274
275 If *host* is an empty string or None all interfaces are assumed
276 and a list of multiple sockets will be returned (most likely
277 one for IPv4 and another one for IPv6).
278
279 *family* can be set to either :data:`~socket.AF_INET` or
280 :data:`~socket.AF_INET6` to force the socket to use IPv4 or IPv6. If not set
281 it will be determined from host (defaults to :data:`~socket.AF_UNSPEC`).
282
283 *flags* is a bitmask for :meth:`getaddrinfo`.
284
285 *sock* can optionally be specified in order to use a preexisting
286 socket object.
287
288 *backlog* is the maximum number of queued connections passed to
289 :meth:`~socket.socket.listen` (defaults to 100).
290
291 ssl can be set to an :class:`~ssl.SSLContext` to enable SSL over the
292 accepted connections.
293
294 *reuse_address* tells the kernel to reuse a local socket in
295 TIME_WAIT state, without waiting for its natural timeout to
296 expire. If not specified will automatically be set to True on
297 UNIX.
298
Victor Stinner59759ff2014-01-16 19:30:21 +0100299 This method returns a :ref:`coroutine object <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100300
Victor Stinnerc8ea8132014-01-23 11:02:09 +0100301 .. seealso::
302
303 The function :func:`start_server` creates a (:class:`StreamReader`,
304 :class:`StreamWriter`) pair and calls back a function with this pair.
305
Victor Stinnerea3183f2013-12-03 01:08:00 +0100306.. method:: BaseEventLoop.create_datagram_endpoint(protocol_factory, local_addr=None, remote_addr=None, \*, family=0, proto=0, flags=0)
307
308 Create datagram connection.
309
Victor Stinner59759ff2014-01-16 19:30:21 +0100310 This method returns a :ref:`coroutine object <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100311
312
313
Victor Stinnerc1567df2014-02-08 23:22:58 +0100314Watch file descriptors
315----------------------
316
317.. method:: BaseEventLoop.add_reader(fd, callback, \*args)
318
319 Start watching the file descriptor for read availability and then call the
320 *callback* with specified arguments.
321
322.. method:: BaseEventLoop.remove_reader(fd)
323
324 Stop watching the file descriptor for read availability.
325
326.. method:: BaseEventLoop.add_writer(fd, callback, \*args)
327
328 Start watching the file descriptor for write availability and then call the
329 *callback* with specified arguments.
330
331.. method:: BaseEventLoop.remove_writer(fd)
332
333 Stop watching the file descriptor for write availability.
334
335
336Low-level socket operations
337---------------------------
338
339.. method:: BaseEventLoop.sock_recv(sock, nbytes)
340
341 Receive data from the socket. The return value is a bytes object
342 representing the data received. The maximum amount of data to be received
343 at once is specified by *nbytes*.
344
345 This method returns a :ref:`coroutine object <coroutine>`.
346
347 .. seealso::
348
349 The :meth:`socket.socket.recv` method.
350
351.. method:: BaseEventLoop.sock_sendall(sock, data)
352
353 Send data to the socket. The socket must be connected to a remote socket.
354 This method continues to send data from *data* until either all data has
355 been sent or an error occurs. ``None`` is returned on success. On error,
356 an exception is raised, and there is no way to determine how much data, if
357 any, was successfully sent.
358
359 This method returns a :ref:`coroutine object <coroutine>`.
360
361 .. seealso::
362
363 The :meth:`socket.socket.sendall` method.
364
365.. method:: BaseEventLoop.sock_connect(sock, address)
366
367 Connect to a remote socket at *address*.
368
369 This method returns a :ref:`coroutine object <coroutine>`.
370
371 .. seealso::
372
373 The :meth:`BaseEventLoop.create_connection` method, the
374 :func:`open_connection` function and the :meth:`socket.socket.connect`
375 method.
376
377
378.. method:: BaseEventLoop.sock_accept(sock)
379
380 Accept a connection. The socket must be bound to an address and listening
381 for connections. The return value is a pair ``(conn, address)`` where *conn*
382 is a *new* socket object usable to send and receive data on the connection,
383 and *address* is the address bound to the socket on the other end of the
384 connection.
385
386 This method returns a :ref:`coroutine object <coroutine>`.
387
388 .. seealso::
389
390 The :meth:`BaseEventLoop.create_server` method, the :func:`start_server`
391 function and the :meth:`socket.socket.accept` method.
392
393
394Resolve host name
395-----------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100396
397.. method:: BaseEventLoop.getaddrinfo(host, port, \*, family=0, type=0, proto=0, flags=0)
398
Victor Stinnerc1567df2014-02-08 23:22:58 +0100399 Similar to the :meth:`socket.getaddrinfo` function, but return a
400 :ref:`coroutine object <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100401
402.. method:: BaseEventLoop.getnameinfo(sockaddr, flags=0)
403
Victor Stinnerc1567df2014-02-08 23:22:58 +0100404 Similar to the :meth:`socket.getnameinfo` function, but return a
405 :ref:`coroutine object <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100406
407
408Running subprocesses
409--------------------
410
411Run subprocesses asynchronously using the :mod:`subprocess` module.
412
Victor Stinner041ff9b2014-01-28 02:24:22 +0100413.. note::
414
415 On Windows, the default event loop uses
416 :class:`selectors.SelectSelector` which only supports sockets. The
Victor Stinner45b27ed2014-02-01 02:36:43 +0100417 :class:`ProactorEventLoop` should be used to support subprocesses.
Victor Stinner041ff9b2014-01-28 02:24:22 +0100418
419.. note::
420
Ned Deilyeecbbad2014-01-27 19:03:07 -0700421 On Mac OS X older than 10.9 (Mavericks), :class:`selectors.KqueueSelector`
Victor Stinner041ff9b2014-01-28 02:24:22 +0100422 does not support character devices like PTY, whereas it is used by the
423 default event loop. The :class:`SelectorEventLoop` can be used with
Victor Stinner3bc647c2014-02-03 00:35:46 +0100424 :class:`SelectSelector` or :class:`PollSelector` to handle character devices
425 on Mac OS X 10.6 (Snow Leopard) and later.
Victor Stinner041ff9b2014-01-28 02:24:22 +0100426
Victor Stinnerea3183f2013-12-03 01:08:00 +0100427.. method:: BaseEventLoop.subprocess_exec(protocol_factory, \*args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=False, shell=False, bufsize=0, \*\*kwargs)
428
429 XXX
430
Victor Stinner59759ff2014-01-16 19:30:21 +0100431 This method returns a :ref:`coroutine object <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100432
433 See the constructor of the :class:`subprocess.Popen` class for parameters.
434
435.. method:: BaseEventLoop.subprocess_shell(protocol_factory, cmd, \*, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=False, shell=True, bufsize=0, \*\*kwargs)
436
437 XXX
438
Victor Stinner59759ff2014-01-16 19:30:21 +0100439 This method returns a :ref:`coroutine object <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100440
441 See the constructor of the :class:`subprocess.Popen` class for parameters.
442
443.. method:: BaseEventLoop.connect_read_pipe(protocol_factory, pipe)
444
445 Register read pipe in eventloop.
446
447 *protocol_factory* should instantiate object with :class:`Protocol`
448 interface. pipe is file-like object already switched to nonblocking.
449 Return pair (transport, protocol), where transport support
450 :class:`ReadTransport` interface.
451
Victor Stinner59759ff2014-01-16 19:30:21 +0100452 This method returns a :ref:`coroutine object <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100453
454.. method:: BaseEventLoop.connect_write_pipe(protocol_factory, pipe)
455
456 Register write pipe in eventloop.
457
458 *protocol_factory* should instantiate object with :class:`BaseProtocol`
459 interface. Pipe is file-like object already switched to nonblocking.
460 Return pair (transport, protocol), where transport support
461 :class:`WriteTransport` interface.
462
Victor Stinner59759ff2014-01-16 19:30:21 +0100463 This method returns a :ref:`coroutine object <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100464
Victor Stinner08444382014-02-02 22:43:39 +0100465.. seealso::
466
467 The :func:`create_subprocess_exec` and :func:`create_subprocess_shell`
468 functions.
469
Victor Stinnerea3183f2013-12-03 01:08:00 +0100470
Victor Stinner8b863482014-01-27 10:07:50 +0100471UNIX signals
472------------
473
474Availability: UNIX only.
475
476.. method:: BaseEventLoop.add_signal_handler(signum, callback, \*args)
477
478 Add a handler for a signal.
479
480 Raise :exc:`ValueError` if the signal number is invalid or uncatchable.
481 Raise :exc:`RuntimeError` if there is a problem setting up the handler.
482
483.. method:: BaseEventLoop.remove_signal_handler(sig)
484
485 Remove a handler for a signal.
486
487 Return ``True`` if a signal handler was removed, ``False`` if not.
488
489.. seealso::
490
491 The :mod:`signal` module.
492
493
Victor Stinnerea3183f2013-12-03 01:08:00 +0100494Executor
495--------
496
497Call a function in an :class:`~concurrent.futures.Executor` (pool of threads or
498pool of processes). By default, an event loop uses a thread pool executor
499(:class:`~concurrent.futures.ThreadPoolExecutor`).
500
501.. method:: BaseEventLoop.run_in_executor(executor, callback, \*args)
502
503 Arrange for a callback to be called in the specified executor.
504
505 *executor* is a :class:`~concurrent.futures.Executor` instance,
506 the default executor is used if *executor* is ``None``.
507
508.. method:: BaseEventLoop.set_default_executor(executor)
509
510 Set the default executor used by :meth:`run_in_executor`.
511
512
Victor Stinner8c462c52014-01-24 18:11:43 +0100513Server
514------
515
516.. class:: AbstractServer
517
518 Abstract server returned by :func:`BaseEventLoop.create_server`.
519
520 .. method:: close()
521
522 Stop serving. This leaves existing connections open.
523
524 .. method:: wait_closed()
525
526 Coroutine to wait until service is closed.
527
528
Victor Stinner3e09e322013-12-03 01:22:06 +0100529.. _asyncio-hello-world-callback:
Victor Stinnerea3183f2013-12-03 01:08:00 +0100530
Victor Stinner3e09e322013-12-03 01:22:06 +0100531Example: Hello World (callback)
532-------------------------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100533
534Print ``Hello World`` every two seconds, using a callback::
535
536 import asyncio
537
538 def print_and_repeat(loop):
539 print('Hello World')
540 loop.call_later(2, print_and_repeat, loop)
541
542 loop = asyncio.get_event_loop()
Victor Stinnerdbd89502013-12-10 02:47:22 +0100543 loop.call_soon(print_and_repeat, loop)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100544 loop.run_forever()
545
Victor Stinner3e09e322013-12-03 01:22:06 +0100546.. seealso::
Victor Stinnerea3183f2013-12-03 01:08:00 +0100547
Victor Stinner3e09e322013-12-03 01:22:06 +0100548 :ref:`Hello World example using a coroutine <asyncio-hello-world-coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100549
Victor Stinner8b863482014-01-27 10:07:50 +0100550
551Example: Set signal handlers for SIGINT and SIGTERM
552---------------------------------------------------
553
554Register handlers for signals :py:data:`SIGINT` and :py:data:`SIGTERM`::
555
556 import asyncio
557 import functools
558 import os
559 import signal
560
561 def ask_exit(signame):
562 print("got signal %s: exit" % signame)
563 loop.stop()
564
565 loop = asyncio.get_event_loop()
566 for signame in ('SIGINT', 'SIGTERM'):
567 loop.add_signal_handler(getattr(signal, signame),
568 functools.partial(ask_exit, signame))
569
570 print("Event loop running forever, press CTRL+c to interrupt.")
571 print("pid %s: send SIGINT or SIGTERM to exit." % os.getpid())
572 loop.run_forever()
573