10.9.3. Prompting Utilities

PyTan prompting module.

class pytan3.utils.prompts.ColorWrap(mode='')[source]

Bases: object

Wrapper for colorama.

MODE_MAP = {'BACK': <colorama.ansi.AnsiBack object at 0x7ff2fe424630>, 'FORE': <colorama.ansi.AnsiFore object at 0x7ff2fe4245c0>, 'STYLE': <colorama.ansi.AnsiStyle object at 0x7ff2fe424668>}

dict – Map of modes this wrapper can expose.

__init__(mode='')[source]

Constructor.

Parameters:mode (str, optional) –

One of keys in MODE_MAP.

Defaults to: “”.

MODE = ''

str – Mode to wrap around colorama.

__getattr__(attr)[source]

Get an attribute from colorama.

Parameters:attr (str) –

If MODE is in MODE_MAP, get uppercased attr from MODE.

Returns an empty string if MODE is not in MODE_MAP or attr is not available in MODE_CLS from MODE_MAP[MODE].

Returns:str
class pytan3.utils.prompts.Promptness(input_stream=<_io.TextIOWrapper name='<stdin>' mode='r' encoding='UTF-8'>, output_stream=<colorama.ansitowin32.StreamWrapper object>, lvl='info')[source]

Bases: object

Prompt utility class.

YES_VALUES = ['y.*', 'true', '1']

list of str – Valid regex values for truthy-ness.

NO_VALUES = ['n.*', 'false', '0']

list of str – Valid regex values for falsey-ness.

USE_COLOR = True

bool – Use color in prepare().

OVERRIDES = None

dict – Default overrides for Promptness.ask_dict().

TMPLS = {'env_value': '\n{{f.green}}OS Environment Variable {env!r} has value {env_value}, {{f.green}}{action} override default {default}{{s.reset}}.', 'option': '\n {{f.BLUE}}{opt}{{s.reset}}', 'options': '\nOptions:{options}\n', 'prompt': '\n{{f.cyan}}{text}{{s.reset}} [default: {default}]: ', 'secure_value': '{{s.reset}}{{f.red}}..HIDDEN..{{s.reset}}', 'value': "{{s.reset}}{{f.green}}'{value}'{{s.reset}}", 'warn_bool_invalid': '\n-- {{f.red}}Value must be one of {yes_values!r} or {no_values!r}{{s.reset}}', 'warn_int_invalid': '\n-- {{f.red}}Value must be a valid number{{s.reset}}', 'warn_nodefault': '\n-- {{f.red}}No default defined, value required!{{s.reset}}', 'warn_notty': '\n\n{{f.red}}No TTY on stream {stream}, using default {default!r} for {text!r}{{s.reset}}\n', 'warn_option_invalid': '\n-- {{f.red}}Value must be one of: {options!r}{{s.reset}}\n', 'warn_text_invalid': '\n-- {{f.red}}Value did not match {validate!r}{{s.reset}}'}

dict – String templates used throughout.

__init__(input_stream=<_io.TextIOWrapper name='<stdin>' mode='r' encoding='UTF-8'>, output_stream=<colorama.ansitowin32.StreamWrapper object>, lvl='info')[source]

Constructor.

Parameters:
  • input_stream (io.IOBase, optional) –

    Stream to get input from.

    Defaults to: sys.stdin.

  • output_stream (io.IOBase, optional) –

    Stream to send output to.

    Defaults to: sys.stderr.

  • lvl (str, optional) –

    Logging level for this object.

    Defaults to: “info”.

input_stream = None

io.IOBase – Stream to get input from.

output_stream = None

io.IOBase – Stream to send output to.

log = None

logging.Logger – Log for this object.

__str__()[source]

Show object info.

Returns:str
__repr__()[source]

Show object info.

Returns:str
spew(text, **kwargs)[source]

Print output to stream.

Parameters:
prepare(text, **kwargs)[source]

Format text with colors.

Parameters:
  • text (str) – String to format.
  • **kwargs
    use_color (bool):
    True: Replace fore, back, and style with color codes.

    False: Replace fore, back, and style with empty vals.

    Defaults to: USE_COLOR.

get_prompter(secure=False)[source]

Get a prompt function.

Parameters:secure (bool, optional) –

Return getpass.getpass instead of input.

Defaults to: False.

Returns:object
prompt(text, default=None, **kwargs)[source]

Prompt for a value.

Parameters:
  • text (str) – Prompt text from parent for error/warning messages.
  • default (object, optional) –

    Default value to use if no value supplied.

    Defaults to: None.

  • **kwargs
    secure (bool, optional):
    If value should have its input hidden or not.

    Defaults to: False.

    check_tty (bool):
    Skip TTY checks for input/output stream.

    Defaults to: False.

    env_var (str):
    Replace default with contents of this OS Env.

    Defaults to: “”.

    rest of kwargs:
    Passed to spew() and prepare().
Raises:

NoTtyError – If the input or output stream is not attached to a console and check_tty is False.

Returns:

str

