Attaching a VSCode Debugger to a Sub Process in Python

Question:

I have a script that effectively does the following:

top_script.py:

os.system("bash_script.sh")

bash_script.sh

python3 child_script.py

child_script.py

# Actual work goes here

In VSCode, I love the integrated debugger, but when I follow their advice[1] when launching from the IDE, I get “ECONNREFUSED 127.0.0.1:5678”.

When I execute the following from the integrated terminal in VSCode, it runs without the errors, but it doesn’t stop on breakpoints in child_script.py.

python3 -m debugpy --listen 5678 top_script.py

How can I execute the top script first (either from the IDE or command line) and have breakpoints I attach in child_script.py be rendered in VSCode?

[1] https://code.visualstudio.com/docs/python/debugging

Asked By: aronchick

||

Answers:

The problem is that by using os.system() the debugger doesn’t know you started another Python interpreter that you care about. What you will need to do is attach to the second process. Details will vary depending on how you want to set this up, but you can look at https://code.visualstudio.com/docs/python/debugging#_local-script-debugging as a starting point.

Answered By: Brett Cannon

It’s fairly simple. You can add a configuration to your launch.json file like the following:

{
        "name": "MySubProcess",
        "type": "python",
        "request": "attach",
        "processId": "${command:pickProcess}
}

Now start your python process separately (via a prompt, or however). This will generate a python subprocess. You can see this in Windows Task Manager (or also in MacOS Activity monitor, or in Linux a similar way).

In VSCode, then click Debug, (select your subprocess configuration: "MySubProcess" in our example above), and then choose the process which was just started. The debugger will then stop at the breakpoints in your subprocess code.

Answered By: RexBarker

I followed RexBarker’s suggestion, but VSC always gave me an error of "Timed out waiting for debug server to connect". In order to find out the cause, the "log to file" was enabled in the Configuration like below,

{
    "name": "MySubProcess",
    "type": "python",
    "request": "attach",
    "processId": "${command:pickProcess}",
    "logToFile": true
}

Then I could find the detailed error in the log file on the VSC host, which is located at ~/.local/share/code-server/extensions/ms-python.python-2021.5.926500501/debugpy.adapter-{pid}.log

It told me ‘gdb’ not found. After I installed gdb, it works as expected.

Answered By: SZ Yang