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

VS Code扩展开发:如何从扩展中访问调试变量?

如何在VS Code扩展中获取调试会话的变量

完全可以做到!你不需要自己实现调试器,VS Code的Debug API支持通过Debug Adapter Protocol (DAP) 来获取调试面板「VARIABLES」区域的变量数据。下面是具体的实现步骤和代码示例:

首先要明确几个核心前提:

  • 只有当调试会话处于暂停状态(比如命中断点)时,才能获取到变量数据
  • 变量是和当前栈帧(Stack Frame)绑定的,必须先获取当前栈帧的信息
  • 我们需要通过vscode.debug.activeDebugSession.customRequest()方法发送DAP标准请求来拉取变量

接下来替换你extension.ts里的命令代码:

export function activate(context: vscode.ExtensionContext) {
    let disposable = vscode.commands.registerCommand('extension.showVariables', async () => {
        // 1. 检查是否存在活跃的调试会话
        const session = vscode.debug.activeDebugSession;
        if (!session) {
            vscode.window.showErrorMessage('没有活跃的调试会话,请先启动调试!');
            return;
        }

        // 2. 确认调试会话处于暂停状态
        if (session.state !== vscode.DebugSessionState.Stopped) {
            vscode.window.showErrorMessage('调试会话未暂停,请先命中断点!');
            return;
        }

        try {
            // 3. 获取当前线程的栈帧列表(默认取主线程,threadId=1)
            const stackTraceResp = await session.customRequest('stackTrace', {
                threadId: 1,
                startFrame: 0,
                levels: 1 // 只获取当前最顶层的栈帧
            });

            if (!stackTraceResp.stackFrames?.length) {
                vscode.window.showErrorMessage('无法获取当前栈帧信息!');
                return;
            }
            const currentFrame = stackTraceResp.stackFrames[0];

            // 4. 获取当前栈帧的变量作用域(比如Local、Global、Closure等)
            const scopesResp = await session.customRequest('scopes', {
                frameId: currentFrame.id
            });

            if (!scopesResp.scopes?.length) {
                vscode.window.showErrorMessage('无法获取变量作用域!');
                return;
            }

            // 5. 遍历每个作用域,获取对应的变量
            let variablesContent = '';
            for (const scope of scopesResp.scopes) {
                variablesContent += `=== ${scope.name} ===\n`;
                
                const variablesResp = await session.customRequest('variables', {
                    variablesReference: scope.variablesReference
                });

                if (variablesResp.variables) {
                    variablesResp.variables.forEach(variable => {
                        variablesContent += `${variable.name}: ${variable.value}\n`;
                    });
                }
                variablesContent += '\n';
            }

            // 6. 展示变量信息
            vscode.window.showInformationMessage('当前调试变量:\n' + variablesContent);
        } catch (err) {
            vscode.window.showErrorMessage(`获取变量失败: ${err}`);
        }
    });

    context.subscriptions.push(disposable);
}

关键细节说明:

  • 线程ID处理:示例中用了固定的threadId:1(对应主线程),如果需要支持多线程调试,可以先通过threads请求获取所有线程列表,再让用户选择目标线程
  • 嵌套变量展开:如果需要获取对象的嵌套属性,可以在variables请求中传入filter: 'children'和start: 0等参数,递归拉取子变量
  • 兼容性:stackTrace、scopes、variables都是DAP标准请求,主流调试适配器(Node.js、Chrome、Python等)都支持

这样修改后,当用户在调试暂停状态下右键编辑器执行命令,就能看到当前栈帧的所有变量了!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 07:13:09