ask_choice(text, choices, default=None, attempts=5, **kwargs)[source]

Prompt user to select from a list of choices.

Parameters:
  • text (str) – Text to use when prompting.
  • choices (list of str) – List of choices for user to pick from.
  • default (str, optional) –

    Default value to use if no value supplied.

    Defaults to: None.

  • attempts (int, optional) –

    Number of attempts to allow empty/invalid input.

    Defaults to: 5.

  • **kwargs – Passed to :meth`prepare` and spew().
Raises:
Returns:

str

ask_bool(text, default=None, attempts=5, **kwargs)[source]

Prompt user to provide yes or no.

Parameters:
  • text (str) – Text to use when prompting.
  • default (bool or str, optional) –

    Default value to use if no value supplied.

    Defaults to: None.

  • attempts (int, optional) –

    Number of attempts to allow empty/invalid input.

    Defaults to: 5.

  • **kwargs
    rest of kwargs:
    Passed to prepare() and spew().
Raises:
Returns:

bool

ask_int(text, default=None, attempts=5, **kwargs)[source]

Prompt user to provide yes or no.

Parameters:
  • text (str) – Text to use when prompting.
  • default (int, optional) –

    Default value to use if no value supplied.

    Defaults to: None.

  • attempts (int, optional) –

    Number of attempts to allow empty/invalid input.

    Defaults to: 5.

  • **kwargs
    rest of kwargs:
    Passed to prompt() and prepare().
Raises:
Returns:

int

ask_str(text, default=None, attempts=5, **kwargs)[source]

Prompt user to provide yes or no.

Parameters:
  • text (str) – Text to use when prompting.
  • default (str, optional) –

    Default value to use if no value supplied.

    Defaults to: “”.

  • attempts (int, optional) –

    Number of attempts to allow empty/invalid input.

    Defaults to: 5.

  • **kwargs
    empty_ok (bool, optional):
    Empty input is allowed.

    Defaults to: False.

    validate (str, optional):
    Regex string to validate value.

    Defaults to: “”.

    rest of kwargs:
    Passed to prompt() and prepare().
Raises:

EmptyValueError – If no value supplied and no default and not empty_ok.

Returns:

str

ask_dict(asks, overrides=None)[source]

Prompt for input from a list of dict.

Parameters:
  • asks (list of dict) – List of dicts with valid kwargs for the various ask methods.
  • overrides

    (dict, optional): Dictionary of key / value pairs to over ride the defaults of asks.

    Defaults to: None.

Notes

Keys for ask dict in asks:

“method”, required:
Ask method to use for this ask dict.
“key”, required:
Key to store value returned from ask method in return dict.
“text”, required:
String to use for prompting.
“choices”, required for ask_choice():
List of valid choices for user to pick.
“secure”, optional for ask_str():
Use prompt that hides user input while typing.
“default”, optional:
Default value to use if user does not provide one.
“attempts”, optional:
Number of attempts to allow empty/invalid input.
“check_tty”, optional:
Skip TTY checks for input/output stream.
Returns:dict
exception pytan3.utils.prompts.PromptError(text, attempts)[source]

Bases: Exception

Parent exception for any errors when prompting.

Thrown by:
Promptness.ask_dict()
msg = '{text}'
__init__(text, attempts)[source]

Constructor.

Parameters:
  • text (str) – Text to insert into exception message
  • attempts (int, optional) – Number of attempts tried before this exception
exception pytan3.utils.prompts.InvalidValueError(text, attempts)[source]

Bases: pytan3.utils.prompts.PromptError

Thrown when a user provides an invalid value.

Thrown by:
Promptness.ask_choice() Promptness.ask_bool() Promptness.ask_int()
msg = 'Invalid value supplied for prompt {text!r} after {attempts} attempts'
exception pytan3.utils.prompts.EmptyValueError(text, attempts)[source]

Bases: pytan3.utils.prompts.PromptError

Thrown when no default defined and user provides no value.

Thrown by:
Promptness.ask_choice() Promptness.ask_bool() Promptness.ask_int() Promptness.ask_str()
msg = 'No value supplied for prompt {text!r} after {attempts} attempts'
exception pytan3.utils.prompts.NoTtyError(stream, text)[source]

Bases: pytan3.utils.prompts.PromptError

Thrown when a TTY is not attached to a console.

Thrown by:
Promptness.prompt()
__init__(stream, text)[source]

Constructor.

Parameters:
  • stream (io.IOBase) – Stream that was not attached to a console.
  • text (str) – Text to insert into exception message
pytan3.utils.prompts.stream_name(stream)[source]

Get the name of a stream.

Parameters:stream (io.IOBase) – Stream to get name of.
Returns:str
pytan3.utils.prompts.isatty(stream)[source]

Check if a stream is attached to a console.

Parameters:stream (io.IOBase) – Stream to check.
Returns:bool
pytan3.utils.prompts.promptness = pytan3.utils.prompts.Promptness(input='<stdin>', output='<stderr>')

Promptness – Pre-established object for easy usage.