Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import argparse
- def argparser_from_spec(spec, **argparser_kwargs):
- ap = argparse.ArgumentParser(**argparser_kwargs)
- for line in spec.splitlines():
- line = line.strip()
- if not line:
- continue
- kwargs = {}
- optdefs, _sep, help = line.partition(":")
- help = help.strip()
- if help:
- kwargs["help"] = help
- items = optdefs.split()
- if len(items) == 1 and not items[0].startswith("-"):
- ap.add_argument(items[0], **kwargs)
- continue
- argnames = []
- metavars = []
- for i, optdef in enumerate(optdefs.split()):
- if optdef.startswith("-"):
- argnames.append(optdef)
- else:
- metavars.append(optdef)
- if len(metavars) == 0:
- kwargs["action"] = "store_true"
- elif len(metavars) == 1:
- kwargs["metavar"] = metavars[0]
- else:
- kwargs["metavar"] = tuple(metavars)
- kwargs["nargs"] = len(metavars)
- ap.add_argument(*argnames, **kwargs)
- return ap
- spec = """
- positional: this is a positional argument
- -f --flag: this is a boolean flag argument
- -c --count N: this is an optional argument
- -s --size X Y: this is an optional argument with multiple parameters
- """
- argparser = argparser_from_spec(spec, allow_abbrev=False)
- print(argparser.parse_args("spam -f --count 42 -s 4 2".split()))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement