我有一段代码负责清理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**?**上清除代码吗?
例如,为了避免写作,我应该在一个除其他区域中处理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))发布于 2021-07-30 09:19:06
解决方案是在写入文件时检查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()将该代码放入the子句中,可以确保以前的操作没有失败,因此此时数据是有效的。
https://stackoverflow.com/questions/68587926
复制相似问题