ROS Resources: Documentation | Support | Discussion Forum | Index | Service Status | ros @ Robotics Stack Exchange
Ask Your Question

Revision history [back]

Assume the file we want to run using the ROS launch file is test.py. Make it executable. The contents of the file should be following:

#!/usr/bin/python
import debugpy

debugpy.listen(5678)
debugpy.wait_for_client()
import os

a = 34
print("Dexter Rocks")

It would be best if you had the below snippet always at the top:

#!/usr/bin/python
import debugpy

debugpy.listen(5678)
debugpy.wait_for_client()

This snippet will pause the execution further and wait for VSCode to connect. Once the VSCode connects, it starts the execution. Now have the below configuration for your VSCode's launch.json

{
    // 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": "attach",
            "program": "${file}",
            "connect": {
                "host": "localhost",
                "port": 5678
            }
        }
    ]
}

Remember to have port numbers the same (5678 in our case). That's it. Now run your python file in ROS launch file, and the python execution pauses and waits for VSCode to connect. Once the VSCode connects, it will automatically stop at the debug point set in the VSCode.

This method is useful in general not only with ROS but for every other method where the python file gets executed by some other process and you want to connect to the process and start debugging it. Hope it helps. Thank you.