-
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...".
-
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.
-
Create/Edit the
launch.jsonFile Debug configurations are stored in the.vscode/launch.jsonfile. 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. -
Set the Working Directory In the
launch.jsonfile, 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".
- 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.