如何阻止 ipython 关闭失败的打开文件句柄



我尝试调试一些IO代码,但是在异常期间文件不断关闭。

使用以下截图

with open('test', 'w') as fid:
    fid.write('a')
    1/0
In [1]: %run test.py
---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
***/test.py in <module>()
      1 with open('test', 'w') as fid:
      2         fid.write('a')
----> 3         1/0
ZeroDivisionError: division by zero
In [2]: %debug
***/test.py(3)<module>()
      1 with open('test', 'w') as fid:
      2         fid.write('a')
----> 3         1/0
ipdb> fid.write('b')
*** ValueError: I/O operation on closed file.

应该说明我的意思。我确实意识到,无论file上下文管理器的意义如何,关闭文件句柄都是如此。但是,由于堆栈跟踪由 IPython (5.1) 保留,因此应该可以在同一位置打开文件 - 假设文件在此期间未被更改。

这是应该的。with open(filename, access_mode, buffering) as var 的用法是在执行所有语句后立即关闭文件。来自 Python 文档:

执行语句后,文件 f 始终处于关闭状态,即使在处理行时遇到问题也是如此。提供预定义清理操作的其他对象将在其文档中指出这一点。

重点是我的。因此,您必须以老式的方式打开文件:

file_name = open("test", "w")
# insert rest of statements here
file_name.close()

最新更新