VSCode -- 如何设置调试 Python 程序的工作目录

新手上路,请多包涵

如何在调试下运行 Python 程序并设置运行的工作目录?

原文由 user1443098 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.5k
2 个回答

@SpeedCoder5 的评论 应该是一个答案。

launch.json 中,使用以下命令指定动态工作目录(即当前打开的 Python 文件所在的目录):

 "cwd": "${fileDirname}"

这利用了 VS Code 中的“变量引用”功能 和预定义变量 fileDirname

如果您在运行 Python 时使用 Python: Current File (Integrated Terminal) 选项,您的 launch.json 文件可能看起来像我的,如下( 有关 launch.json 的更多信息)。

 {
    "version": "0.2.0",
    "configurations": [
    {
            "name": "Python: Current File (Integrated Terminal)",
            "type": "python",
            "request": "launch",
            "program": "${file}",
            "console": "integratedTerminal",
            "cwd": "${fileDirname}"
    },

    //... other settings, but I modified the "Current File" setting above ...
}

请记住 launch.json 文件控制 Visual Studio 代码项目的运行/调试设置;我的 launch.json 文件是由 VS Code 在我当前的“打开项目”目录中自动生成的。我只是手动编辑文件以添加 "cwd": "${fileDirname}" 如上所示。

请记住 launch.json 文件可能特定于您的项目或特定于您的目录,因此请确认您正在编辑 正确launch.json (请参阅评论)

如果你没有 launch.json 文件, 试试这个

要创建 launch.json 文件,请在 VS Code 中打开项目文件夹(文件 > 打开文件夹),然后选择调试视图顶部栏上的配置齿轮图标。

原文由 The Red Pea 发布,翻译遵循 CC BY-SA 4.0 许可协议

配置 cwd 设置 launch.json 如下:

 {
    "name": "Python",
    "type": "python",
    "pythonPath": "python",
    ...
    "cwd": "<Path to the directory>"
    ...
}

原文由 Don 发布,翻译遵循 CC BY-SA 4.0 许可协议

推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