I am working with ROS. ROS needs to source a few scripts e.g., /opt/ros/noetic/setup.sh before running any python programs. Otherwise I cannot import roslib or similar stuffs.
When I debug with vscode, is there any way to let vscode to source this script automatically before starting the debugger?
If your launch script allows you to specify a python target (and finishes quickly enough), you can use pythonArgs in launch.json to insert a shim.
.vscode/launch.json
{
"version": "0.2.0",
"configurations": [
{
"name": "Launch via Shell Script",
"type": "python",
"pythonArgs": ["debug_shim.py", "launch.sh"],
"args": ["your", "app", "args"],
"request": "launch",
"program": "app.py"
}
]
}
debug_shim.py
import os, subprocess, sys
launcher, debugger, debugger_args = sys.argv[1], sys.argv[2], sys.argv[3:]
sys.exit(subprocess.run(
args=[launcher] + debugger_args,
env=dict(os.environ, LAUNCH_TARGET=debugger),
stdin=sys.stdin,
stdout=sys.stdout,
stderr=sys.stderr,
).returncode)
launch.sh
#!/usr/bin/env bash
# Or target could be passed along the command line as well.
# LAUNCH_TARGET="${1?}"
# ...stuff...
python "${LAUNCH_TARGET-app.py}" "${@}"
In my setup of v1.80.0 on WSL2, the debugger call is like so:
python python_args... debugger debugger_args... app app_args...
Then the call stack will be vscode -> shim -> launcher -> debugger -> app and the debugger will connect seamlessly, although if it takes more than several seconds VSCode will time out.
Adding the setup scripts to your .bashrc file will ensure that they are sourced before vscode begins debugging your program. The ROS2 documentation supports this method and provides an example.
In your .bashrc file add the following:
source /opt/ros/${ROS_DISTRO}/setup.bash
source ~/ros2_ws/install/local_setup.bash
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With