Python 异步编程实战:掌握任务取消的艺术与优雅退出策略

别只会Ctrl+C了!Python中KeyboardInterrupt的3个高级用法与实战避坑指南 本文深入探讨了Python中KeyboardInterrupt的3个高级用法与实战避坑技巧,帮助开发者在异步编程、信号处理和多线程/多进程环境下实现优雅中断。通过具体代码示例和解决方案,避免数据丢失和资源泄漏等问题,提升程序的健壮性和可靠性。 阅读详情

Python 异步编程实战:掌握任务取消的艺术与优雅退出策略

引言:当"停下来"比"跑起来"更难

在我职业生涯的第三年,我负责的一个数据采集系统出现了严重的资源泄漏问题。每当用户点击"停止"按钮,系统表面上停止了,但后台仍有数十个网络连接保持活跃,数据库事务未提交,临时文件散落一地。这次惨痛的经历让我意识到:如何优雅地停止一个异步任务,远比启动它更具挑战性。

在异步编程的世界里,任务取消(Task Cancellation)是一门被严重低估的艺术。大多数开发者将 90% 的精力放在如何让任务高效运行,却忽略了那关键的 10%——如何让它们安全、干净、彻底地停下来。今天,我将通过实战案例和深度剖析,带你全面掌握 Python asyncio 中任务取消的精髓。

一、任务取消的本质:协作式而非强制式

1.1 理解 asyncio 的取消机制

与线程的强制终止不同,asyncio 的任务取消是协作式的:

import asyncio

async def naive_task():
    """天真的任务:不处理取消"""
    print("任务开始")
    try:
        # 长时间运行的操作
        for i in range(10):
            print(f"执行步骤 {
     
     i}")
            await asyncio.sleep(1)
        print("任务完成")
    except Exception as e:
        print(f"捕获异常:{
     
     e}")

async def test_naive_cancellation():
    task = asyncio.create_task(naive_task())
    
    # 等待 3 秒后取消
    await asyncio.sleep(3)
    print("\n⚠️  尝试取消任务...")
    task.cancel()
    
    try:
        await task
    except asyncio.CancelledError:
        print("✅ 任务已被取消")

# asyncio.run(test_naive_cancellation())

关键发现:

  • cancel() 方法只是设置一个标志,并不立即停止任务
  • 下一次 await 时会抛出 CancelledError 异常
  • 如果任务中没有 await 点,取消将无法生效

1.2 取消的三个阶段

import asyncio
import time

async def three_phase_task():
    """展示取消的三个阶段"""
    print("阶段1:任务正常运行")
    
    try:
        await asyncio.sleep(2)
        print("阶段2:继续运行(如果未被取消)")
        await asyncio.sleep(2)
        
    except asyncio.CancelledError:
        print("阶段3:取消信号已接收")
        # 清理工作
        print("  - 关闭数据库连接")
        print("  - 保存中间状态")
        print("  - 释放文件句柄")
        raise  # 重要:重新抛出 CancelledError
    
    finally:
        print("阶段4:finally 块总会执行")
        print("  - 执行最终清理")

async def demo_three_phases():
    task = asyncio.create_task(three_phase_task())
    await asyncio.sleep(1)
    
    task.cancel()
    
    try:
        await task
    except asyncio.CancelledError:
        print("\n主程序:确认任务已取消")

asyncio.run(demo_three_phases())

输出解析:

阶段1:任务正常运行
阶段3:取消信号已接收
  - 关闭数据库连接
  - 保存中间状态
  - 释放文件句柄
阶段4:finally 块总会执行
  - 执行最终清理

主程序:确认任务已取消

二、边界情况处理:魔鬼在细节中

2.1 边界情况一:屏蔽取消信号(反模式)

async def cancel_resistant_task():
    """❌ 错误示范:吞掉 CancelledError"""
    try:
        while True:
            print("我停不下来!")
            await asyncio.sleep(1)
    except asyncio.CancelledError:
        print("收到取消信号,但我选择无视...")
        # 危险:不重新抛出异常
        await asyncio.sleep(5)  # 继续运行
        print("哈哈,我还活着")

