Search code examples
pythonvisual-studio-codevscode-debugger

VSC Python: required and optional args in launch.json


I'm working in Visual Studio Code with Python on a project that is called with main(args). There are optional and required arguments. The code looks like this:

import sys
import argparse

def main(args):
    print(args.mode)
    print(args.path)
    return 0

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--mode", type=str, choices=["opt1","opt2"], default="opt1")
    parser.add_argument("path", type=str)
    args = parser.parse_args()
    sys.exit(main(args))

Now I want to debug the code in VSC and use a launch.json file for this process to speed it up. How do I setup my launch.json file correctly for both arguments?

Currently my launch.json looks like this:

{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "something",
            "type": "python",
            "request": "launch",
            "program": "%{file}",
            "args": [
                "--mode","opt2",
                "path","~/some_path",
            ],
            "console": "integratedTerminal"
        }
    ]
}

I'm getting an error every time I start the debug process: error: the following arguments are required: path Does anybody know what I'm doing wrong?

Thanks for your help!


Solution

  • I now found a solution. So I have made 2 mistakes here:

    1. The args statement in launch.json is wrong
    2. The args specified are not passed to the debugger

    To 1

    Since I need an optional argument e.g. --mode AND a required argument e.g. path the correct syntax in the launch.json is:

    "args": ["--mode=opt2", "~/path_to_some_folder"],
    

    To 2

    In order to ensure that the launch options specified in launch.json are being used by the debugger simply add "purpose": ["debug-in-terminal"] to it.