1

我有一个创建大量临时文件的 python 脚本。如果脚本由于 ctrl+c 中断而提前终止,我想在程序结束之前快速删除这些文件。

处理这个的pythonic方式是什么?

4

3 回答 3

6

with如果可能,在语句中打开文件,或使用带有关闭文件的块的try语句。finally如果您使用tempfile,文件将在关闭时自动销毁;否则,您可能需要自己在finally块中删除它们。

于 2013-08-16T19:46:38.070 回答
1

http://docs.python.org/2/library/exceptions.html#exceptions.KeyboardInterrupt

if __name__ == '__main__':
  try:
    main()
  except KeyboardInterrupt:
    cleanUp()
于 2013-08-16T19:47:24.313 回答
0

要么 catch 并处理KeyboardInterrupt,要么设置一个退出处理程序atexit

另外,tempfile.

于 2013-08-16T19:45:33.057 回答