VS Code终端运行Python代码块时自动增缩进的问题求助
修复步骤:
检查Python扩展交互窗口缩进设置
打开VS Code设置(快捷键Ctrl+,),搜索python.interactiveWindow.indentOnEnter,将其设置为false,避免交互窗口自动叠加缩进;同时检查python.sendSelectionToInteractiveWindow的相关配置,确保没有开启额外的缩进处理规则。统一编辑器与代码的缩进配置
在设置中确认editor.detectIndentation为开启状态,editor.tabSize和editor.insertSpaces与你的代码缩进规则一致(比如用4空格缩进就把tabSize设为4)。也可以在当前工作区的.vscode/settings.json中添加以下配置,强制统一缩进:{ "editor.tabSize": 4, "editor.insertSpaces": true, "editor.detectIndentation": true }切换运行方式或终端类型
暂时改用右键代码块选择Run Selection/Line in Python Interactive Window运行,替代Shift+Enter的终端运行方式;或者把终端从当前类型切换为Command Prompt(Windows)、Bash(Linux/macOS),排查终端适配问题。更新或重装Python扩展
打开扩展面板找到Python扩展,检查并安装最新更新,重启VS Code;若问题仍存在,卸载扩展后重新安装,清除可能的更新残留bug。清除工作区缓存
关闭所有VS Code窗口,删除对应工作区的缓存目录:- Windows:
%APPDATA%\Code\User\workspaceStorage - macOS:
~/Library/Application Support/Code/User/workspaceStorage - Linux:
~/.config/Code/User/workspaceStorage
重新打开VS Code后再测试代码运行。
- Windows:
问题复现细节:
当选中多行同级缩进的代码块(如下方带两行print的for循环),按Shift+Enter运行时,终端会给第一行后的代码逐次叠加额外缩进:
编辑器原代码:
for i in range (0,2): print(i) print("test")
首次运行终端输出:
>>> for i in range (0,2): ... print(i) ... print("test") ... File "<python-input-1>", line 3 print("test") IndentationError: unexpected indent >>>
再次运行同一代码块,缩进会进一步累积,触发相同错误。但调试器运行无异常,仅含一行缩进的代码块也能正常执行。
内容的提问来源于stack exchange,提问作者Girrr

