blob: 5cb2f56f7919878e8f9c898298120545c79d6b46 [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
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500105 If the argument is a :ref:`coroutine <coroutine>`, it is wrapped
106 in a :class:`Task`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100107
108 Return the Future's result, or raise its exception.
109
110.. method:: BaseEventLoop.is_running()
111
112 Returns running status of event loop.
113
Victor Stinnerafbf8272013-12-03 02:05:42 +0100114.. method:: BaseEventLoop.stop()
Victor Stinnerea3183f2013-12-03 01:08:00 +0100115
116 Stop running the event loop.
117
118 Every callback scheduled before :meth:`stop` is called will run.
119 Callback scheduled after :meth:`stop` is called won't. However, those
120 callbacks will run if :meth:`run_forever` is called again later.
121
122.. method:: BaseEventLoop.close()
123
124 Close the event loop. The loop should not be running.
125
126 This clears the queues and shuts down the executor, but does not wait for
127 the executor to finish.
128
129 This is idempotent and irreversible. No other methods should be called after
130 this one.
131
132
133Calls
134-----
135
136.. method:: BaseEventLoop.call_soon(callback, \*args)
137
138 Arrange for a callback to be called as soon as possible.
139
140 This operates as a FIFO queue, callbacks are called in the order in
141 which they are registered. Each callback will be called exactly once.
142
143 Any positional arguments after the callback will be passed to the
144 callback when it is called.
145
Yury Selivanov43ee1c12014-02-19 20:58:44 -0500146 An instance of :class:`asyncio.Handle` is returned.
147
Victor Stinnerea3183f2013-12-03 01:08:00 +0100148.. method:: BaseEventLoop.call_soon_threadsafe(callback, \*args)
149
150 Like :meth:`call_soon`, but thread safe.
151
152
Victor Stinner45b27ed2014-02-01 02:36:43 +0100153.. _asyncio-delayed-calls:
154
Victor Stinnerea3183f2013-12-03 01:08:00 +0100155Delayed calls
156-------------
157
158The event loop has its own internal clock for computing timeouts.
159Which clock is used depends on the (platform-specific) event loop
160implementation; ideally it is a monotonic clock. This will generally be
161a different clock than :func:`time.time`.
162
Victor Stinnerfd9d3742014-02-18 09:37:43 +0100163.. note::
164
165 Timeouts (relative *delay* or absolute *when*) should not exceed one day.
166
Victor Stinner45b27ed2014-02-01 02:36:43 +0100167
Victor Stinnerea3183f2013-12-03 01:08:00 +0100168.. method:: BaseEventLoop.call_later(delay, callback, *args)
169
170 Arrange for the *callback* to be called after the given *delay*
171 seconds (either an int or float).
172
Yury Selivanov43ee1c12014-02-19 20:58:44 -0500173 An instance of :class:`asyncio.Handle` is returned.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100174
175 *callback* will be called exactly once per call to :meth:`call_later`.
176 If two callbacks are scheduled for exactly the same time, it is
177 undefined which will be called first.
178
179 The optional positional *args* will be passed to the callback when it
180 is called. If you want the callback to be called with some named
181 arguments, use a closure or :func:`functools.partial`.
182
183.. method:: BaseEventLoop.call_at(when, callback, *args)
184
185 Arrange for the *callback* to be called at the given absolute timestamp
186 *when* (an int or float), using the same time reference as :meth:`time`.
187
188 This method's behavior is the same as :meth:`call_later`.
189
190.. method:: BaseEventLoop.time()
191
192 Return the current time, as a :class:`float` value, according to the
193 event loop's internal clock.
194
Victor Stinner3e09e322013-12-03 01:22:06 +0100195.. seealso::
196
197 The :func:`asyncio.sleep` function.
198
Victor Stinnerea3183f2013-12-03 01:08:00 +0100199
200Creating connections
Victor Stinner0c6f1ca2013-12-03 01:46:39 +0100201--------------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100202
203.. 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)
204
205 Create a streaming transport connection to a given Internet *host* and
Victor Stinnera6919aa2014-02-19 13:32:34 +0100206 *port*: socket family :py:data:`~socket.AF_INET` or
207 :py:data:`~socket.AF_INET6` depending on *host* (or *family* if specified),
208 socket type :py:data:`~socket.SOCK_STREAM`. *protocol_factory* must be a
209 callable returning a :ref:`protocol <asyncio-protocol>` instance.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100210
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500211 This method is a :ref:`coroutine <coroutine>` which will try to
Victor Stinnerea3183f2013-12-03 01:08:00 +0100212 establish the connection in the background. When successful, the
213 coroutine returns a ``(transport, protocol)`` pair.
214
215 The chronological synopsis of the underlying operation is as follows:
216
Victor Stinner9592edb2014-02-02 15:03:02 +0100217 #. The connection is established, and a :ref:`transport <asyncio-transport>`
Victor Stinnerea3183f2013-12-03 01:08:00 +0100218 is created to represent it.
219
220 #. *protocol_factory* is called without arguments and must return a
Victor Stinner9592edb2014-02-02 15:03:02 +0100221 :ref:`protocol <asyncio-protocol>` instance.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100222
223 #. The protocol instance is tied to the transport, and its
224 :meth:`connection_made` method is called.
225
226 #. The coroutine returns successfully with the ``(transport, protocol)``
227 pair.
228
229 The created transport is an implementation-dependent bidirectional stream.
230
231 .. note::
232 *protocol_factory* can be any kind of callable, not necessarily
233 a class. For example, if you want to use a pre-created
234 protocol instance, you can pass ``lambda: my_protocol``.
235
236 Options allowing to change how the connection is created:
237
238 * *ssl*: if given and not false, a SSL/TLS transport is created
239 (by default a plain TCP transport is created). If *ssl* is
240 a :class:`ssl.SSLContext` object, this context is used to create
241 the transport; if *ssl* is :const:`True`, a context with some
242 unspecified default settings is used.
243
Antoine Pitrouc5e075f2014-03-22 18:19:11 +0100244 .. seealso:: :ref:`SSL/TLS security considerations <ssl-security>`
245
Victor Stinnerea3183f2013-12-03 01:08:00 +0100246 * *server_hostname*, is only for use together with *ssl*,
247 and sets or overrides the hostname that the target server's certificate
248 will be matched against. By default the value of the *host* argument
249 is used. If *host* is empty, there is no default and you must pass a
250 value for *server_hostname*. If *server_hostname* is an empty
251 string, hostname matching is disabled (which is a serious security
252 risk, allowing for man-in-the-middle-attacks).
253
254 * *family*, *proto*, *flags* are the optional address family, protocol
255 and flags to be passed through to getaddrinfo() for *host* resolution.
256 If given, these should all be integers from the corresponding
257 :mod:`socket` module constants.
258
259 * *sock*, if given, should be an existing, already connected
260 :class:`socket.socket` object to be used by the transport.
261 If *sock* is given, none of *host*, *port*, *family*, *proto*, *flags*
262 and *local_addr* should be specified.
263
264 * *local_addr*, if given, is a ``(local_host, local_port)`` tuple used
265 to bind the socket to locally. The *local_host* and *local_port*
266 are looked up using getaddrinfo(), similarly to *host* and *port*.
267
Victor Stinnerc8ea8132014-01-23 11:02:09 +0100268 .. seealso::
269
270 The :func:`open_connection` function can be used to get a pair of
271 (:class:`StreamReader`, :class:`StreamWriter`) instead of a protocol.
272
Victor Stinnerea3183f2013-12-03 01:08:00 +0100273
Victor Stinnera6919aa2014-02-19 13:32:34 +0100274.. method:: BaseEventLoop.create_datagram_endpoint(protocol_factory, local_addr=None, remote_addr=None, \*, family=0, proto=0, flags=0)
275
276 Create datagram connection: socket family :py:data:`~socket.AF_INET` or
277 :py:data:`~socket.AF_INET6` depending on *host* (or *family* if specified),
278 socket type :py:data:`~socket.SOCK_DGRAM`.
279
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500280 This method is a :ref:`coroutine <coroutine>` which will try to
Victor Stinnera6919aa2014-02-19 13:32:34 +0100281 establish the connection in the background. When successful, the
282 coroutine returns a ``(transport, protocol)`` pair.
283
284 See the :meth:`BaseEventLoop.create_connection` method for parameters.
285
286
287.. method:: BaseEventLoop.create_unix_connection(protocol_factory, path, \*, ssl=None, sock=None, server_hostname=None)
288
289 Create UNIX connection: socket family :py:data:`~socket.AF_UNIX`, socket
290 type :py:data:`~socket.SOCK_STREAM`. The :py:data:`~socket.AF_UNIX` socket
291 family is used to communicate between processes on the same machine
292 efficiently.
293
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500294 This method is a :ref:`coroutine <coroutine>` which will try to
Victor Stinnera6919aa2014-02-19 13:32:34 +0100295 establish the connection in the background. When successful, the
296 coroutine returns a ``(transport, protocol)`` pair.
297
298 See the :meth:`BaseEventLoop.create_connection` method for parameters.
299
300 Availability: UNIX.
301
302
Victor Stinnerea3183f2013-12-03 01:08:00 +0100303Creating listening connections
304------------------------------
305
306.. 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)
307
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500308 A :ref:`coroutine <coroutine>` method which creates a TCP server bound to
309 host and port.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100310
311 The return value is a :class:`AbstractServer` object which can be used to stop
312 the service.
313
314 If *host* is an empty string or None all interfaces are assumed
315 and a list of multiple sockets will be returned (most likely
316 one for IPv4 and another one for IPv6).
317
318 *family* can be set to either :data:`~socket.AF_INET` or
319 :data:`~socket.AF_INET6` to force the socket to use IPv4 or IPv6. If not set
320 it will be determined from host (defaults to :data:`~socket.AF_UNSPEC`).
321
322 *flags* is a bitmask for :meth:`getaddrinfo`.
323
324 *sock* can optionally be specified in order to use a preexisting
325 socket object.
326
327 *backlog* is the maximum number of queued connections passed to
328 :meth:`~socket.socket.listen` (defaults to 100).
329
330 ssl can be set to an :class:`~ssl.SSLContext` to enable SSL over the
331 accepted connections.
332
333 *reuse_address* tells the kernel to reuse a local socket in
334 TIME_WAIT state, without waiting for its natural timeout to
335 expire. If not specified will automatically be set to True on
336 UNIX.
337
Victor Stinnerc8ea8132014-01-23 11:02:09 +0100338 .. seealso::
339
340 The function :func:`start_server` creates a (:class:`StreamReader`,
341 :class:`StreamWriter`) pair and calls back a function with this pair.
342
Victor Stinnerea3183f2013-12-03 01:08:00 +0100343
Victor Stinnera6919aa2014-02-19 13:32:34 +0100344.. method:: BaseEventLoop.create_unix_server(protocol_factory, path=None, \*, sock=None, backlog=100, ssl=None)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100345
Victor Stinnera6919aa2014-02-19 13:32:34 +0100346 Similar to :meth:`BaseEventLoop.create_server`, but specific to the
347 socket family :py:data:`~socket.AF_UNIX`.
348
349 Availability: UNIX.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100350
351
352
Victor Stinnerc1567df2014-02-08 23:22:58 +0100353Watch file descriptors
354----------------------
355
356.. method:: BaseEventLoop.add_reader(fd, callback, \*args)
357
358 Start watching the file descriptor for read availability and then call the
359 *callback* with specified arguments.
360
361.. method:: BaseEventLoop.remove_reader(fd)
362
363 Stop watching the file descriptor for read availability.
364
365.. method:: BaseEventLoop.add_writer(fd, callback, \*args)
366
367 Start watching the file descriptor for write availability and then call the
368 *callback* with specified arguments.
369
370.. method:: BaseEventLoop.remove_writer(fd)
371
372 Stop watching the file descriptor for write availability.
373
374
375Low-level socket operations
376---------------------------
377
378.. method:: BaseEventLoop.sock_recv(sock, nbytes)
379
380 Receive data from the socket. The return value is a bytes object
381 representing the data received. The maximum amount of data to be received
382 at once is specified by *nbytes*.
383
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500384 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100385
386 .. seealso::
387
388 The :meth:`socket.socket.recv` method.
389
390.. method:: BaseEventLoop.sock_sendall(sock, data)
391
392 Send data to the socket. The socket must be connected to a remote socket.
393 This method continues to send data from *data* until either all data has
394 been sent or an error occurs. ``None`` is returned on success. On error,
395 an exception is raised, and there is no way to determine how much data, if
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500396 any, was successfully processed by the receiving end of the connection.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100397
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500398 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100399
400 .. seealso::
401
402 The :meth:`socket.socket.sendall` method.
403
404.. method:: BaseEventLoop.sock_connect(sock, address)
405
406 Connect to a remote socket at *address*.
407
Victor Stinner1b0580b2014-02-13 09:24:37 +0100408 The *address* must be already resolved to avoid the trap of hanging the
409 entire event loop when the address requires doing a DNS lookup. For
410 example, it must be an IP address, not an hostname, for
411 :py:data:`~socket.AF_INET` and :py:data:`~socket.AF_INET6` address families.
412 Use :meth:`getaddrinfo` to resolve the hostname asynchronously.
413
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500414 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100415
416 .. seealso::
417
418 The :meth:`BaseEventLoop.create_connection` method, the
419 :func:`open_connection` function and the :meth:`socket.socket.connect`
420 method.
421
422
423.. method:: BaseEventLoop.sock_accept(sock)
424
425 Accept a connection. The socket must be bound to an address and listening
426 for connections. The return value is a pair ``(conn, address)`` where *conn*
427 is a *new* socket object usable to send and receive data on the connection,
428 and *address* is the address bound to the socket on the other end of the
429 connection.
430
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500431 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100432
433 .. seealso::
434
435 The :meth:`BaseEventLoop.create_server` method, the :func:`start_server`
436 function and the :meth:`socket.socket.accept` method.
437
438
439Resolve host name
440-----------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100441
442.. method:: BaseEventLoop.getaddrinfo(host, port, \*, family=0, type=0, proto=0, flags=0)
443
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500444 This method is a :ref:`coroutine <coroutine>`, similar to
445 :meth:`socket.getaddrinfo` function but non-blocking.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100446
447.. method:: BaseEventLoop.getnameinfo(sockaddr, flags=0)
448
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500449 This method is a :ref:`coroutine <coroutine>`, similar to
450 :meth:`socket.getnameinfo` function but non-blocking.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100451
452
453Running subprocesses
454--------------------
455
456Run subprocesses asynchronously using the :mod:`subprocess` module.
457
Victor Stinner041ff9b2014-01-28 02:24:22 +0100458.. note::
459
460 On Windows, the default event loop uses
461 :class:`selectors.SelectSelector` which only supports sockets. The
Victor Stinner45b27ed2014-02-01 02:36:43 +0100462 :class:`ProactorEventLoop` should be used to support subprocesses.
Victor Stinner041ff9b2014-01-28 02:24:22 +0100463
464.. note::
465
Ned Deilyeecbbad2014-01-27 19:03:07 -0700466 On Mac OS X older than 10.9 (Mavericks), :class:`selectors.KqueueSelector`
Victor Stinner041ff9b2014-01-28 02:24:22 +0100467 does not support character devices like PTY, whereas it is used by the
468 default event loop. The :class:`SelectorEventLoop` can be used with
Victor Stinner3bc647c2014-02-03 00:35:46 +0100469 :class:`SelectSelector` or :class:`PollSelector` to handle character devices
470 on Mac OS X 10.6 (Snow Leopard) and later.
Victor Stinner041ff9b2014-01-28 02:24:22 +0100471
Yury Selivanov53281b12014-02-20 20:10:28 -0500472.. method:: BaseEventLoop.subprocess_exec(protocol_factory, \*args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, \*\*kwargs)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100473
Yury Selivanov53281b12014-02-20 20:10:28 -0500474 Create a subprocess from one or more string arguments, where the first string
475 specifies the program to execute, and the remaining strings specify the
476 program's arguments. (Thus, together the string arguments form the
477 ``sys.argv`` value of the program, assuming it is a Python script.) This is
478 similar to the standard library :class:`subprocess.Popen` class called with
479 shell=False and the list of strings passed as the first argument;
480 however, where :class:`~subprocess.Popen` takes a single argument which is
481 list of strings, :func:`subprocess_exec` takes multiple string arguments.
482
483 Other parameters:
484
485 * *stdin*: Either a file-like object representing the pipe to be connected
486 to the subprocess's standard input stream using
487 :meth:`~BaseEventLoop.connect_write_pipe`, or the constant
488 :const:`subprocess.PIPE` (the default). By default a new pipe will be
489 created and connected.
490
491 * *stdout*: Either a file-like object representing the pipe to be connected
492 to the subprocess's standard output stream using
Larry Hastings3732ed22014-03-15 21:13:56 -0700493 :meth:`~BaseEventLoop.connect_read_pipe`, or the constant
Yury Selivanov53281b12014-02-20 20:10:28 -0500494 :const:`subprocess.PIPE` (the default). By default a new pipe will be
495 created and connected.
496
497 * *stderr*: Either a file-like object representing the pipe to be connected
498 to the subprocess's standard error stream using
499 :meth:`~BaseEventLoop.connect_read_pipe`, or one of the constants
500 :const:`subprocess.PIPE` (the default) or :const:`subprocess.STDOUT`.
501 By default a new pipe will be created and connected. When
502 :const:`subprocess.STDOUT` is specified, the subprocess's standard error
503 stream will be connected to the same pipe as the standard output stream.
504
505 * All other keyword arguments are passed to :class:`subprocess.Popen`
506 without interpretation, except for *bufsize*, *universal_newlines* and
507 *shell*, which should not be specified at all.
508
509 Returns a pair of ``(transport, protocol)``, where *transport* is an
510 instance of :class:`BaseSubprocessTransport`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100511
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500512 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100513
514 See the constructor of the :class:`subprocess.Popen` class for parameters.
515
Yury Selivanov53281b12014-02-20 20:10:28 -0500516.. method:: BaseEventLoop.subprocess_shell(protocol_factory, cmd, \*, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, \*\*kwargs)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100517
Yury Selivanov53281b12014-02-20 20:10:28 -0500518 Create a subprocess from *cmd*, which is a string using the platform's
519 "shell" syntax. This is similar to the standard library
520 :class:`subprocess.Popen` class called with ``shell=True``.
521
522 See :meth:`~BaseEventLoop.subprocess_exec` for more details about
523 the remaining arguments.
524
525 Returns a pair of ``(transport, protocol)``, where *transport* is an
526 instance of :class:`BaseSubprocessTransport`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100527
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500528 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100529
530 See the constructor of the :class:`subprocess.Popen` class for parameters.
531
532.. method:: BaseEventLoop.connect_read_pipe(protocol_factory, pipe)
533
534 Register read pipe in eventloop.
535
536 *protocol_factory* should instantiate object with :class:`Protocol`
537 interface. pipe is file-like object already switched to nonblocking.
538 Return pair (transport, protocol), where transport support
539 :class:`ReadTransport` interface.
540
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500541 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100542
543.. method:: BaseEventLoop.connect_write_pipe(protocol_factory, pipe)
544
545 Register write pipe in eventloop.
546
547 *protocol_factory* should instantiate object with :class:`BaseProtocol`
548 interface. Pipe is file-like object already switched to nonblocking.
549 Return pair (transport, protocol), where transport support
550 :class:`WriteTransport` interface.
551
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500552 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100553
Victor Stinner08444382014-02-02 22:43:39 +0100554.. seealso::
555
556 The :func:`create_subprocess_exec` and :func:`create_subprocess_shell`
557 functions.
558
Victor Stinnerea3183f2013-12-03 01:08:00 +0100559
Victor Stinner8b863482014-01-27 10:07:50 +0100560UNIX signals
561------------
562
563Availability: UNIX only.
564
565.. method:: BaseEventLoop.add_signal_handler(signum, callback, \*args)
566
567 Add a handler for a signal.
568
569 Raise :exc:`ValueError` if the signal number is invalid or uncatchable.
570 Raise :exc:`RuntimeError` if there is a problem setting up the handler.
571
572.. method:: BaseEventLoop.remove_signal_handler(sig)
573
574 Remove a handler for a signal.
575
576 Return ``True`` if a signal handler was removed, ``False`` if not.
577
578.. seealso::
579
580 The :mod:`signal` module.
581
582
Victor Stinnerea3183f2013-12-03 01:08:00 +0100583Executor
584--------
585
586Call a function in an :class:`~concurrent.futures.Executor` (pool of threads or
587pool of processes). By default, an event loop uses a thread pool executor
588(:class:`~concurrent.futures.ThreadPoolExecutor`).
589
590.. method:: BaseEventLoop.run_in_executor(executor, callback, \*args)
591
592 Arrange for a callback to be called in the specified executor.
593
Larry Hastings3732ed22014-03-15 21:13:56 -0700594 The *executor* argument should be an :class:`~concurrent.futures.Executor`
595 instance. The default executor is used if *executor* is ``None``.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100596
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500597 This method is a :ref:`coroutine <coroutine>`.
598
Victor Stinnerea3183f2013-12-03 01:08:00 +0100599.. method:: BaseEventLoop.set_default_executor(executor)
600
601 Set the default executor used by :meth:`run_in_executor`.
602
603
Yury Selivanov43ee1c12014-02-19 20:58:44 -0500604Error Handling API
605------------------
606
607Allows to customize how exceptions are handled in the event loop.
608
609.. method:: BaseEventLoop.set_exception_handler(handler)
610
611 Set *handler* as the new event loop exception handler.
612
613 If *handler* is ``None``, the default exception handler will
614 be set.
615
616 If *handler* is a callable object, it should have a
617 matching signature to ``(loop, context)``, where ``loop``
618 will be a reference to the active event loop, ``context``
619 will be a ``dict`` object (see :meth:`call_exception_handler`
620 documentation for details about context).
621
622.. method:: BaseEventLoop.default_exception_handler(context)
623
624 Default exception handler.
625
626 This is called when an exception occurs and no exception
627 handler is set, and can be called by a custom exception
628 handler that wants to defer to the default behavior.
629
630 *context* parameter has the same meaning as in
631 :meth:`call_exception_handler`.
632
633.. method:: BaseEventLoop.call_exception_handler(context)
634
635 Call the current event loop exception handler.
636
637 *context* is a ``dict`` object containing the following keys
638 (new keys may be introduced later):
639
640 * 'message': Error message;
641 * 'exception' (optional): Exception object;
642 * 'future' (optional): :class:`asyncio.Future` instance;
643 * 'handle' (optional): :class:`asyncio.Handle` instance;
644 * 'protocol' (optional): :ref:`Protocol <asyncio-protocol>` instance;
645 * 'transport' (optional): :ref:`Transport <asyncio-transport>` instance;
646 * 'socket' (optional): :class:`socket.socket` instance.
647
648 .. note::
649
650 Note: this method should not be overloaded in subclassed
651 event loops. For any custom exception handling, use
652 :meth:`set_exception_handler()` method.
653
Victor Stinner0f3e6bc2014-02-19 23:15:02 +0100654Debug mode
655----------
656
657.. method:: BaseEventLoop.get_debug()
658
Victor Stinner1415e252014-02-20 01:44:10 +0100659 Get the debug mode (:class:`bool`) of the event loop, ``False`` by default.
Victor Stinner0f3e6bc2014-02-19 23:15:02 +0100660
661.. method:: BaseEventLoop.set_debug(enabled: bool)
662
663 Set the debug mode of the event loop.
664
665.. seealso::
666
667 The :ref:`Develop with asyncio <asyncio-dev>` section.
668
669
Victor Stinner8c462c52014-01-24 18:11:43 +0100670Server
671------
672
673.. class:: AbstractServer
674
675 Abstract server returned by :func:`BaseEventLoop.create_server`.
676
677 .. method:: close()
678
679 Stop serving. This leaves existing connections open.
680
681 .. method:: wait_closed()
682
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500683 A :ref:`coroutine <coroutine>` to wait until service is closed.
Victor Stinner8c462c52014-01-24 18:11:43 +0100684
685
Yury Selivanov43ee1c12014-02-19 20:58:44 -0500686Handle
687------
688
689.. class:: Handle
690
691 A callback wrapper object returned by :func:`BaseEventLoop.call_soon`,
692 :func:`BaseEventLoop.call_soon_threadsafe`, :func:`BaseEventLoop.call_later`,
693 and :func:`BaseEventLoop.call_at`.
694
695 .. method:: cancel()
696
697 Cancel the call.
698
699
Victor Stinner3e09e322013-12-03 01:22:06 +0100700.. _asyncio-hello-world-callback:
Victor Stinnerea3183f2013-12-03 01:08:00 +0100701
Victor Stinner3e09e322013-12-03 01:22:06 +0100702Example: Hello World (callback)
703-------------------------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100704
705Print ``Hello World`` every two seconds, using a callback::
706
707 import asyncio
708
709 def print_and_repeat(loop):
710 print('Hello World')
711 loop.call_later(2, print_and_repeat, loop)
712
713 loop = asyncio.get_event_loop()
Victor Stinnerdbd89502013-12-10 02:47:22 +0100714 loop.call_soon(print_and_repeat, loop)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100715 loop.run_forever()
716
Victor Stinner3e09e322013-12-03 01:22:06 +0100717.. seealso::
Victor Stinnerea3183f2013-12-03 01:08:00 +0100718
Victor Stinner3e09e322013-12-03 01:22:06 +0100719 :ref:`Hello World example using a coroutine <asyncio-hello-world-coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100720
Victor Stinner8b863482014-01-27 10:07:50 +0100721
722Example: Set signal handlers for SIGINT and SIGTERM
723---------------------------------------------------
724
725Register handlers for signals :py:data:`SIGINT` and :py:data:`SIGTERM`::
726
727 import asyncio
728 import functools
729 import os
730 import signal
731
732 def ask_exit(signame):
733 print("got signal %s: exit" % signame)
734 loop.stop()
735
736 loop = asyncio.get_event_loop()
737 for signame in ('SIGINT', 'SIGTERM'):
738 loop.add_signal_handler(getattr(signal, signame),
739 functools.partial(ask_exit, signame))
740
741 print("Event loop running forever, press CTRL+c to interrupt.")
742 print("pid %s: send SIGINT or SIGTERM to exit." % os.getpid())
743 loop.run_forever()
744