Advertisement
Guest User

Untitled

a guest
Jun 16th, 2019
50
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.42 KB | None | 0 0
  1. import argparse
  2.  
  3.  
  4. def argparser_from_spec(spec, **argparser_kwargs):
  5. ap = argparse.ArgumentParser(**argparser_kwargs)
  6.  
  7. for line in spec.splitlines():
  8. line = line.strip()
  9. if not line:
  10. continue
  11.  
  12. kwargs = {}
  13. optdefs, _sep, help = line.partition(":")
  14.  
  15. help = help.strip()
  16. if help:
  17. kwargs["help"] = help
  18.  
  19. items = optdefs.split()
  20. if len(items) == 1 and not items[0].startswith("-"):
  21. ap.add_argument(items[0], **kwargs)
  22. continue
  23.  
  24. argnames = []
  25. metavars = []
  26. for i, optdef in enumerate(optdefs.split()):
  27. if optdef.startswith("-"):
  28. argnames.append(optdef)
  29. else:
  30. metavars.append(optdef)
  31.  
  32. if len(metavars) == 0:
  33. kwargs["action"] = "store_true"
  34. elif len(metavars) == 1:
  35. kwargs["metavar"] = metavars[0]
  36. else:
  37. kwargs["metavar"] = tuple(metavars)
  38. kwargs["nargs"] = len(metavars)
  39.  
  40. ap.add_argument(*argnames, **kwargs)
  41.  
  42. return ap
  43.  
  44.  
  45. spec = """
  46. positional: this is a positional argument
  47. -f --flag: this is a boolean flag argument
  48. -c --count N: this is an optional argument
  49. -s --size X Y: this is an optional argument with multiple parameters
  50. """
  51. argparser = argparser_from_spec(spec, allow_abbrev=False)
  52. print(argparser.parse_args("spam -f --count 42 -s 4 2".split()))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement