PyCharm调试pytest时调试控制台报错无法使用问题求助
PyCharm调试pytest时触发断点后使用调试控制台报"I/O operation on closed file"错误
问题详情
在PyCharm中以调试模式运行pytest测试,触发断点后使用调试控制台时,无论测试内容如何都会触发错误,VS Code中执行相同操作无异常。
环境信息:
- Python 3.11.5
- pytest 7.4.4
控制台输出
object address : 0x2dc09d780 object refcount : 5 object type : 0x105ccac28 object type name: ValueError object repr : ValueError('I/O operation on closed file.') lost sys.stderr
错误栈追踪
self = <contextlib._GeneratorContextManager object at 0x2dc0b4610>, typ = None value = None, traceback = None def __exit__(self, typ, value, traceback): if typ is None: try: > next(self.gen) E ValueError: I/O operation on closed file. /Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/contextlib.py:144: ValueError
示例测试代码
import pytest def example_function(a: int, b: int) -> int: c = a + b return c class TestExample: def test_example(self): result = example_function(1,2) assert result == 3
触发条件:在c = a + b处设置断点,尝试使用调试控制台时触发错误。
解决办法
1. 调整PyCharm调试控制台设置
打开Settings/Preferences > Build, Execution, Deployment > Debugger > Console:
- 取消勾选**"Redirect input from console"**选项,重启PyCharm后重试
- 尝试恢复控制台相关设置为默认值
2. 禁用pytest的输出捕获
- 运行调试时,在pytest参数中添加
-s(禁用stdout/stderr捕获) - 或者在项目根目录创建
pytest.ini文件,添加如下内容:
[pytest] capture = no
3. 更新PyCharm至最新版本
该问题可能是PyCharm与Python 3.11+pytest组合的兼容性bug,更新到最新稳定版可修复此类问题。
4. 重置PyCharm项目配置
- 删除项目根目录下的
.idea文件夹(注意备份重要配置),重新导入项目 - 删除现有pytest调试配置,重新创建新的调试配置
内容的提问来源于stack exchange,提问作者arty
相关产品推荐
相关产品推荐

