Python调试时如何复用已有外部终端会话,避免每次打开新窗口?
macOS iTerm2 Python调试外部终端会话问题解决方案
1. 复用同一个iTerm2会话的实现方法
VS Code Python调试插件原生不支持直接复用externalTerminal模式的会话,可通过自定义启动脚本实现:
- 第一步:写AppleScript脚本保存为
launch_iterm.scpt,逻辑为检测是否存在已打开的调试专用会话,存在则直接在该会话执行命令,不存在则新建:
on run argv set cmd to item 1 of argv tell application "iTerm" if exists current window then tell current window select last tab tell current session write text cmd end tell end tell else create window with default profile tell current window tell current session write text cmd end tell end tell end if end tell end run
- 第二步:打开VS Code设置,搜索
terminal.external.osxExec,将值修改为osascript /path/to/your/launch_iterm.scpt(替换为你脚本的实际路径)。 - 第三步:保留你现有launch.json的
"console": "externalTerminal"配置即可,之后调试都会复用最近的iTerm会话。
2. 自动关闭旧会话的设置方法
如果不需要复用,可通过以下两种方式避免多窗口堆叠:
方式1:修改iTerm2全局配置(推荐,无额外代码)
打开iTerm2 → 偏好设置(⌘,)→ Profiles → 选中你正在使用的默认配置文件 → General标签 → 找到「Session ends」下拉菜单,选择「Close the session」,即可让调试结束后自动关闭对应窗口。
方式2:修改launch.json配置实现自动关闭
在你的外部终端调试配置中添加postDebugTask参数,搭配VS Code任务自动关闭旧会话,参考配置如下:
{ "version": "0.2.0", "configurations": [ { "name": "Python: Current File (External)", "type": "python", "request": "launch", "program": "${file}", "console": "externalTerminal", "python": "/Users/josip/.virtualenvs/myproject-JnedzVU7/bin/python", "postDebugTask": "close-old-iterm-session" } ] }
然后在.vscode文件夹下新建tasks.json,添加对应关闭任务:
{ "version": "2.0.0", "tasks": [ { "label": "close-old-iterm-session", "type": "shell", "command": "osascript -e 'tell application \"iTerm\" to close (every session of current window whose name contains \"python\")'", "problemMatcher": [] } ] }
内容的提问来源于stack exchange,提问作者Joël Brigate
相关产品推荐
相关产品推荐

