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

如何在VS Code中通过Python调试器调试被调用的Rust代码?

如何在VS Code中调试Python调用的Rust代码

当然可以实现跨语言调试,核心是用VS Code的C/C++调试器附加到Python进程,配合带调试信息的Rust编译产物。下面是具体操作步骤:

1. 确保Rust代码带调试符号编译

默认cargo build会生成debug版本(包含完整调试符号),如果用maturin等绑定工具,要添加--profile debug参数(比如maturin develop --profile debug)。绝对不能用release模式编译,否则调试器无法识别Rust源码的调试信息。

2. 配置VS Code混合调试环境

首先安装C/C++ Extension Pack插件,这是调试Rust底层代码的必要工具。然后修改.vscode/launch.json,添加C/C++附加调试配置,甚至可以配置复合调试一键启动双调试器:

{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Python: Current File",
            "type": "python",
            "request": "launch",
            "program": "${file}",
            "console": "integratedTerminal",
            "stopOnEntry": true,
            "justMyCode": false,
            "preLaunchTask": "build-rust-debug" // 可选:自动编译Rust debug版本
        },
        {
            "name": "C/C++: Attach to Python",
            "type": "cppdbg",
            "request": "attach",
            "program": "${command:python.interpreterPath}", // 自动获取当前Python解释器路径
            "processId": "${command:pickProcess}", // 弹出选择框选择正在运行的Python进程
            "MIMode": "lldb", // macOS/Linux用lldb,Windows替换为vsdbg
            "sourceFileMap": {
                "/your/rust/project/absolute/path": "${workspaceFolder}/rust" // 映射Rust源码路径,避免调试器找不到代码
            },
            "additionalSOLibSearchPath": "${workspaceFolder}/target/debug" // 指定Rust调试库的路径
        }
    ],
    "compounds": [
        {
            "name": "Python + Rust Debug",
            "configurations": ["Python: Current File", "C/C++: Attach to Python"],
            "stopAll": true
        }
    ]
}

如果使用了上面的preLaunchTask,新建.vscode/tasks.json来自动编译Rust:

{
    "version": "2.0.0",
    "tasks": [
        {
            "label": "build-rust-debug",
            "type": "shell",
            "command": "cargo build", // 若用其他绑定工具,替换为对应编译命令
            "group": "build",
            "problemMatcher": ["$rustc"],
            "presentation": {
                "reveal": "silent"
            }
        }
    ]
}

3. 启动调试

  • 打开你的Python主文件,在调试面板选择Python + Rust Debug启动。
  • 启动后会先进入Python调试,停在stopOnEntry的位置;接着弹出进程选择窗口,选中当前运行的Python进程。
  • 在Rust代码中设置断点,当Python调用到Rust函数时,断点会触发,即可像调试纯Rust代码一样单步执行、查看变量。

注意事项

  • Windows系统下,MIMode需改为vsdbg,且要安装Visual Studio的调试工具组件。
  • 确保Python加载的是debug版本的Rust共享库,不要误加载release版本。
  • 如果调试器只显示反汇编而非Rust源码,检查sourceFileMap的路径映射是否正确,需和Rust编译时的绝对路径对应。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 04:30:38