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.

55 lines
1.6 KiB

4 years ago
  1. # coding: utf-8
  2. #
  3. # Copyright © 2010—2014 Andrey Mikhaylenko and contributors
  4. #
  5. # This file is part of Argh.
  6. #
  7. # Argh is free software under terms of the GNU Lesser
  8. # General Public License version 3 (LGPLv3) as published by the Free
  9. # Software Foundation. See the file README.rst for copying conditions.
  10. #
  11. """
  12. Utilities
  13. ~~~~~~~~~
  14. """
  15. import argparse
  16. import inspect
  17. from argh import compat
  18. def get_subparsers(parser, create=False):
  19. """
  20. Returns the :class:`argparse._SubParsersAction` instance for given
  21. :class:`ArgumentParser` instance as would have been returned by
  22. :meth:`ArgumentParser.add_subparsers`. The problem with the latter is that
  23. it only works once and raises an exception on the second attempt, and the
  24. public API seems to lack a method to get *existing* subparsers.
  25. :param create:
  26. If `True`, creates the subparser if it does not exist. Default if
  27. `False`.
  28. """
  29. # note that ArgumentParser._subparsers is *not* what is returned by
  30. # ArgumentParser.add_subparsers().
  31. if parser._subparsers:
  32. actions = [a for a in parser._actions
  33. if isinstance(a, argparse._SubParsersAction)]
  34. assert len(actions) == 1
  35. return actions[0]
  36. else:
  37. if create:
  38. return parser.add_subparsers()
  39. def get_arg_spec(function):
  40. """
  41. Returns argument specification for given function. Omits special
  42. arguments of instance methods (`self`) and static methods (usually `cls`
  43. or something like this).
  44. """
  45. spec = compat.getargspec(function)
  46. if inspect.ismethod(function):
  47. spec = spec._replace(args=spec.args[1:])
  48. return spec