blob: 7760fcb168e6d376bbdb0b569c1249636107a359 [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
Victor Stinner1b0580b2014-02-13 09:24:37 +0100369 The *address* must be already resolved to avoid the trap of hanging the
370 entire event loop when the address requires doing a DNS lookup. For
371 example, it must be an IP address, not an hostname, for
372 :py:data:`~socket.AF_INET` and :py:data:`~socket.AF_INET6` address families.
373 Use :meth:`getaddrinfo` to resolve the hostname asynchronously.
374
Victor Stinnerc1567df2014-02-08 23:22:58 +0100375 This method returns a :ref:`coroutine object <coroutine>`.
376
377 .. seealso::
378
379 The :meth:`BaseEventLoop.create_connection` method, the
380 :func:`open_connection` function and the :meth:`socket.socket.connect`
381 method.
382
383
384.. method:: BaseEventLoop.sock_accept(sock)
385
386 Accept a connection. The socket must be bound to an address and listening
387 for connections. The return value is a pair ``(conn, address)`` where *conn*
388 is a *new* socket object usable to send and receive data on the connection,
389 and *address* is the address bound to the socket on the other end of the
390 connection.
391
392 This method returns a :ref:`coroutine object <coroutine>`.
393
394 .. seealso::
395
396 The :meth:`BaseEventLoop.create_server` method, the :func:`start_server`
397 function and the :meth:`socket.socket.accept` method.
398
399
400Resolve host name
401-----------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100402
403.. method:: BaseEventLoop.getaddrinfo(host, port, \*, family=0, type=0, proto=0, flags=0)
404
Victor Stinnerc1567df2014-02-08 23:22:58 +0100405 Similar to the :meth:`socket.getaddrinfo` function, but return a
406 :ref:`coroutine object <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100407
408.. method:: BaseEventLoop.getnameinfo(sockaddr, flags=0)
409
Victor Stinnerc1567df2014-02-08 23:22:58 +0100410 Similar to the :meth:`socket.getnameinfo` function, but return a
411 :ref:`coroutine object <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100412
413
414Running subprocesses
415--------------------
416
417Run subprocesses asynchronously using the :mod:`subprocess` module.
418
Victor Stinner041ff9b2014-01-28 02:24:22 +0100419.. note::
420
421 On Windows, the default event loop uses
422 :class:`selectors.SelectSelector` which only supports sockets. The
Victor Stinner45b27ed2014-02-01 02:36:43 +0100423 :class:`ProactorEventLoop` should be used to support subprocesses.
Victor Stinner041ff9b2014-01-28 02:24:22 +0100424
425.. note::
426
Ned Deilyeecbbad2014-01-27 19:03:07 -0700427 On Mac OS X older than 10.9 (Mavericks), :class:`selectors.KqueueSelector`
Victor Stinner041ff9b2014-01-28 02:24:22 +0100428 does not support character devices like PTY, whereas it is used by the
429 default event loop. The :class:`SelectorEventLoop` can be used with
Victor Stinner3bc647c2014-02-03 00:35:46 +0100430 :class:`SelectSelector` or :class:`PollSelector` to handle character devices
431 on Mac OS X 10.6 (Snow Leopard) and later.
Victor Stinner041ff9b2014-01-28 02:24:22 +0100432
Victor Stinnerea3183f2013-12-03 01:08:00 +0100433.. method:: BaseEventLoop.subprocess_exec(protocol_factory, \*args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=False, shell=False, bufsize=0, \*\*kwargs)
434
435 XXX
436
Victor Stinner59759ff2014-01-16 19:30:21 +0100437 This method returns a :ref:`coroutine object <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100438
439 See the constructor of the :class:`subprocess.Popen` class for parameters.
440
441.. method:: BaseEventLoop.subprocess_shell(protocol_factory, cmd, \*, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=False, shell=True, bufsize=0, \*\*kwargs)
442
443 XXX
444
Victor Stinner59759ff2014-01-16 19:30:21 +0100445 This method returns a :ref:`coroutine object <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100446
447 See the constructor of the :class:`subprocess.Popen` class for parameters.
448
449.. method:: BaseEventLoop.connect_read_pipe(protocol_factory, pipe)
450
451 Register read pipe in eventloop.
452
453 *protocol_factory* should instantiate object with :class:`Protocol`
454 interface. pipe is file-like object already switched to nonblocking.
455 Return pair (transport, protocol), where transport support
456 :class:`ReadTransport` interface.
457
Victor Stinner59759ff2014-01-16 19:30:21 +0100458 This method returns a :ref:`coroutine object <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100459
460.. method:: BaseEventLoop.connect_write_pipe(protocol_factory, pipe)
461
462 Register write pipe in eventloop.
463
464 *protocol_factory* should instantiate object with :class:`BaseProtocol`
465 interface. Pipe is file-like object already switched to nonblocking.
466 Return pair (transport, protocol), where transport support
467 :class:`WriteTransport` interface.
468
Victor Stinner59759ff2014-01-16 19:30:21 +0100469 This method returns a :ref:`coroutine object <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100470
Victor Stinner08444382014-02-02 22:43:39 +0100471.. seealso::
472
473 The :func:`create_subprocess_exec` and :func:`create_subprocess_shell`
474 functions.
475
Victor Stinnerea3183f2013-12-03 01:08:00 +0100476
Victor Stinner8b863482014-01-27 10:07:50 +0100477UNIX signals
478------------
479
480Availability: UNIX only.
481
482.. method:: BaseEventLoop.add_signal_handler(signum, callback, \*args)
483
484 Add a handler for a signal.
485
486 Raise :exc:`ValueError` if the signal number is invalid or uncatchable.
487 Raise :exc:`RuntimeError` if there is a problem setting up the handler.
488
489.. method:: BaseEventLoop.remove_signal_handler(sig)
490
491 Remove a handler for a signal.
492
493 Return ``True`` if a signal handler was removed, ``False`` if not.
494
495.. seealso::
496
497 The :mod:`signal` module.
498
499
Victor Stinnerea3183f2013-12-03 01:08:00 +0100500Executor
501--------
502
503Call a function in an :class:`~concurrent.futures.Executor` (pool of threads or
504pool of processes). By default, an event loop uses a thread pool executor
505(:class:`~concurrent.futures.ThreadPoolExecutor`).
506
507.. method:: BaseEventLoop.run_in_executor(executor, callback, \*args)
508
509 Arrange for a callback to be called in the specified executor.
510
511 *executor* is a :class:`~concurrent.futures.Executor` instance,
512 the default executor is used if *executor* is ``None``.
513
514.. method:: BaseEventLoop.set_default_executor(executor)
515
516 Set the default executor used by :meth:`run_in_executor`.
517
518
Victor Stinner8c462c52014-01-24 18:11:43 +0100519Server
520------
521
522.. class:: AbstractServer
523
524 Abstract server returned by :func:`BaseEventLoop.create_server`.
525
526 .. method:: close()
527
528 Stop serving. This leaves existing connections open.
529
530 .. method:: wait_closed()
531
532 Coroutine to wait until service is closed.
533
534
Victor Stinner3e09e322013-12-03 01:22:06 +0100535.. _asyncio-hello-world-callback:
Victor Stinnerea3183f2013-12-03 01:08:00 +0100536
Victor Stinner3e09e322013-12-03 01:22:06 +0100537Example: Hello World (callback)
538-------------------------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100539
540Print ``Hello World`` every two seconds, using a callback::
541
542 import asyncio
543
544 def print_and_repeat(loop):
545 print('Hello World')
546 loop.call_later(2, print_and_repeat, loop)
547
548 loop = asyncio.get_event_loop()
Victor Stinnerdbd89502013-12-10 02:47:22 +0100549 loop.call_soon(print_and_repeat, loop)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100550 loop.run_forever()
551
Victor Stinner3e09e322013-12-03 01:22:06 +0100552.. seealso::
Victor Stinnerea3183f2013-12-03 01:08:00 +0100553
Victor Stinner3e09e322013-12-03 01:22:06 +0100554 :ref:`Hello World example using a coroutine <asyncio-hello-world-coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100555
Victor Stinner8b863482014-01-27 10:07:50 +0100556
557Example: Set signal handlers for SIGINT and SIGTERM
558---------------------------------------------------
559
560Register handlers for signals :py:data:`SIGINT` and :py:data:`SIGTERM`::
561
562 import asyncio
563 import functools
564 import os
565 import signal
566
567 def ask_exit(signame):
568 print("got signal %s: exit" % signame)
569 loop.stop()
570
571 loop = asyncio.get_event_loop()
572 for signame in ('SIGINT', 'SIGTERM'):
573 loop.add_signal_handler(getattr(signal, signame),
574 functools.partial(ask_exit, signame))
575
576 print("Event loop running forever, press CTRL+c to interrupt.")
577 print("pid %s: send SIGINT or SIGTERM to exit." % os.getpid())
578 loop.run_forever()
579