Created
September 12, 2013 21:02
-
-
Save jmoiron/6543743 to your computer and use it in GitHub Desktop.
allow certain arguments to short circuit required positional arguments and other argparse errors
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
#!/usr/bin/env python | |
# I had a script which I wanted to have a special option that short-circuited the normal | |
# argument parsing error handling behavior so that it could be run without thenormal | |
# required arguments. This option would work similar to how `--help` or `--version` | |
# works, except that the parser would return a valid args object in its presence | |
# rather than exiting the program. | |
import argparse | |
class Parser(argparse.ArgumentParser): | |
has_errors = False | |
def error(self, message): | |
self.has_errors = True | |
self.error_message = message | |
def handle_error(self): | |
if self.has_errors: | |
super(Parser, self).error(self.error_message) | |
parser = Parser(description='description') | |
parser.add_argument('a', type=int, help='a') | |
parser.add_argument('b', type=int, help='b') | |
parser.add_argument('--verbose', '-v', action='count', help='verbose') | |
parser.add_argument('--option', '-o', action='store_true', help='verbose') | |
# when running with -b/--bootstrap, we don't need the regular arguments | |
parser.add_argument('--bootstrap', '-b', action='store_true', help='bootstrap this script') | |
args = parser.parse_args() | |
if parser.has_errors and not args.bootstrap: | |
parser.handle_error() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment