Created
May 3, 2021 03:29
-
-
Save sumanthkumarc/95bcd2b00677010b497a871c7548d51e to your computer and use it in GitHub Desktop.
Custom Argument Parser class to use argparse in REST api app
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from argparse import ArgumentParser | |
import sys as _sys | |
# Tested on Python 3.8. For version >=3.9, There is new exit_on_error flag in init function. | |
# Although it doesn't entirely help our use case, we should be passing our flag `exit_on_error` | |
# to the parent class init function. | |
class CustomArgumentParser(ArgumentParser): | |
def __init__(self, prog=None, exit_on_error=False): | |
self.exit_on_error = exit_on_error | |
super().__init__(prog=prog) | |
def exit(self, status=0, message=None): | |
if message: | |
self._print_message(message, _sys.stdout) | |
if self.exit_on_error: | |
_sys.exit(status) | |
def error(self, message): | |
"""error(message: string) | |
Prints a usage message incorporating the message to stdout and | |
exits if respective class is provided. | |
""" | |
self.print_usage(_sys.stdout) | |
args = {"prog": self.prog, "message": message} | |
self.exit(2, "%(prog)s: error: %(message)s\n" % args) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment