fork download
  1. import argparse
  2.  
  3.  
  4. def command_d(value):
  5. print("d", value)
  6.  
  7. def command_a(value_a, value_b):
  8. print("a", value_a, value_b)
  9.  
  10. def command_r(value_a, value_b):
  11. print("r", value_a, value_b)
  12.  
  13.  
  14. def make_custom_action(command):
  15. class CustomAction(argparse.Action):
  16. def __call__(self, parser, namespace, values, option_string=None):
  17. return command(*values)
  18. return CustomAction
  19.  
  20.  
  21.  
  22. def init_parser():
  23. """Initiate argparse and return an `argparse.ArgumentParser`
  24. Returns: An `ArgumentParser`
  25. """
  26. parser = argparse.ArgumentParser()
  27.  
  28. parser.add_argument(
  29. '--remove-duplicates', '-d',
  30. nargs=1,
  31. action=make_custom_action(command_d)
  32. )
  33.  
  34. parser.add_argument(
  35. '--use-absolute-paths', '-A',
  36. nargs=2,
  37. action=make_custom_action(command_a)
  38. )
  39.  
  40. parser.add_argument(
  41. '--use-relative-paths', '-R',
  42. nargs=2,
  43. action=make_custom_action(command_r)
  44. )
  45.  
  46. return parser
  47.  
  48. init_parser().parse_args(['-A', 'foo', 'bar'])
  49. init_parser().parse_args(['-R', 'foo', 'bar'])
  50. init_parser().parse_args(['-d', 'baz'])
  51.  
Success #stdin #stdout 0.03s 28896KB
stdin
Standard input is empty
stdout
a foo bar
r foo bar
d baz