【发布时间】:2016-12-02 01:33:32
【问题描述】:
我开始在 Python 中使用 vscode。我有一个简单的测试程序。我想在调试下运行它,我需要为运行设置工作目录。
我该如何/在哪里这样做?
【问题讨论】:
我开始在 Python 中使用 vscode。我有一个简单的测试程序。我想在调试下运行它,我需要为运行设置工作目录。
我该如何/在哪里这样做?
【问题讨论】:
@SpeedCoder5 的评论值得回答;
具体可以指定一个动态的工作目录; (即当前打开的 Python 文件所在的目录),使用 "cwd": "${fileDirname}"——这利用了 "variables reference" feature in VS Code 和预定义变量 fileDirname
如果您在运行 Python 时使用Python: Current File (Integrated Terminal) 选项,您的launch.json 文件可能与我的类似,如下所示(more info on launch.json files here)。
{
"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 ...
}
Remember the launch.json file controls the run/debug settings of your Visual Studio code project;我的launch.json 文件是由VS Code 自动生成的,位于我当前的“打开项目”目录中。我只是手动编辑文件以添加"cwd": "${fileDirname}",如上所示。
请记住launch.json 文件可能特定于您的项目或特定于您的目录,因此请确认您正在编辑正确 launch.json(见评论)
如果你没有launch.json 文件,try this:
要创建 launch.json 文件,请在 VS Code 中打开您的项目文件夹(文件 > 打开文件夹),然后选择调试视图顶部栏上的配置齿轮图标。
【讨论】:
您需要做的就是在launch.json文件中配置cwd设置如下:
{
"name": "Python",
"type": "python",
"pythonPath":"python",
....
"cwd": "<Path to the directory>"
....
}
更多信息可以在on the official VS Code docs website找到。
【讨论】:
"cwd": "${fileDirname}" 在开源文件当前目录运行
此设置对我有帮助:
{
"type": "node",
"request": "launch",
"name": "Launch Program",
"cwd": "${workspaceFolder}\\app\\js", // set directory here
"program": "${workspaceFolder}\\app\\js\\server.js", // set start js here
}
【讨论】:
在某些情况下,将PYTHONPATH 与workspaceFolder 一起设置可能也很有用:
{
"name": "Python: Current File",
"type": "python",
"request": "launch",
"program": "${file}",
"console": "integratedTerminal",
"cwd": "${workspaceFolder}",
"env": {
"PYTHONPATH": "${cwd}"
}
}
【讨论】:
我为在 Node.js 上使用 TypeScript 的人发布此示例配置
在我的项目中,我的 Node.js 服务器 TypeScript 文件位于文件夹 Application_ts 并在名为Application的文件夹中生成编译好的js文件
因为当我们在调试模式下运行我们的应用程序或正常启动它时,我们应该从包含 js 文件的 Application 文件夹开始 所以下面的配置从我的 application_ts 也存在并且完美运行的根文件夹中运行调试
{
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Debug TypeScript in Node.js",
"program": "${workspaceRoot}\\Application\\app.js",
"cwd": "${workspaceRoot}\\Application",
"protocol": "inspector",
"outFiles": [],
"sourceMaps": true
},
{
"type": "node",
"request": "attach",
"name": "Attach to Process",
"port": 5858,
"outFiles": [],
"sourceMaps": true
}
]
}
【讨论】:
您可以使用launch.json 中的cwd 参数为被调试程序设置当前工作目录
【讨论】:
将当前工作目录设置为您当时正在执行的任何文件:
文件 > 首选项 > 设置 > Python > 数据科学 > 在文件目录中执行
谢谢brch:Python in VSCode: Set working directory to python file's path everytime
【讨论】: