'argparse subparser exit_on_error

I want to disable exit_on_error for a parser and subparser, to prevent error messages:

import argparse


if __name__ == '__main__':

    parser = argparse.ArgumentParser(exit_on_error=False)
       
    subparsers = parser.add_subparsers() 
   
    subcommand = subparsers.add_parser('subcommand')
    subcommand.add_argument('argument')
   
    try:
        arguments = parser.parse_args()
    except:
        parser.print_usage(std.stderr)

With no arguments (ie: no subparser invoked) it works as intended:

$ python3 main.py 
usage: main.py {subcommand} ...

But when I use a subcommand, it doesn't:

$ python3 main.py subcommand
usage: main.py subcommand [-h] argument
main.py subcommand: error: the following arguments are required: argument
usage: main.py {subcommand} ...

In this instance, I'd want it to print this instead:

$ python3 main.py subcommand
usage: main.py {subcommand} ...

I checked, and neither add_subparsers nor add_parser take an exit_on_error argument. How can I suppress printing those error messages?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source