You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

79 lines
2.7 KiB

  1. '''
  2. Created on Jan 15 2019
  3. @author: Jonathan Schultz
  4. This file contains code that allows the default argument values to be specified
  5. on the command line.
  6. '''
  7. from argparse import _SubParsersAction
  8. def parse_cmd_args(self, args=None):
  9. def prepare_to_read_cmd_args(item):
  10. '''
  11. Before reading the command-line arguments, we need to fudge a few things:
  12. 1. If there are subparsers, we need a dest in order to know in which
  13. subparser the command-line values should be stored.
  14. 2. Any required argument or mutex group needs to be made not required,
  15. otherwise it will be compulsory to enter those values on the command
  16. line.
  17. We save the everything as it was before the fudge, so we can restore later.
  18. '''
  19. for action in item._actions:
  20. if isinstance(action, _SubParsersAction):
  21. action.save_dest = action.dest
  22. if not action.dest:
  23. action.dest = '_subparser'
  24. else:
  25. action.save_required = action.required
  26. action.required = False
  27. action.save_nargs = action.nargs
  28. if action.nargs == '+':
  29. action.nargs = '*'
  30. elif action.nargs is None:
  31. action.nargs = '?'
  32. for mutex_group in item._mutually_exclusive_groups:
  33. mutex_group.save_required = mutex_group.required
  34. mutex_group.required = False
  35. def overwrite_default_values(item, cmd_args):
  36. '''
  37. Subsistute arguments provided on the command line in the place of the
  38. default values provided to argparse.
  39. '''
  40. for action in item._actions:
  41. if isinstance(action, _SubParsersAction):
  42. subparser_arg = getattr(cmd_args, action.dest, None)
  43. if subparser_arg:
  44. overwrite_default_values(action.choices[subparser_arg], cmd_args)
  45. else:
  46. dest = getattr(action, 'dest', None)
  47. if dest:
  48. cmd_arg = getattr(cmd_args, dest, None)
  49. if cmd_arg:
  50. action.default = cmd_arg
  51. def restore_original_configuration(item):
  52. '''
  53. Restore the old values as they were to start with.
  54. '''
  55. for action in item._actions:
  56. if isinstance(action, _SubParsersAction):
  57. action.dest = action.save_dest
  58. del action.save_dest
  59. else:
  60. action.required = action.save_required
  61. del action.save_required
  62. action.nargs = action.save_nargs
  63. del action.save_nargs
  64. for mutex_group in item._mutually_exclusive_groups:
  65. mutex_group.required = mutex_group.save_required
  66. del mutex_group.save_required
  67. prepare_to_read_cmd_args(self)
  68. overwrite_default_values(self, self.original_parse_args(args))
  69. restore_original_configuration(self)