Windows系统下VS Code中Python REPL发送代码异常问题求助
修复Windows下VS Code发送Python代码到Terminal REPL的KeyboardInterrupt问题
问题根源
Windows终端(尤其是PowerShell)与VS Code Python扩展的代码发送逻辑存在交互冲突;未安装Jupyter扩展时,原快捷键配置中的Jupyter相关判断条件可能引发异常;同时Python终端的缓冲机制也会导致输入中断触发。
解决方案
1. 更换默认终端类型
PowerShell的交互处理逻辑易与Python REPL冲突,建议切换为Command Prompt或WSL终端:
- 按下
Ctrl+Shift+P打开命令面板 - 输入
Terminal: Select Default Profile - 选择Command Prompt或WSL(若使用Windows子系统Linux)作为默认终端
2. 调整Python扩展的代码发送配置
在VS Code的settings.json中添加以下配置,优化代码发送行为:
"python.sendSelectionToTerminal": { "withoutRepl": true, "useFile": false }, "python.terminal.env": { "PYTHONUNBUFFERED": "1" }
withoutRepl: 确保直接向终端发送代码,不依赖REPL的特殊处理逻辑PYTHONUNBUFFERED=1: 禁用Python终端的输出缓冲,避免输入时触发中断
3. 简化快捷键的判断条件
原配置中的Jupyter相关条件在未安装Jupyter扩展时冗余且可能引发判断异常,修改快捷键配置为:
[ { "key": "ctrl+enter", "command": "python.execSelectionInTerminal", "when": "editorTextFocus && editorLangId == 'python' && !findInputFocussed && !replaceInputFocussed" }, { "key": "shift+enter", "command": "-python.execSelectionInTerminal", "when": "editorTextFocus && editorLangId == 'python' && !findInputFocussed && !replaceInputFocussed" } ]
去掉所有与Jupyter相关的判断项,避免无扩展时的逻辑错误。
4. 临时应急方案(若上述配置无效)
在发送代码前,先在Python终端中执行以下命令,强制重置标准输入流:
import sys; sys.stdin = open(0)
此操作可修复REPL的交互状态,避免KeyboardInterrupt触发。
内容的提问来源于stack exchange,提问作者Lee Hachadoorian
相关产品推荐
相关产品推荐