async def demo_cancel_resistance():
    task = asyncio.create_task(cancel_resistant_task())
    await asyncio.sleep(3)
    
    task.cancel()
    print("已发送取消信号")
    
    try:
        await asyncio.wait_for(task, timeout=10)
    except asyncio.TimeoutError:
        print("⚠️  任务拒绝取消,超时强制退出")
    except asyncio.CancelledError:
        print("任务已取消")

# asyncio.run(demo_cancel_resistance())

正确做法:

async def well_behaved_task():
    """✅ 正确示范:响应取消但完成必要清理"""
    try:
        while True:
            print("执行任务...")
            await asyncio.sleep(1)
    except asyncio.CancelledError:
        print("收到取消信号,执行清理...")
        # 执行必要的同步清理(注意:不要有 await)
        print("清理完成")
        raise  # 关键:必须重新抛出

2.2 边界情况二:嵌套任务的级联取消

import asyncio

async def child_task(task_id, duration):
    """子任务"""
    try:
        print(f"  子任务 {
     
     task_id} 开始")
        await asyncio.sleep(duration)
        print(f"  子任务 {
     
     task_id} 完成")
        return f"Result-{
     
     task_id}"
    except asyncio.CancelledError:
        print(f"  子任务 {
     
     task_id} 被取消")
        raise

async def parent_task():
    """父任务:管理多个子任务"""
    
基于Playwright与异步编程的高效直播平台数据抓取实战 在现代Web开发中,动态内容渲染已成为主流技术,这给传统爬虫方案带来了巨大挑战。其核心原理在于,网站通过JavaScript在客户端动态加载数据,使得直接获取HTML源码的方式失效。为了应对这一技术难题,高效的浏览器自动化与异步非阻塞I/O模型相结合,展现出极高的技术价值,尤其在需要实时、高并发处理数据的应用场景中。例如,在直播行业数据分析、市场热度监控等场景下,稳定、高效地获取实时列表数据是关键需求。本文聚焦于利用Playwright这一强大的浏览器自动化库,结合Python的asyncio异步编程框架, 阅读详情

相关推荐

打通Creo与Matlab的桥梁:Simscape Multibody Link插件安装与配置全攻略

本文详细介绍了Simscape Multibody Link插件的安装与配置全流程,旨在帮助机械工程师和开发者打通Creo与Matlab/Simulink之间的桥梁,实现CAD模型到多体动力学仿真的高效转换。文章重点解析了版本兼容性、管理员权限、注册文件配置等关键步骤与常见故障排查方法,助力用户快速建立设计与仿真一体化工作流。

rrr55的博客 638

中心对数比变换(Centered Log Ratio Transformation,CLR)的原理及scikit-bio介绍

中心对数比变换(Centered Log Ratio Transformation,CLR)是一种数据预处理方法,常用于成分数据分析领域。在成分数据中,各成分之间通常存在一定的约束关系,比如它们的和为固定值等,中心对数比变换可以有效地处理这种具有特殊约束的数据。官方文档scikit-bio是一个在Python3中处理生物数据的库成分统计 (skbio.stats.composition )模块中的,此函数将组合从Aitchison几何体转换到真实空间。这个clr。

RECORD LEARN PROGRESS 1万+

Jasypt 开源加密库使用教程

Jasypt 加密框架概述 1、Jasypt Spring Boot 为 spring boot 应用程序中的属性源提供加密支持,出于安全考虑,Spring boot 配置文件中的敏感信息通常需要对它进行加密/脱敏处理,尽量不使用明文,要实现这一点,办法有很多,自己手动对敏感信息进行加解密也是可以的。 2、有需求就有人奉献,Jasypt 开源安全框架就是专门用于处理 Spring boot 属性加密的,在配置文件中直接配置密文,然后应用启动的时候,Jasypt 会自动将密码解密成明文供程序使用。 3、

蚩尤后裔-汪茂雄 3万+

芯片研发完整全流程

