published: 25th of October 2024
Imagine you have a Python library that installs a CLI program. You want to run a debugger that calls the CLI program with different arguments and stops at particular breakpoints. You can apparently do this in VSCode with a launch configuration.
I had a pretty frustrating experience trying to get this working. This post covers the steps I used to get a working debugging session going for a Python CLI program.
I am pretty certain that this methods is not the best way to do it, but it's the only way I could get it working. If you have any good references, please hit me up on xitter.
The following software versions were used in this post.
Firstly, if you are using a virtual envrionment make sure you set the workspace to use the virtual environments Python interpreter.
Create a launch.json file in the root of the workspace.
{
"version": "0.2.0",
"configurations": [
{
"name": "Debug CLI Program",
"type": "debugpy",
"request": "launch",
"cwd": "${workspaceFolder}",
"program": "${workspaceFolder}/testing.py",
"args": [],
"env": {
"ENV_VAR_ONE": "${env:ENV_VAR_ONE}",
"ENV_VAR_TWO": "${env:ENV_VAR_TWO}"
}
}
]
}
Create a testing.py file in the root of the workspace that will be run from the launch.json file. In this file, set the CLI arguments that you would normally call from the command line.
import os
import sys
from src.package import some_file
args = [
f"--url={os.environ['ENV_VAR_ONE']}",
f"--token={os.environ['ENV_VAR_TWO']}",
"--d=debug",
"--site=hell",
]
sys.argv.extend(args)
some_file.main()
Now, set the debug symbols in the desired locations in your CLI library. Then, select the testing.py file and start the debugger using the launch.json file.
Finally, when the debugger runs, it will be as if the CLI program was called with the specified arguemnts and the debugger will pause at the debug symbols.
Buggered if I know if there is a better way to do it. This works for me, so it's good enough for now. If you are also struggling with this scenario, I hope this post may alleviate some of your pain. If you have a better method, please hit me up on xitter. Link down 👇🏾