开源 企业版 高校版 私有云 模力方舟 AI 队友
代码拉取完成,页面将自动刷新
捐赠
捐赠前请先登录
扫描微信二维码支付
取消
支付完成
支付提示
将跳转至支付宝完成支付
确定
取消
1 Star 0 Fork 0

source-code-analysis/python3.8.1

加入 Gitee
与超过 1400万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
已有帐号? 立即登录
文件
master
分支 (1)
master
master
分支 (1)
master
克隆/下载
克隆/下载
提示
下载代码请复制以下命令到终端执行
为确保你提交的代码身份被 Gitee 正确识别,请执行以下命令完成配置
初次使用 SSH 协议进行代码克隆、推送等操作时,需按下述提示完成 SSH 配置
1 生成 RSA 密钥
2 获取 RSA 公钥内容,并配置到 SSH公钥
在 Gitee 上使用 SVN,请访问 使用指南
使用 HTTPS 协议时,命令行会出现如下账号密码验证步骤。基于安全考虑,Gitee 建议 配置并使用私人令牌 替代登录密码进行克隆、推送等操作
Username for 'https://gitee.com': userName
Password for 'https://userName@gitee.com': # 私人令牌
master
分支 (1)
master
python3.8.1
/
Doc
/
library
/
asyncio-dev.rst
python3.8.1
/
Doc
/
library
/
asyncio-dev.rst
asyncio-dev.rst 6.55 KB
一键复制 编辑 原始数据 按行查看 历史
zhangweibo 提交于 2021年11月16日 09:46 +08:00 . git init
.. currentmodule:: asyncio

Developing with asyncio

Asynchronous programming is different from classic "sequential" programming.

This page lists common mistakes and traps and explains how to avoid them.

Debug Mode

By default asyncio runs in production mode. In order to ease the development asyncio has a debug mode.

There are several ways to enable asyncio debug mode:

In addition to enabling the debug mode, consider also:

When the debug mode is enabled:

Concurrency and Multithreading

An event loop runs in a thread (typically the main thread) and executes all callbacks and Tasks in its thread. While a Task is running in the event loop, no other Tasks can run in the same thread. When a Task executes an await expression, the running Task gets suspended, and the event loop executes the next Task.

To schedule a callback from a different OS thread, the :meth:`loop.call_soon_threadsafe` method should be used. Example:

loop.call_soon_threadsafe(callback, *args)

Almost all asyncio objects are not thread safe, which is typically not a problem unless there is code that works with them from outside of a Task or a callback. If there's a need for such code to call a low-level asyncio API, the :meth:`loop.call_soon_threadsafe` method should be used, e.g.:

loop.call_soon_threadsafe(fut.cancel)

To schedule a coroutine object from a different OS thread, the :func:`run_coroutine_threadsafe` function should be used. It returns a :class:`concurrent.futures.Future` to access the result:

async def coro_func():
 return await asyncio.sleep(1, 42)

# Later in another OS thread:

future = asyncio.run_coroutine_threadsafe(coro_func(), loop)
# Wait for the result:
result = future.result()

To handle signals and to execute subprocesses, the event loop must be run in the main thread.

The :meth:`loop.run_in_executor` method can be used with a :class:`concurrent.futures.ThreadPoolExecutor` to execute blocking code in a different OS thread without blocking the OS thread that the event loop runs in.

Running Blocking Code

Blocking (CPU-bound) code should not be called directly. For example, if a function performs a CPU-intensive calculation for 1 second, all concurrent asyncio Tasks and IO operations would be delayed by 1 second.

An executor can be used to run a task in a different thread or even in a different process to avoid blocking the OS thread with the event loop. See the :meth:`loop.run_in_executor` method for more details.

Logging

asyncio uses the :mod:`logging` module and all logging is performed via the "asyncio" logger.

The default log level is :py:data:`logging.INFO`, which can be easily adjusted:

logging.getLogger("asyncio").setLevel(logging.WARNING)

Detect never-awaited coroutines

When a coroutine function is called, but not awaited (e.g. coro() instead of await coro()) or the coroutine is not scheduled with :meth:`asyncio.create_task`, asyncio will emit a :exc:`RuntimeWarning`:

import asyncio

async def test():
 print("never scheduled")

async def main():
 test()

asyncio.run(main())

Output:

test.py:7: RuntimeWarning: coroutine 'test' was never awaited
 test()

Output in debug mode:

test.py:7: RuntimeWarning: coroutine 'test' was never awaited
Coroutine created at (most recent call last)
 File "../t.py", line 9, in <module>
 asyncio.run(main(), debug=True)

 < .. >

 File "../t.py", line 7, in main
 test()
 test()

The usual fix is to either await the coroutine or call the :meth:`asyncio.create_task` function:

async def main():
 await test()

Detect never-retrieved exceptions

If a :meth:`Future.set_exception` is called but the Future object is never awaited on, the exception would never be propagated to the user code. In this case, asyncio would emit a log message when the Future object is garbage collected.

Example of an unhandled exception:

import asyncio

async def bug():
 raise Exception("not consumed")

async def main():
 asyncio.create_task(bug())

asyncio.run(main())

Output:

Task exception was never retrieved
future: <Task finished coro=<bug() done, defined at test.py:3>
 exception=Exception('not consumed')>

Traceback (most recent call last):
 File "test.py", line 4, in bug
 raise Exception("not consumed")
Exception: not consumed

:ref:`Enable the debug mode <asyncio-debug-mode>` to get the traceback where the task was created:

asyncio.run(main(), debug=True)

Output in debug mode:

Task exception was never retrieved
future: <Task finished coro=<bug() done, defined at test.py:3>
 exception=Exception('not consumed') created at asyncio/tasks.py:321>

source_traceback: Object created at (most recent call last):
 File "../t.py", line 9, in <module>
 asyncio.run(main(), debug=True)

< .. >

Traceback (most recent call last):
 File "../t.py", line 4, in bug
 raise Exception("not consumed")
Exception: not consumed
Loading...
举报
举报成功
我们将于2个工作日内通过站内信反馈结果给你!
请认真填写举报原因,尽可能描述详细。
请选择举报类型
取消
发送
误判申诉

此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。

如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。

取消
提交

简介

取消

发行版

暂无发行版

贡献者

全部

近期动态

不能加载更多了
编辑仓库简介
简介内容
主页
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/python_sourcecode/python3.8.1.git
git@gitee.com:python_sourcecode/python3.8.1.git
python_sourcecode
python3.8.1
python3.8.1
master
点此查找更多帮助

搜索帮助

评论
仓库举报
回到顶部
登录提示
该操作需登录 Gitee 帐号,请先登录后再操作。
立即登录
没有帐号,去注册

AltStyle によって変換されたページ (->オリジナル) /