Debugging Pi from VSCode

There’s a few tutorials and references for debugging a python program on a remote (e.g. pi) computer. I had to fiddle a fair bit to get VSCode, ssh and debugpy to work. Here is how.

Traps and Notes

  • ptvsd is depreceated
  • run everything the command line first
  • use “ss -ntlp4” to view open ports on the remote (check for 5678, the debug port)
  • use “ps -aux | grep python3” to see what’s running on the remote

References

Setup

Get key-based ssh setup so this works

mypc>ssh mypi
* logins in automatically *
mypi>

Make a new VSCode python project and add a program:

import debugpy
import socket

# Allow other computers to attach to debugpy at this IP address and port.
print("starting")
print(f"hostname: {socket.gethostname()}")
print("bye")

Add a .vscode folder and configure the launch process.

// launch.json
{
  "version": "0.2.0",
  "configurations": [
{
    "name": "Python: RunAndAttach",
    "type": "python",
    "request": "attach",
    "port": 5678,
    "host": "lunchbox",
    "pathMappings": [
      {
        "localRoot": "${workspaceFolder}", 
        "remoteRoot": "~/${workspaceFolderBasename}/" // To current working directory ~/project1
      }
    ],
    "preLaunchTask": "copyAndStartOnRemote",
    "postDebugTask": "cleanupOnRemote"
  },  
]

and setup commands/tasks:

{
    "version": "2.0.0",
    "tasks": [
        {
            "label": "copyToRemote",
            "type": "shell",
            "command": "scp ${file} ${config:sshUser}@${config:sshEndpoint}:~/${workspaceFolderBasename}/${fileBasename}" 
        },
        {
            "label": "startOnRemote",
            "type": "shell",
            "command": "ssh -f ${config:sshUser}@${config:sshEndpoint} 'python3 -m debugpy --wait-for-client --listen 0.0.0.0:5678 ~/${workspaceFolderBasename}/${fileBasename} > /dev/null 2>&1'"
        },
        {
            "label": "wait",
            "type": "shell",
            "command": "sleep 10"
        },
        {
            "label": "copyAndStartOnRemote",
            "dependsOrder": "sequence",
            "dependsOn": ["copyToRemote", "startOnRemote", "wait"]
        },
        {
            "label": "cleanupOnRemote",
            "type": "shell",
            "command": "ssh ${config:sshUser}@${config:sshEndpoint} 'killall -9 --younger-than 1h python3'"
        },
    ]    

}

Configure your settings:

{
    "python.pythonPath": "/home/bbeeson/pdb/venv/bin/python3",
    "sshUser" : "pi",
    "sshEndpoint": "lunchbox"
}

Double check a folder exists on the remote (in this example ~/pdb) and ssh works. Install debugpy on both machines:

venv>python3 -m pip install debugpy
venv>ssh remote
remote>python3 -m pip install debugpy

Select the testy.py file in vscode, debugging mode (left side play/bug symbol ) and run the “RunAndAttach”.

Leave a Reply

Your email address will not be published. Required fields are marked *