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


当前回答

设置当前工作目录为当前正在执行的文件:

File > Preferences > Settings > Python > Data Science >在File Dir执行

brch: Python in VSCode:每次设置工作目录为Python文件的路径

其他回答

你可以在launch.json中使用cwd参数设置调试程序的当前工作目录

在启动时配置cwd设置。Json格式如下:

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

我使用“justMyCode = false”,所以我也可以调试和跳转到主脚本调用的函数。

{
    // Use IntelliSense to learn about possible attributes.    
    // Hover to view descriptions of existing attributes.    
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387    
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Python: Current File",
            "type": "python",
            "request": "launch",
            "program": "${file}",
            "console": "integratedTerminal",
            "justMyCode": false,
            "cwd": "${fileDirname}"        }
    ]
}

这个设置帮助我:(我是一个Windows用户)

{
  "type": "node",
  "request": "launch",
  "name": "Launch Program",
  "cwd": "${workspaceFolder}\\app\\js", // set directory here
  "program": "${workspaceFolder}\\app\\js\\server.js", // set start js here
}

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

在发射。json,指定一个动态工作目录(即当前打开的Python文件所在的目录)使用:

"cwd": "${fileDirname}"

这利用了VS Code中的“变量引用”特性,以及预定义的变量fileDirname。

如果您在运行Python时使用Python: Current File (Integrated Terminal)选项,则您的启动。Json文件可能看起来像我的,下面(更多关于启动的信息。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 ...
}

记住发射。json文件控制Visual Studio代码项目的运行/调试设置;我的发射。json文件是由VS Code自动生成的,在我当前的“Open Project”目录下。我只是手动编辑文件,如上图所示添加“cwd”:“${fileDirname}”。

记住发射。Json文件可能特定于您的项目,或特定于您的目录,所以请确认您正在编辑正确的启动。Json(见注释)

如果你没有发行。Json文件,试试这个:

制造发射。在VS Code中打开你的项目文件夹(文件>打开文件夹),然后选择调试视图顶部栏上的配置齿轮图标。

根据@kbro的评论,你可能会被提示创建一个启动。通过单击Debug按钮来查看json文件:

当我点击导航面板上的调试按钮时,它显示“要自定义运行和调试创建启动”。json文件。”点击“create…”打开一个对话框,询问我正在调试哪种语言。在我的例子中,我选择了Python