multicmd 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. # -*- coding: utf-8 -*-
  2. # name: multicmd
  3. # key: multicmd
  4. # --
  5. #!/usr/bin/env python
  6. import argparse
  7. import logging
  8. import sys
  9. parser = argparse.ArgumentParser(usage="%(prog)s [options] args...")
  10. parser.add_argument("-v", action="append_const", const=1, dest="verbosity", default=[],
  11. help="Be more verbose. Can be specified multiple times to increase verbosity further")
  12. subparsers = parser.add_subparsers(help="Action to be taken")
  13. def _action(name):
  14. def decorator(func):
  15. parser = subparsers.add_parser(name)
  16. parser.set_defaults(action=func)
  17. return parser
  18. return decorator
  19. @_action("${1:command}")
  20. def cmd_$1(args):
  21. $0
  22. return 0
  23. ################################## Boilerplate ################################
  24. def _configure_logging(args):
  25. verbosity_level = len(args.verbosity)
  26. if verbosity_level == 0:
  27. level = "WARNING"
  28. elif verbosity_level == 1:
  29. level = "INFO"
  30. else:
  31. level = "DEBUG"
  32. logging.basicConfig(
  33. stream=sys.stderr,
  34. level=level,
  35. format="%(asctime)s -- %(message)s"
  36. )
  37. #### For use with entry_points/console_scripts
  38. def main_entry_point():
  39. args = parser.parse_args()
  40. _configure_logging(args)
  41. sys.exit(args.action(args))
  42. if __name__ == "__main__":
  43. main_entry_point()