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

在Jupyter Notebook中运行含input()的Python文件时无输入弹窗问题求助

解决方案
  • 使用Jupyter魔法命令%run替代!python
    直接在Notebook单元格中执行:

    %run test.py
    

    运行后会在单元格下方自动弹出输入框,输入内容后程序即可继续执行,这是最直接的交互方式。

  • 通过命令行参数传递输入内容
    修改test.py脚本,支持从命令行参数读取输入:

    import sys
    
    # 优先读取命令行参数,没有则 fallback 到 input
    if len(sys.argv) > 1:
        txt = sys.argv[1]
    else:
        txt = input("input text")
    print(txt)
    

    然后在Notebook中执行:

    !python test.py "你的输入文本"
    
  • 用subprocess模块手动处理输入输出
    在Notebook单元格中编写代码,通过subprocess主动传入输入内容:

    import subprocess
    
    # 启动子进程并传入输入
    proc = subprocess.Popen(
        ['python', 'test.py'],
        stdin=subprocess.PIPE,
        stdout=subprocess.PIPE,
        text=True
    )
    # 传入输入内容(注意加换行符模拟回车)
    output, _ = proc.communicate(input="你的输入内容\n")
    print(output)
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 16:33:09