Python 键盘中断导致文件损坏

Python KeyboardInterrupt is causing a file corruption

我有一段代码负责清理一个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))

解决方案是在写入文件时检查 KeyboardInterrupt 并在退出前重新尝试写入操作:

import lxml.etree as ET
from pathlib import Path
from sys import exit

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

将该代码放在 else 子句中可确保之前的操作不会失败,因此此时数据有效。