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

Python中assert断言失败后如何跳过异常继续执行程序

问题根因

assert语句的默认行为就是条件不满足时抛出AssertionError终止程序,你当前写的try-except虽然捕获了断言错误,但是捕获异常后没有中断当前循环的后续执行逻辑——只要文件不存在触发断言失败,后续执行move(of, fn)时依然会因为源文件不存在抛出新的错误,导致程序中断。
另外补充:assert本质是调试用的校验语法,Python以优化模式(启动时加-O参数)运行时,所有assert语句会被全局移除,不适合用来做批量任务的业务逻辑校验。

修正方案

方案1:保留assert写法,捕获异常后跳过当前轮次

只需要在except块中加continue,触发断言失败时直接进入下一条链接的处理,不要执行后续的文件移动、成功状态写入逻辑即可,修正后的核心代码如下:

import os
from shutil import move
# 前置初始化逻辑保持原有写法即可
for line in url_file:
  stripped_line = line.split(',')
  target_url = stripped_line[2]+stripped_line[1]
  list_of_urls.append(target_url)
  driver.get(target_url)
  time.sleep(2)
  
  # 用os.path.join拼接路径,避免跨系统路径分隔符错误
  of = os.path.join(download_dir, f"{stripped_line[3]}.pdf")
  fn = os.path.join(download_dir, f"{stripped_line[0]}.pdf")

  try: 
    assert os.path.exists(of), f"File not found at, {of}"
  except AssertionError: 
    # 可选:打印失败日志方便排查
    print(f"链接{target_url}对应文件下载失败,跳过")
    # 写入失败状态,方便后续对账
    status_file.write(f"{stripped_line[0]},Download Failed\n")
    # 直接进入下一轮循环,不执行后续逻辑
    continue

  move(of, fn)
  fns.append(stripped_line[0])
  ofns.append(stripped_line[3])
  status_file.write(f"{stripped_line[0]},File Downloaded\n")

url_file.close()
status_file.close()
driver.quit()

方案2:移除assert,直接做条件判断(更推荐)

批量处理任务不建议依赖assert做存在性校验,直接写显式的条件判断更稳定,不会因为运行参数变化导致校验逻辑失效:

import os
from shutil import move
# 前置初始化逻辑保持原有写法即可
for line in url_file:
  stripped_line = line.split(',')
  target_url = stripped_line[2]+stripped_line[1]
  list_of_urls.append(target_url)
  driver.get(target_url)
  time.sleep(2)
  
  of = os.path.join(download_dir, f"{stripped_line[3]}.pdf")
  fn = os.path.join(download_dir, f"{stripped_line[0]}.pdf")

  # 直接判断文件是否存在,不需要抛断言异常
  if not os.path.exists(of):
    print(f"文件{of}不存在,对应链接失效,跳过")
    status_file.write(f"{stripped_line[0]},Download Failed\n")
    continue

  move(of, fn)
  fns.append(stripped_line[0])
  ofns.append(stripped_line[3])
  status_file.write(f"{stripped_line[0]},File Downloaded\n")

url_file.close()
status_file.close()
driver.quit()
额外优化提示
  • 建议给文件等待逻辑加超时重试,现在固定sleep(2)在网络慢的时候可能文件还没下完就做存在性判断,会误判成链接失效
  • 失败的条目一定要写入状态文件,避免后续排查的时候找不到哪些URL处理失败

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 22:45:45