在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
相关产品推荐
相关产品推荐

