cli.py 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. # -*- coding: utf-8 -*-
  2. import getpass
  3. from ._compat import string_types, ascii_lowercase, input
  4. def prompt(name, default=None):
  5. """
  6. Grab user input from command line.
  7. :param name: prompt text
  8. :param default: default value if no input provided.
  9. """
  10. prompt = name + (default and ' [%s]' % default or '')
  11. prompt += name.endswith('?') and ' ' or ': '
  12. while True:
  13. rv = input(prompt)
  14. if rv:
  15. return rv
  16. if default is not None:
  17. return default
  18. def prompt_pass(name, default=None):
  19. """
  20. Grabs hidden (password) input from command line.
  21. :param name: prompt text
  22. :param default: default value if no input provided.
  23. """
  24. prompt = name + (default and ' [%s]' % default or '')
  25. prompt += name.endswith('?') and ' ' or ': '
  26. while True:
  27. rv = getpass.getpass(prompt)
  28. if rv:
  29. return rv
  30. if default is not None:
  31. return default
  32. def prompt_bool(name, default=False, yes_choices=None, no_choices=None):
  33. """
  34. Grabs user input from command line and converts to boolean
  35. value.
  36. :param name: prompt text
  37. :param default: default value if no input provided.
  38. :param yes_choices: default 'y', 'yes', '1', 'on', 'true', 't'
  39. :param no_choices: default 'n', 'no', '0', 'off', 'false', 'f'
  40. """
  41. yes_choices = yes_choices or ('y', 'yes', '1', 'on', 'true', 't')
  42. no_choices = no_choices or ('n', 'no', '0', 'off', 'false', 'f')
  43. while True:
  44. rv = prompt(name, default and yes_choices[0] or no_choices[0])
  45. if not rv:
  46. return default
  47. if rv.lower() in yes_choices:
  48. return True
  49. elif rv.lower() in no_choices:
  50. return False
  51. def prompt_choices(name, choices, default=None, resolve=ascii_lowercase,
  52. no_choice=('none',)):
  53. """
  54. Grabs user input from command line from set of provided choices.
  55. :param name: prompt text
  56. :param choices: list or tuple of available choices. Choices may be
  57. single strings or (key, value) tuples.
  58. :param default: default value if no input provided.
  59. :param no_choice: acceptable list of strings for "null choice"
  60. """
  61. _choices = []
  62. options = []
  63. for choice in choices:
  64. if isinstance(choice, string_types):
  65. options.append(choice)
  66. else:
  67. options.append("%s [%s]" % (choice[1], choice[0]))
  68. choice = choice[0]
  69. _choices.append(choice)
  70. while True:
  71. rv = prompt(name + ' - (%s)' % ', '.join(options), default)
  72. if not rv:
  73. return default
  74. rv = resolve(rv)
  75. if rv in no_choice:
  76. return None
  77. if rv in _choices:
  78. return rv