10

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?

megayeye
  • 101
  • 4
  • Does this answer your question? [How to set environment variables in vscode for debugging?](https://stackoverflow.com/questions/71381536/how-to-set-environment-variables-in-vscode-for-debugging) – Welgriv Feb 08 '23 at 14:34
  • It seems to be the same answer but using powershell instead of a Linux / MacOS terminal, which at least on Mac doesn't work and the debugger command isn't run after the script is run. – Fatlad Feb 28 '23 at 23:04

2 Answers2

0

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.

Merramore
  • 1
  • 1
-6

You can have a try on Task, For example:

tasks.json file:

{
    "version": "2.0.0",
    "tasks": [
        {
            "label": "Task Name",
            "type": "shell",
            "command":"the commands you want to execute",
        }
    ]
}

And add this in the launch.json file:

"preLaunchTask": "Task Name",

You can refer to the official docs for more details.

Steven-MSFT
  • 7,438
  • 1
  • 5
  • 13
  • 7
    Tasks run in a separate shell, and does not allow you to affect the debug environment/to source a script in a way that affects the debug-environment. – Tobias Bergkvist Jul 26 '22 at 09:52