From 4c685c0088ffa8589946e565f5289f3baa2d1f82 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sven=20M=C3=A4der?= <maeder@phys.ethz.ch> Date: Tue, 30 Mar 2021 14:44:17 +0200 Subject: [PATCH] Allow extendable simple argparser --- lib/isg/argparser.py | 38 ++++++++++++++++++++++++++++++-------- 1 file changed, 30 insertions(+), 8 deletions(-) diff --git a/lib/isg/argparser.py b/lib/isg/argparser.py index 0eef125..fdc18d0 100644 --- a/lib/isg/argparser.py +++ b/lib/isg/argparser.py @@ -2,9 +2,10 @@ import argparse -def simple(description, arg=None, arg_help='', opts=dict(), noopts=dict()): + +def extendable(description, arg=None, arg_help='', opts=dict(), noopts=dict()): """ - Get cmd argument with simplified argparser + Get extendable simplified argparser """ parser = argparse.ArgumentParser( add_help=False, description=description) @@ -15,18 +16,39 @@ def simple(description, arg=None, arg_help='', opts=dict(), noopts=dict()): for k, v in opts.items(): if isinstance(v, list): v = ', '.join(v) - parser.add_argument('-' + k[:1], '--' + k, dest=k, - action='store_const', const=True, - help='Show ' + v) + + try: + parser.add_argument('-' + k[:1], '--' + k, dest=k, + action='store_const', const=True, + help='Show ' + v) + except argparse.ArgumentError: + parser.add_argument('--' + k, dest=k, + action='store_const', const=True, + help='Show ' + v) for k, v in noopts.items(): if isinstance(v, list): v = ', '.join(v) - parser.add_argument('-' + k[3:4].upper(), '--' + k, dest=k, - action='store_const', const=True, - help='Hide ' + v) + + try: + parser.add_argument('-' + k[3:4].upper(), '--' + k, dest=k, + action='store_const', const=True, + help='Hide ' + v) + except argparse.ArgumentError: + parser.add_argument('--' + k, dest=k, + action='store_const', const=True, + help='Hide ' + v) parser.add_argument('--help', action='help', help='Show this help message and exit') + return parser + + +def simple(description, arg=None, arg_help='', opts=dict(), noopts=dict()): + """ + Get cmd argument with simplified argparser + """ + parser = extendable(description, arg=arg, arg_help=arg_help, opts=opts, noopts=noopts) + return vars(parser.parse_args()) -- GitLab