blob: b2c48024b54052de24787bb07754b720c92d40e6 [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
204 *port*. *protocol_factory* must be a callable returning a
Victor Stinner9592edb2014-02-02 15:03:02 +0100205 :ref:`protocol <asyncio-protocol>` instance.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100206
Victor Stinner59759ff2014-01-16 19:30:21 +0100207 This method returns a :ref:`coroutine object <coroutine>` which will try to
Victor Stinnerea3183f2013-12-03 01:08:00 +0100208 establish the connection in the background. When successful, the
209 coroutine returns a ``(transport, protocol)`` pair.
210
211 The chronological synopsis of the underlying operation is as follows:
212
Victor Stinner9592edb2014-02-02 15:03:02 +0100213 #. The connection is established, and a :ref:`transport <asyncio-transport>`
Victor Stinnerea3183f2013-12-03 01:08:00 +0100214 is created to represent it.
215
216 #. *protocol_factory* is called without arguments and must return a
Victor Stinner9592edb2014-02-02 15:03:02 +0100217 :ref:`protocol <asyncio-protocol>` instance.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100218
219 #. The protocol instance is tied to the transport, and its
220 :meth:`connection_made` method is called.
221
222 #. The coroutine returns successfully with the ``(transport, protocol)``
223 pair.
224
225 The created transport is an implementation-dependent bidirectional stream.
226
227 .. note::
228 *protocol_factory* can be any kind of callable, not necessarily
229 a class. For example, if you want to use a pre-created
230 protocol instance, you can pass ``lambda: my_protocol``.
231
232 Options allowing to change how the connection is created:
233
234 * *ssl*: if given and not false, a SSL/TLS transport is created
235 (by default a plain TCP transport is created). If *ssl* is
236 a :class:`ssl.SSLContext` object, this context is used to create
237 the transport; if *ssl* is :const:`True`, a context with some
238 unspecified default settings is used.
239
240 * *server_hostname*, is only for use together with *ssl*,
241 and sets or overrides the hostname that the target server's certificate
242 will be matched against. By default the value of the *host* argument
243 is used. If *host* is empty, there is no default and you must pass a
244 value for *server_hostname*. If *server_hostname* is an empty
245 string, hostname matching is disabled (which is a serious security
246 risk, allowing for man-in-the-middle-attacks).
247
248 * *family*, *proto*, *flags* are the optional address family, protocol
249 and flags to be passed through to getaddrinfo() for *host* resolution.
250 If given, these should all be integers from the corresponding
251 :mod:`socket` module constants.
252
253 * *sock*, if given, should be an existing, already connected
254 :class:`socket.socket` object to be used by the transport.
255 If *sock* is given, none of *host*, *port*, *family*, *proto*, *flags*
256 and *local_addr* should be specified.
257
258 * *local_addr*, if given, is a ``(local_host, local_port)`` tuple used
259 to bind the socket to locally. The *local_host* and *local_port*
260 are looked up using getaddrinfo(), similarly to *host* and *port*.
261
Victor Stinnerc8ea8132014-01-23 11:02:09 +0100262 .. seealso::
263
264 The :func:`open_connection` function can be used to get a pair of
265 (:class:`StreamReader`, :class:`StreamWriter`) instead of a protocol.
266
Victor Stinnerea3183f2013-12-03 01:08:00 +0100267
268Creating listening connections
269------------------------------
270
271.. 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)
272
Victor Stinner59759ff2014-01-16 19:30:21 +0100273 A :ref:`coroutine function <coroutine>` which creates a TCP server bound to host and
Victor Stinnerea3183f2013-12-03 01:08:00 +0100274 port.
275
276 The return value is a :class:`AbstractServer` object which can be used to stop
277 the service.
278
279 If *host* is an empty string or None all interfaces are assumed
280 and a list of multiple sockets will be returned (most likely
281 one for IPv4 and another one for IPv6).
282
283 *family* can be set to either :data:`~socket.AF_INET` or
284 :data:`~socket.AF_INET6` to force the socket to use IPv4 or IPv6. If not set
285 it will be determined from host (defaults to :data:`~socket.AF_UNSPEC`).
286
287 *flags* is a bitmask for :meth:`getaddrinfo`.
288
289 *sock* can optionally be specified in order to use a preexisting
290 socket object.
291
292 *backlog* is the maximum number of queued connections passed to
293 :meth:`~socket.socket.listen` (defaults to 100).
294
295 ssl can be set to an :class:`~ssl.SSLContext` to enable SSL over the
296 accepted connections.
297
298 *reuse_address* tells the kernel to reuse a local socket in
299 TIME_WAIT state, without waiting for its natural timeout to
300 expire. If not specified will automatically be set to True on
301 UNIX.
302
Victor Stinner59759ff2014-01-16 19:30:21 +0100303 This method returns a :ref:`coroutine object <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100304
Victor Stinnerc8ea8132014-01-23 11:02:09 +0100305 .. seealso::
306
307 The function :func:`start_server` creates a (:class:`StreamReader`,
308 :class:`StreamWriter`) pair and calls back a function with this pair.
309
Victor Stinnerea3183f2013-12-03 01:08:00 +0100310.. method:: BaseEventLoop.create_datagram_endpoint(protocol_factory, local_addr=None, remote_addr=None, \*, family=0, proto=0, flags=0)
311
312 Create datagram connection.
313
Victor Stinner59759ff2014-01-16 19:30:21 +0100314 This method returns a :ref:`coroutine object <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100315
316
317
Victor Stinnerc1567df2014-02-08 23:22:58 +0100318Watch file descriptors
319----------------------
320
321.. method:: BaseEventLoop.add_reader(fd, callback, \*args)
322
323 Start watching the file descriptor for read availability and then call the
324 *callback* with specified arguments.
325
326.. method:: BaseEventLoop.remove_reader(fd)
327
328 Stop watching the file descriptor for read availability.
329
330.. method:: BaseEventLoop.add_writer(fd, callback, \*args)
331
332 Start watching the file descriptor for write availability and then call the
333 *callback* with specified arguments.
334
335.. method:: BaseEventLoop.remove_writer(fd)
336
337 Stop watching the file descriptor for write availability.
338
339
340Low-level socket operations
341---------------------------
342
343.. method:: BaseEventLoop.sock_recv(sock, nbytes)
344
345 Receive data from the socket. The return value is a bytes object
346 representing the data received. The maximum amount of data to be received
347 at once is specified by *nbytes*.
348
349 This method returns a :ref:`coroutine object <coroutine>`.
350
351 .. seealso::
352
353 The :meth:`socket.socket.recv` method.
354
355.. method:: BaseEventLoop.sock_sendall(sock, data)
356
357 Send data to the socket. The socket must be connected to a remote socket.
358 This method continues to send data from *data* until either all data has
359 been sent or an error occurs. ``None`` is returned on success. On error,
360 an exception is raised, and there is no way to determine how much data, if
361 any, was successfully sent.
362
363 This method returns a :ref:`coroutine object <coroutine>`.
364
365 .. seealso::
366
367 The :meth:`socket.socket.sendall` method.
368
369.. method:: BaseEventLoop.sock_connect(sock, address)
370
371 Connect to a remote socket at *address*.
372
Victor Stinner28773462014-02-13 09:24:37 +0100373 The *address* must be already resolved to avoid the trap of hanging the
374 entire event loop when the address requires doing a DNS lookup. For
375 example, it must be an IP address, not an hostname, for
376 :py:data:`~socket.AF_INET` and :py:data:`~socket.AF_INET6` address families.
377 Use :meth:`getaddrinfo` to resolve the hostname asynchronously.
378
Victor Stinnerc1567df2014-02-08 23:22:58 +0100379 This method returns a :ref:`coroutine object <coroutine>`.
380
381 .. seealso::
382
383 The :meth:`BaseEventLoop.create_connection` method, the
384 :func:`open_connection` function and the :meth:`socket.socket.connect`
385 method.
386
387
388.. method:: BaseEventLoop.sock_accept(sock)
389
390 Accept a connection. The socket must be bound to an address and listening
391 for connections. The return value is a pair ``(conn, address)`` where *conn*
392 is a *new* socket object usable to send and receive data on the connection,
393 and *address* is the address bound to the socket on the other end of the
394 connection.
395
396 This method returns a :ref:`coroutine object <coroutine>`.
397
398 .. seealso::
399
400 The :meth:`BaseEventLoop.create_server` method, the :func:`start_server`
401 function and the :meth:`socket.socket.accept` method.
402
403
404Resolve host name
405-----------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100406
407.. method:: BaseEventLoop.getaddrinfo(host, port, \*, family=0, type=0, proto=0, flags=0)
408
Victor Stinnerc1567df2014-02-08 23:22:58 +0100409 Similar to the :meth:`socket.getaddrinfo` function, but return a
410 :ref:`coroutine object <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100411
412.. method:: BaseEventLoop.getnameinfo(sockaddr, flags=0)
413
Victor Stinnerc1567df2014-02-08 23:22:58 +0100414 Similar to the :meth:`socket.getnameinfo` function, but return a
415 :ref:`coroutine object <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100416
417
418Running subprocesses
419--------------------
420
421Run subprocesses asynchronously using the :mod:`subprocess` module.
422
Victor Stinner041ff9b2014-01-28 02:24:22 +0100423.. note::
424
425 On Windows, the default event loop uses
426 :class:`selectors.SelectSelector` which only supports sockets. The
Victor Stinner45b27ed2014-02-01 02:36:43 +0100427 :class:`ProactorEventLoop` should be used to support subprocesses.
Victor Stinner041ff9b2014-01-28 02:24:22 +0100428
429.. note::
430
Ned Deilyeecbbad2014-01-27 19:03:07 -0700431 On Mac OS X older than 10.9 (Mavericks), :class:`selectors.KqueueSelector`
Victor Stinner041ff9b2014-01-28 02:24:22 +0100432 does not support character devices like PTY, whereas it is used by the
433 default event loop. The :class:`SelectorEventLoop` can be used with
Victor Stinner3bc647c2014-02-03 00:35:46 +0100434 :class:`SelectSelector` or :class:`PollSelector` to handle character devices
435 on Mac OS X 10.6 (Snow Leopard) and later.
Victor Stinner041ff9b2014-01-28 02:24:22 +0100436
Victor Stinnerea3183f2013-12-03 01:08:00 +0100437.. method:: BaseEventLoop.subprocess_exec(protocol_factory, \*args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=False, shell=False, bufsize=0, \*\*kwargs)
438
439 XXX
440
Victor Stinner59759ff2014-01-16 19:30:21 +0100441 This method returns a :ref:`coroutine object <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100442
443 See the constructor of the :class:`subprocess.Popen` class for parameters.
444
445.. method:: BaseEventLoop.subprocess_shell(protocol_factory, cmd, \*, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=False, shell=True, bufsize=0, \*\*kwargs)
446
447 XXX
448
Victor Stinner59759ff2014-01-16 19:30:21 +0100449 This method returns a :ref:`coroutine object <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100450
451 See the constructor of the :class:`subprocess.Popen` class for parameters.
452
453.. method:: BaseEventLoop.connect_read_pipe(protocol_factory, pipe)
454
455 Register read pipe in eventloop.
456
457 *protocol_factory* should instantiate object with :class:`Protocol`
458 interface. pipe is file-like object already switched to nonblocking.
459 Return pair (transport, protocol), where transport support
460 :class:`ReadTransport` interface.
461
Victor Stinner59759ff2014-01-16 19:30:21 +0100462 This method returns a :ref:`coroutine object <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100463
464.. method:: BaseEventLoop.connect_write_pipe(protocol_factory, pipe)
465
466 Register write pipe in eventloop.
467
468 *protocol_factory* should instantiate object with :class:`BaseProtocol`
469 interface. Pipe is file-like object already switched to nonblocking.
470 Return pair (transport, protocol), where transport support
471 :class:`WriteTransport` interface.
472
Victor Stinner59759ff2014-01-16 19:30:21 +0100473 This method returns a :ref:`coroutine object <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100474
Victor Stinner08444382014-02-02 22:43:39 +0100475.. seealso::
476
477 The :func:`create_subprocess_exec` and :func:`create_subprocess_shell`
478 functions.
479
Victor Stinnerea3183f2013-12-03 01:08:00 +0100480
Victor Stinner8b863482014-01-27 10:07:50 +0100481UNIX signals
482------------
483
484Availability: UNIX only.
485
486.. method:: BaseEventLoop.add_signal_handler(signum, callback, \*args)
487
488 Add a handler for a signal.
489
490 Raise :exc:`ValueError` if the signal number is invalid or uncatchable.
491 Raise :exc:`RuntimeError` if there is a problem setting up the handler.
492
493.. method:: BaseEventLoop.remove_signal_handler(sig)
494
495 Remove a handler for a signal.
496
497 Return ``True`` if a signal handler was removed, ``False`` if not.
498
499.. seealso::
500
501 The :mod:`signal` module.
502
503
Victor Stinnerea3183f2013-12-03 01:08:00 +0100504Executor
505--------
506
507Call a function in an :class:`~concurrent.futures.Executor` (pool of threads or
508pool of processes). By default, an event loop uses a thread pool executor
509(:class:`~concurrent.futures.ThreadPoolExecutor`).
510
511.. method:: BaseEventLoop.run_in_executor(executor, callback, \*args)
512
513 Arrange for a callback to be called in the specified executor.
514
515 *executor* is a :class:`~concurrent.futures.Executor` instance,
516 the default executor is used if *executor* is ``None``.
517
518.. method:: BaseEventLoop.set_default_executor(executor)
519
520 Set the default executor used by :meth:`run_in_executor`.
521
522
Victor Stinner8c462c52014-01-24 18:11:43 +0100523Server
524------
525
526.. class:: AbstractServer
527
528 Abstract server returned by :func:`BaseEventLoop.create_server`.
529
530 .. method:: close()
531
532 Stop serving. This leaves existing connections open.
533
534 .. method:: wait_closed()
535
536 Coroutine to wait until service is closed.
537
538
Victor Stinner3e09e322013-12-03 01:22:06 +0100539.. _asyncio-hello-world-callback:
Victor Stinnerea3183f2013-12-03 01:08:00 +0100540
Victor Stinner3e09e322013-12-03 01:22:06 +0100541Example: Hello World (callback)
542-------------------------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100543
544Print ``Hello World`` every two seconds, using a callback::
545
546 import asyncio
547
548 def print_and_repeat(loop):
549 print('Hello World')
550 loop.call_later(2, print_and_repeat, loop)
551
552 loop = asyncio.get_event_loop()
Victor Stinnerdbd89502013-12-10 02:47:22 +0100553 loop.call_soon(print_and_repeat, loop)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100554 loop.run_forever()
555
Victor Stinner3e09e322013-12-03 01:22:06 +0100556.. seealso::
Victor Stinnerea3183f2013-12-03 01:08:00 +0100557
Victor Stinner3e09e322013-12-03 01:22:06 +0100558 :ref:`Hello World example using a coroutine <asyncio-hello-world-coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100559
Victor Stinner8b863482014-01-27 10:07:50 +0100560
561Example: Set signal handlers for SIGINT and SIGTERM
562---------------------------------------------------
563
564Register handlers for signals :py:data:`SIGINT` and :py:data:`SIGTERM`::
565
566 import asyncio
567 import functools
568 import os
569 import signal
570
571 def ask_exit(signame):
572 print("got signal %s: exit" % signame)
573 loop.stop()
574
575 loop = asyncio.get_event_loop()
576 for signame in ('SIGINT', 'SIGTERM'):
577 loop.add_signal_handler(getattr(signal, signame),
578 functools.partial(ask_exit, signame))
579
580 print("Event loop running forever, press CTRL+c to interrupt.")
581 print("pid %s: send SIGINT or SIGTERM to exit." % os.getpid())
582 loop.run_forever()
583