How to avoid exiting the program when python argparse uses [- h]

argparse displays help when using [- h] and then exits. How can I not quit the interface and wait for the next input?

while True:
    cmd = input(">>>")
    parser = argparse.ArgumentParser()
    parser.add_argument("-f", help="foo")
    parser.parse_args(cmd.split())

when entering [- h] like this:

>>>-h
usage: test.py [-h] [-f F]

optional arguments:
  -h, --help  show this help message and exit
  -f F        foo
The

program is over. Now I only need "show this help message"," instead of "exit",". What can I do? Thank you!

Mar.03,2021

The root cause of

is that argparse.parse_args () executes sys.exit () in the event of an error and -h . This can be solved by catching SystemExit exceptions:

    def exit(self, status=0, message=None):
        if message:
            self._print_message(message, _sys.stderr)
        _sys.exit(status)

    def error(self, message):
        """error(message: string)

        Prints a usage message incorporating the message to stderr and
        exits.

        If you override this in a subclass, it should not return -- it
        should either exit or raise an exception.
        """
        self.print_usage(_sys.stderr)
        args = {'prog': self.prog, 'message': message}
        self.exit(2, _('%(prog)s: error: %(message)s\n') % args)
Menu