You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中def函数无法接收输入:pytest捕获输出引发OSError

问题原因

这个错误的核心原因是pytest默认会捕获程序的输出(stdout/stderr),同时禁用了标准输入(stdin)的读取功能。你的代码里调用了input()函数试图从stdin获取手动输入,而pytest的这个机制是为了避免测试过程中因为等待用户输入而卡住,所以直接抛出了这个OSError。

解决方法
  • 临时允许stdin输入:运行pytest时加上-s参数,禁用输出捕获,让input()能正常读取你的手动输入:
    pytest your_test_file.py -s
    
  • 编写自动化测试(推荐):如果是为了做测试,不要依赖手动输入,用pytest的monkeypatch fixture模拟input()的返回值,示例代码:
    def test_play(monkeypatch):
        # 模拟用户输入"5"
        monkeypatch.setattr('builtins.input', lambda prompt: "5")
        play([])  # 传入game_words参数,这里用空列表作为示例
    
  • 直接用Python运行脚本:如果只是想运行代码而不是测试,跳过pytest,直接用Python解释器执行:
    python your_script.py
    

内容的提问来源于stack exchange,提问作者Daniel Wiesel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 13:32:12