乐闻世界logo
搜索文章和话题

How to set the working directory for debugging a Python program in VS Code?

1个答案

1
  1. Open the Workspace First, ensure that you have opened the folder containing your Python project as the workspace. You can select and open your project folder in VS Code by clicking "File" > "Open Folder...".

  2. Install the Python Extension In VS Code, confirm that the official Python extension is installed. Click the Extensions icon in the Activity Bar (or use the shortcut Ctrl+Shift+X), search for "Python", and install the Microsoft-provided Python extension.

  3. Create/Edit the launch.json File Debug configurations are stored in the .vscode/launch.json file. To create this file (if it doesn't exist), click the Run and Debug icon in the Activity Bar (or press Ctrl+Shift+D) and select "Create launch.json file". Choose the configuration environment for your Python file.

  4. Set the Working Directory In the launch.json file, configure the working directory for each debug configuration by adding or editing the "cwd" attribute (representing the current working directory). For example, to set the working directory to the project root, use:

json
{ "version": "0.2.0", "configurations": [ { "name": "Python: Current File", "type": "python", "request": "launch", "program": "${file}", "cwd": "${workspaceFolder}" } ] }

Here, "${workspaceFolder}" is a variable referencing the root directory opened in VS Code. You can also set it to any subdirectory within the project, such as "${workspaceFolder}/subfolder".

  1. Start Debugging After setting the working directory, return to the Run and Debug view, select the configured debug mode (e.g., "Python: Current File") from the configuration dropdown menu, and click the green Start Debugging button or press F5 to begin debugging.

By following these steps, you ensure VS Code uses the correct working directory during Python debugging, which is essential for projects with path dependencies or specific directory requirements.

2024年8月10日 08:16 回复

你的答案