0

I have this command, made with argparse, that can either submit or read an item.

Here is a dummy version of what I am trying to do:

if __name__ == "__main__":

    # Create the CLI Arguments parser
    parser = argparse.ArgumentParser(prog="dummy",
        allow_abbrev=False,
        description="Dummy command for StackOverflow")

    # Create subparsers to add several commands
    subparsers = parser.add_subparsers(help="CLI options")

    # Command to submit
    submit_parser = subparsers.add_parser("submit", help="Submit a new Job")
    #submit_parser.set_defaults(func=sub)
    submit_parser.add_argument("job_id", type=str, help="The Job ID")
    submit_parser.add_argument("job_file", type=str, help="Path to the Job file")

    # Command to read Job
    status_parser = subparsers.add_parser("read", help="Read the Job Status")
    #status_parser.set_defaults(func=status)
    status_parser.add_argument("job_id", help="The Job ID")

    # Parse the command
    parse_res = parser.parse_args()
    #parse_res.func(parse_res)

Now, if I type mycommand -h, I get what I expect:

command help

If I try to use the sub commands without their arguments, I get what I expect as well:

Correct error for submit

Correct error for read

But if i put nothing, no argument, just the naked command, I get nothing. No output, no print, no help, no error. Worse: if I try to associate functions to the sub commands, the naked command raises this error:

Error with empty command

How do I get ArgParse to print an help or an error when the command has no argument, just like the sub commands do ?

Gaëtan
  • 779
  • 1
  • 8
  • 26
  • 1
    If you want the subcommands to be required, pass `required=True` when you call [`add_subparsers`](https://docs.python.org/3/library/argparse.html#argparse.ArgumentParser.add_subparsers). – Brian61354270 Mar 08 '22 at 19:08
  • 1
    `parser.add_subparsers(dest='cmd', required=True, help="CLI options")`. The `dest` isn't necessary on the latest versions, but still a good idea when you expect a error message about missing subparsers. – hpaulj Mar 08 '22 at 19:10
  • @Brian, while your link works, it goes back to 2013. – hpaulj Mar 08 '22 at 19:11
  • During debugging, include a `print(parse_res)`. That will give you a clearer idea of what the parser has found. In this case, there's not point to trying to use `parse_res.func` if the `func` attributes hasn't been set. The whole point to using `submit_parser.set_defaults(func=sub)` is to set that attribute to a specific value only when that particular subparse is used. It is not set if no subparser is used. – hpaulj Mar 08 '22 at 20:29

0 Answers0