芯片研发全流程可分为需求与架构设计、前端逻辑设计、后端物理设计、晶圆制造、封装测试五大阶段,涉及16个核心步骤。研发过程需要多学科交叉协作,包括微电子、物理、材料、计算机等。关键注意事项包括验证优先、工艺约束遵循、可测性设计等。芯片设计需要绘制纳米级精度的物理版图,而非传统工程图纸,需使用专业EDA工具而非KiCad这类PCB设计软件。完整研发流程具有高投入、高风险特点,需严格遵循行业标准和规范。

weixin_44520581的博客 265

浅谈银行内部户治理

为避免该问题的发生,对内部户入账类交易,或内部户是可透支的账户(如系统间往来),可考虑通过异步方式更新账户余额(当然,根本上还是要考虑银行业务量的实际,异步消息接口很多时候没有同步接口方便),另外,在进行内部户余额更新时,可以通过定时的借贷方发生额轧差的方式,将多次的锁请求,简化为一次(当然,发生额明细本身在加工账户交易历史时,是不能汇总的)。内部户在银行系统中,属于业务属性较少,实现相对简单,原理也很容易讲清的系统,但管中窥豹,越是基础的东西,越能看出一家银行业务、内控的专业程度。

银行信息系统应用架构详解 808

HTML5+CSS3+JS小实例:焦点图波浪切换动画特效

实例:焦点图波浪切换动画特效。字体图标库:Font Awesome。技术栈:HTML+CSS+JS。

艾恩小灰灰的博客 914

手把手教你学Simulink--基础储能管理场景实例:基于Simulink的锂电池健康状态(SOH)在线评估仿真

本文详细介绍了基于Simulink的锂电池健康状态(SOH)在线评估仿真方法。主要内容包括:1)SOH定义与量化指标(容量SOH、内阻SOH及综合SOH);2)基于Thevenin模型参数辨识和递推最小二乘法(RLS)的在线评估原理;3)100次充放电循环的仿真场景设置;4)Simulink建模步骤(主电路搭建、核心模块实现及信号流连接);5)仿真结果分析,显示SOH评估误差<2%,响应时间45秒,满足在线评估需求;6)提出多参数融合评估、深度学习辅助辨识等优化方向。该方法为储能系统寿命管理提供了有效

MHD0815的博客 183

WPF数据绑定Binding对数据的转换与效验(四)

Binding的作用就是架在Source与Target之间的桥梁,数据可以在这座桥梁的帮助下来流通。就像现实世界中的桥梁会设置一些关卡进行安检一样,Binding这座桥上也可以设置关卡对数据的有效性进行检验,不仅如此,当Binding的两端要求使用不同的数据类型时,我们还可以为数据设置转换器。Binding用于数据有效性检验的关卡是它的ValidationRules属性,用于数据类型转换的关卡是它的Converter属性。

qq_30725967的博客 1632

全球国家地区城市数据

MySQL全球国家地区城市数据报。。。。。。。。。。。。

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

pscad IEEE标准系统搭建说明

pscad IEEE标准系统搭建说明,包含典型的IEEE 9节点、14节点、30节点、39节点和118节点系统。内含标准测试系统的原始数据和潮流结果。

Data-Structures-and-Algorithm-Analysis-in-Java.pdf

作者: Weiss, Mark A. 出版社: Addison Wesley Data Structures and Algorithm Analysis in Java is an “advanced algorithms” book that fits between traditional CS2 and Algorithms Analysis courses. In the old ACM Curriculum Guidelines, this course was known as CS7. This text is for readers who want to learn good programming and algorithm analysis skills simultaneously so that they can develop such programs with the maximum amo...

上一篇: Python 异步编程实战:深入理解背压机制与 asyncio.Queue 的流量控制艺术
下一篇: Python 异步上下文管理器深度解析:从 `with` 到 `async with` 的进化之旅
铭渊老黄
铭渊老黄 新星创作者: Python技术领域 新星创作者: Python技术领域
博客等级 码龄7年 1万+粉丝 2220原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

铭渊老黄

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值