PageRenderTime 57ms CodeModel.GetById 31ms RepoModel.GetById 0ms app.codeStats 0ms

/Doc/library/asyncio-dev.rst

https://gitlab.com/unofficial-mirrors/cpython
ReStructuredText | 418 lines | 294 code | 124 blank | 0 comment | 0 complexity | 24b541ca77f20300fa113187d7d4d57a MD5 | raw file
  1. .. currentmodule:: asyncio
  2. .. _asyncio-dev:
  3. Develop with asyncio
  4. ====================
  5. Asynchronous programming is different than classical "sequential" programming.
  6. This page lists common traps and explains how to avoid them.
  7. .. _asyncio-debug-mode:
  8. Debug mode of asyncio
  9. ---------------------
  10. The implementation of :mod:`asyncio` has been written for performance.
  11. In order to ease the development of asynchronous code, you may wish to
  12. enable *debug mode*.
  13. To enable all debug checks for an application:
  14. * Enable the asyncio debug mode globally by setting the environment variable
  15. :envvar:`PYTHONASYNCIODEBUG` to ``1``, or by calling :meth:`AbstractEventLoop.set_debug`.
  16. * Set the log level of the :ref:`asyncio logger <asyncio-logger>` to
  17. :py:data:`logging.DEBUG`. For example, call
  18. ``logging.basicConfig(level=logging.DEBUG)`` at startup.
  19. * Configure the :mod:`warnings` module to display :exc:`ResourceWarning`
  20. warnings. For example, use the ``-Wdefault`` command line option of Python to
  21. display them.
  22. Examples debug checks:
  23. * Log :ref:`coroutines defined but never "yielded from"
  24. <asyncio-coroutine-not-scheduled>`
  25. * :meth:`~AbstractEventLoop.call_soon` and :meth:`~AbstractEventLoop.call_at` methods
  26. raise an exception if they are called from the wrong thread.
  27. * Log the execution time of the selector
  28. * Log callbacks taking more than 100 ms to be executed. The
  29. :attr:`AbstractEventLoop.slow_callback_duration` attribute is the minimum
  30. duration in seconds of "slow" callbacks.
  31. * :exc:`ResourceWarning` warnings are emitted when transports and event loops
  32. are :ref:`not closed explicitly <asyncio-close-transports>`.
  33. .. seealso::
  34. The :meth:`AbstractEventLoop.set_debug` method and the :ref:`asyncio logger
  35. <asyncio-logger>`.
  36. Cancellation
  37. ------------
  38. Cancellation of tasks is not common in classic programming. In asynchronous
  39. programming, not only it is something common, but you have to prepare your
  40. code to handle it.
  41. Futures and tasks can be cancelled explicitly with their :meth:`Future.cancel`
  42. method. The :func:`wait_for` function cancels the waited task when the timeout
  43. occurs. There are many other cases where a task can be cancelled indirectly.
  44. Don't call :meth:`~Future.set_result` or :meth:`~Future.set_exception` method
  45. of :class:`Future` if the future is cancelled: it would fail with an exception.
  46. For example, write::
  47. if not fut.cancelled():
  48. fut.set_result('done')
  49. Don't schedule directly a call to the :meth:`~Future.set_result` or the
  50. :meth:`~Future.set_exception` method of a future with
  51. :meth:`AbstractEventLoop.call_soon`: the future can be cancelled before its method
  52. is called.
  53. If you wait for a future, you should check early if the future was cancelled to
  54. avoid useless operations. Example::
  55. @coroutine
  56. def slow_operation(fut):
  57. if fut.cancelled():
  58. return
  59. # ... slow computation ...
  60. yield from fut
  61. # ...
  62. The :func:`shield` function can also be used to ignore cancellation.
  63. .. _asyncio-multithreading:
  64. Concurrency and multithreading
  65. ------------------------------
  66. An event loop runs in a thread and executes all callbacks and tasks in the same
  67. thread. While a task is running in the event loop, no other task is running in
  68. the same thread. But when the task uses ``yield from``, the task is suspended
  69. and the event loop executes the next task.
  70. To schedule a callback from a different thread, the
  71. :meth:`AbstractEventLoop.call_soon_threadsafe` method should be used. Example::
  72. loop.call_soon_threadsafe(callback, *args)
  73. Most asyncio objects are not thread safe. You should only worry if you access
  74. objects outside the event loop. For example, to cancel a future, don't call
  75. directly its :meth:`Future.cancel` method, but::
  76. loop.call_soon_threadsafe(fut.cancel)
  77. To handle signals and to execute subprocesses, the event loop must be run in
  78. the main thread.
  79. To schedule a coroutine object from a different thread, the
  80. :func:`run_coroutine_threadsafe` function should be used. It returns a
  81. :class:`concurrent.futures.Future` to access the result::
  82. future = asyncio.run_coroutine_threadsafe(coro_func(), loop)
  83. result = future.result(timeout) # Wait for the result with a timeout
  84. The :meth:`AbstractEventLoop.run_in_executor` method can be used with a thread pool
  85. executor to execute a callback in different thread to not block the thread of
  86. the event loop.
  87. .. seealso::
  88. The :ref:`Synchronization primitives <asyncio-sync>` section describes ways
  89. to synchronize tasks.
  90. The :ref:`Subprocess and threads <asyncio-subprocess-threads>` section lists
  91. asyncio limitations to run subprocesses from different threads.
  92. .. _asyncio-handle-blocking:
  93. Handle blocking functions correctly
  94. -----------------------------------
  95. Blocking functions should not be called directly. For example, if a function
  96. blocks for 1 second, other tasks are delayed by 1 second which can have an
  97. important impact on reactivity.
  98. For networking and subprocesses, the :mod:`asyncio` module provides high-level
  99. APIs like :ref:`protocols <asyncio-protocol>`.
  100. An executor can be used to run a task in a different thread or even in a
  101. different process, to not block the thread of the event loop. See the
  102. :meth:`AbstractEventLoop.run_in_executor` method.
  103. .. seealso::
  104. The :ref:`Delayed calls <asyncio-delayed-calls>` section details how the
  105. event loop handles time.
  106. .. _asyncio-logger:
  107. Logging
  108. -------
  109. The :mod:`asyncio` module logs information with the :mod:`logging` module in
  110. the logger ``'asyncio'``.
  111. The default log level for the :mod:`asyncio` module is :py:data:`logging.INFO`.
  112. For those not wanting such verbosity from :mod:`asyncio` the log level can
  113. be changed. For example, to change the level to :py:data:`logging.WARNING`:
  114. .. code-block:: none
  115. logging.getLogger('asyncio').setLevel(logging.WARNING)
  116. .. _asyncio-coroutine-not-scheduled:
  117. Detect coroutine objects never scheduled
  118. ----------------------------------------
  119. When a coroutine function is called and its result is not passed to
  120. :func:`ensure_future` or to the :meth:`AbstractEventLoop.create_task` method,
  121. the execution of the coroutine object will never be scheduled which is
  122. probably a bug. :ref:`Enable the debug mode of asyncio <asyncio-debug-mode>`
  123. to :ref:`log a warning <asyncio-logger>` to detect it.
  124. Example with the bug::
  125. import asyncio
  126. @asyncio.coroutine
  127. def test():
  128. print("never scheduled")
  129. test()
  130. Output in debug mode::
  131. Coroutine test() at test.py:3 was never yielded from
  132. Coroutine object created at (most recent call last):
  133. File "test.py", line 7, in <module>
  134. test()
  135. The fix is to call the :func:`ensure_future` function or the
  136. :meth:`AbstractEventLoop.create_task` method with the coroutine object.
  137. .. seealso::
  138. :ref:`Pending task destroyed <asyncio-pending-task-destroyed>`.
  139. Detect exceptions never consumed
  140. --------------------------------
  141. Python usually calls :func:`sys.displayhook` on unhandled exceptions. If
  142. :meth:`Future.set_exception` is called, but the exception is never consumed,
  143. :func:`sys.displayhook` is not called. Instead, :ref:`a log is emitted
  144. <asyncio-logger>` when the future is deleted by the garbage collector, with the
  145. traceback where the exception was raised.
  146. Example of unhandled exception::
  147. import asyncio
  148. @asyncio.coroutine
  149. def bug():
  150. raise Exception("not consumed")
  151. loop = asyncio.get_event_loop()
  152. asyncio.ensure_future(bug())
  153. loop.run_forever()
  154. loop.close()
  155. Output::
  156. Task exception was never retrieved
  157. future: <Task finished coro=<coro() done, defined at asyncio/coroutines.py:139> exception=Exception('not consumed',)>
  158. Traceback (most recent call last):
  159. File "asyncio/tasks.py", line 237, in _step
  160. result = next(coro)
  161. File "asyncio/coroutines.py", line 141, in coro
  162. res = func(*args, **kw)
  163. File "test.py", line 5, in bug
  164. raise Exception("not consumed")
  165. Exception: not consumed
  166. :ref:`Enable the debug mode of asyncio <asyncio-debug-mode>` to get the
  167. traceback where the task was created. Output in debug mode::
  168. Task exception was never retrieved
  169. future: <Task finished coro=<bug() done, defined at test.py:3> exception=Exception('not consumed',) created at test.py:8>
  170. source_traceback: Object created at (most recent call last):
  171. File "test.py", line 8, in <module>
  172. asyncio.ensure_future(bug())
  173. Traceback (most recent call last):
  174. File "asyncio/tasks.py", line 237, in _step
  175. result = next(coro)
  176. File "asyncio/coroutines.py", line 79, in __next__
  177. return next(self.gen)
  178. File "asyncio/coroutines.py", line 141, in coro
  179. res = func(*args, **kw)
  180. File "test.py", line 5, in bug
  181. raise Exception("not consumed")
  182. Exception: not consumed
  183. There are different options to fix this issue. The first option is to chain the
  184. coroutine in another coroutine and use classic try/except::
  185. @asyncio.coroutine
  186. def handle_exception():
  187. try:
  188. yield from bug()
  189. except Exception:
  190. print("exception consumed")
  191. loop = asyncio.get_event_loop()
  192. asyncio.ensure_future(handle_exception())
  193. loop.run_forever()
  194. loop.close()
  195. Another option is to use the :meth:`AbstractEventLoop.run_until_complete`
  196. function::
  197. task = asyncio.ensure_future(bug())
  198. try:
  199. loop.run_until_complete(task)
  200. except Exception:
  201. print("exception consumed")
  202. .. seealso::
  203. The :meth:`Future.exception` method.
  204. Chain coroutines correctly
  205. --------------------------
  206. When a coroutine function calls other coroutine functions and tasks, they
  207. should be chained explicitly with ``yield from``. Otherwise, the execution is
  208. not guaranteed to be sequential.
  209. Example with different bugs using :func:`asyncio.sleep` to simulate slow
  210. operations::
  211. import asyncio
  212. @asyncio.coroutine
  213. def create():
  214. yield from asyncio.sleep(3.0)
  215. print("(1) create file")
  216. @asyncio.coroutine
  217. def write():
  218. yield from asyncio.sleep(1.0)
  219. print("(2) write into file")
  220. @asyncio.coroutine
  221. def close():
  222. print("(3) close file")
  223. @asyncio.coroutine
  224. def test():
  225. asyncio.ensure_future(create())
  226. asyncio.ensure_future(write())
  227. asyncio.ensure_future(close())
  228. yield from asyncio.sleep(2.0)
  229. loop.stop()
  230. loop = asyncio.get_event_loop()
  231. asyncio.ensure_future(test())
  232. loop.run_forever()
  233. print("Pending tasks at exit: %s" % asyncio.Task.all_tasks(loop))
  234. loop.close()
  235. Expected output:
  236. .. code-block:: none
  237. (1) create file
  238. (2) write into file
  239. (3) close file
  240. Pending tasks at exit: set()
  241. Actual output:
  242. .. code-block:: none
  243. (3) close file
  244. (2) write into file
  245. Pending tasks at exit: {<Task pending create() at test.py:7 wait_for=<Future pending cb=[Task._wakeup()]>>}
  246. Task was destroyed but it is pending!
  247. task: <Task pending create() done at test.py:5 wait_for=<Future pending cb=[Task._wakeup()]>>
  248. The loop stopped before the ``create()`` finished, ``close()`` has been called
  249. before ``write()``, whereas coroutine functions were called in this order:
  250. ``create()``, ``write()``, ``close()``.
  251. To fix the example, tasks must be marked with ``yield from``::
  252. @asyncio.coroutine
  253. def test():
  254. yield from asyncio.ensure_future(create())
  255. yield from asyncio.ensure_future(write())
  256. yield from asyncio.ensure_future(close())
  257. yield from asyncio.sleep(2.0)
  258. loop.stop()
  259. Or without ``asyncio.ensure_future()``::
  260. @asyncio.coroutine
  261. def test():
  262. yield from create()
  263. yield from write()
  264. yield from close()
  265. yield from asyncio.sleep(2.0)
  266. loop.stop()
  267. .. _asyncio-pending-task-destroyed:
  268. Pending task destroyed
  269. ----------------------
  270. If a pending task is destroyed, the execution of its wrapped :ref:`coroutine
  271. <coroutine>` did not complete. It is probably a bug and so a warning is logged.
  272. Example of log:
  273. .. code-block:: none
  274. Task was destroyed but it is pending!
  275. task: <Task pending coro=<kill_me() done, defined at test.py:5> wait_for=<Future pending cb=[Task._wakeup()]>>
  276. :ref:`Enable the debug mode of asyncio <asyncio-debug-mode>` to get the
  277. traceback where the task was created. Example of log in debug mode:
  278. .. code-block:: none
  279. Task was destroyed but it is pending!
  280. source_traceback: Object created at (most recent call last):
  281. File "test.py", line 15, in <module>
  282. task = asyncio.ensure_future(coro, loop=loop)
  283. task: <Task pending coro=<kill_me() done, defined at test.py:5> wait_for=<Future pending cb=[Task._wakeup()] created at test.py:7> created at test.py:15>
  284. .. seealso::
  285. :ref:`Detect coroutine objects never scheduled <asyncio-coroutine-not-scheduled>`.
  286. .. _asyncio-close-transports:
  287. Close transports and event loops
  288. --------------------------------
  289. When a transport is no more needed, call its ``close()`` method to release
  290. resources. Event loops must also be closed explicitly.
  291. If a transport or an event loop is not closed explicitly, a
  292. :exc:`ResourceWarning` warning will be emitted in its destructor. By default,
  293. :exc:`ResourceWarning` warnings are ignored. The :ref:`Debug mode of asyncio
  294. <asyncio-debug-mode>` section explains how to display them.