Debugging Python in VSCode

This demonstrates the usage of the Python debugger in VS Code with the ability to pass arguments.

To use the Python debugger in VS Code and pass arguments, follow these steps:

  1. Set breakpoints in your code by clicking on the left gutter of the desired line(s) or by using the keyboard shortcut F9.
  2. Open the Debug view in VS Code by clicking on the bug icon in the sidebar or by using the keyboard shortcut Ctrl+Shift+D.
  3. Select the “Python: Current File” configuration from the dropdown menu in the Debug view.
  4. If you need to pass arguments to your script, open the launch.json file by clicking on the gear icon in the Debug view and selecting “Open launch.json”.
  5. In the “args” section of the launch.json file, specify the arguments you want to pass as an array. For example:
     "args": ["arg1", "arg2"]
    
  6. Save the launch.json file.

    launch.json file with arguments

     {
         // 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": true,
                 "args": ["arg1", "arg2"]
             }
         ]
     }
    
  7. Add the following line to indicate to vscode to use the parameters when debugging or running python files: “purpose”: [“debug-in-terminal”] Reference: https://stackoverflow.com/questions/70357348/cannot-get-vs-code-to-pass-arguments-to-python-from-launch-json
  8. Start the debugger by clicking on the green play button in the Debug view or by using the keyboard shortcut F5.
  9. The debugger will stop at the breakpoints you set, allowing you to step through the code and inspect variables.

Note: Make sure you have the Python extension installed in VS Code before using the debugger.

Related:

Journal