Python KeyboardInterrupt 导致文件损坏

问题描述

我有一段代码负责清理 XML 文件。处理解析错误(忽略文件)。

然而,我用 ctrl+C 中断了这个函数,它最终破坏了当前处理的文件(文件内容被删除):

import lxml.etree as ET
from pathlib import Path


def foo(path: str):
  try:
    tree = ET.parse(path)
    # Some code that reads and modifies the tree...
  except ET.ParseError:
    return
  Path(path).write_text(ET.tostring(tree))

有没有办法在 KeyboardInterrupt 上执行清理代码?

例如,我应该在一个 except 块中处理 KeyboardInterrupt 以避免写入吗?也许我可以在错误处理后使用 else 块只在没有发生错误时写入:

def foo(path: str):
  try:
    tree = ET.parse(path)
    # Some code that reads and modifies the tree...
  except ET.ParseError:
    return
  else:
    Path(path).write_text(ET.tostring(tree))

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)