You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中try代码未执行完成就进入finally块的解决方法

问题解决思路

问题根源

你的代码出现这个问题,大概率是因为模型打分代码是异步执行的——主线程启动打分任务后,不会等待它完成,直接执行完try块剩余代码,随即进入finally块执行关闭操作。而finally块的执行逻辑是:只要try/except块的代码执行完毕(无论是否抛出异常),就会立刻触发。

两种解决办法

1. 强制等待模型打分任务完成

如果打分代码是通过线程、进程或异步IO启动的,修改代码让主线程等待任务结束后再继续:

  • 若是用线程:启动线程后调用join()方法等待线程执行完毕
    import threading
    
    def model_scoring():
        # 原模型打分代码
        pass
    
    # 在try块中替换原打分代码:
    t = threading.Thread(target=model_scoring)
    t.start()
    t.join()  # 主线程等待打分线程完成
    
  • 若是用异步IO(比如asyncio):在异步函数前加await关键字,确保阻塞等待完成
    import asyncio
    
    async def model_scoring():
        # 原异步打分代码
        pass
    
    # 在try块中替换原打分代码:
    await model_scoring()  # 等待异步打分任务完成
    
  • 若是调用了第三方异步API:查看API文档,找到同步等待的方法(比如某些SDK会提供wait()或get_result()这类方法)

2. 调整关闭逻辑的位置

如果不需要保持异步执行,也可以把关闭笔记本的代码从finally块中移出,分别放在正常流程结束后和异常处理完成后:

file_ctr = 4
try:
    if (file_ctr!=5):
        raise ValueError('The number of files is different than expected.')
    print("I made it")
    print("I made it")
    print("Model scoring will start now")
    # 模型打分代码(确保同步执行)
    # Model scoring code
    # 打分完成后执行关闭
    print("Shutting notebook")
    # sagemaker_client.stop_notebook_instance(NotebookInstanceName=get_notebook_name())
except Exception as e:
    print("Feature set not up-to-date.")
    print(e)
    # 异常处理完成后执行关闭
    print("Shutting notebook")
    # sagemaker_client.stop_notebook_instance(NotebookInstanceName=get_notebook_name())

这种方式下,只有当打分任务完成(或异常处理完毕)后,才会执行关闭操作,从根本上避免提前关闭的问题。

内容的提问来源于stack exchange,提问作者warri0r_princess

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 12:45:17