https://raw.githubusercontent.com/jeffrimko/Qprompt/master/doc/logo/qprompt.png
http://img.shields.io/:license-mit-blue.svghttps://travis-ci.org/jeffrimko/Qprompt.svg?branch=master

This is the main documentation for Qprompt, a Python library for quickly creating user input prompts and various related functionality.

For more information:

Introduction

This project provides a Python 2.7/3.3+ library that allows the user to quickly create CLI prompts for user input. The main features of Qprompt are:

  • Simple multi-entry menus.
  • Prompt for typed (integer/float/string) input.
  • Optional default values and validity checks.
  • Various CLI convenience functions.
  • User input can optionally be supplied from script command-line arguments allowing for simple automation.
  • Should work on any platform without additional dependencies.

Demo

Status

Currently, this project is in the development release stage. While this project is suitable for use, please note that there may be incompatibilities in new releases.

Release notes are maintained in the project changelog.

Requirements

Qprompt should run on any Python 2.7/3.3+ interpreter and uses some third-party libraries.

Installation

Qprompt is available on PyPI here and can be installed with pip using the following command: pip install qprompt

Additionally, Qprompt can be installed from source by running: python setup.py install

Usage

Start by importing Qprompt into your Python script:

import qprompt

You can prompt the user for various input types:

qprompt.ask_yesno()
qprompt.ask_int()
qprompt.ask_float()
qprompt.ask_str()

All prompts requiring user input will start with [?]:

qprompt.ask_int()
# [?] Enter an integer:

At any prompt, the user can enter the ? character to show valid entries:

qprompt.ask_yesno()
# [?] Proceed?: ?
# ['N', 'NO', 'Y', 'YES', 'n', 'no', 'y', 'yes']

The default prompt message can be changed:

qprompt.ask_str("Enter your name")
# [?] Enter your name:

An optional default value can be supplied:

qprompt.ask_yesno(default="y")
# [?] Proceed? [y]:

Optional validity checks can be added:

qprompt.ask_int(valid=[1,2,3])
# [?] Enter an integer: 4
# [?] Enter an integer: 1

qprompt.ask_str(valid=lambda x: x.startswith("spa"))
# [?] Enter a string: foo
# [?] Enter a string: spam

qprompt.ask_str("Enter a path", valid=lambda x: os.path.exists(x))
# [?] Enter a path: C:\Windows

Robot problem? Try using a captcha:

qprompt.ask_captcha()
# [?] Enter the following letters, "kslg":

qprompt.ask_captcha(length=6)
# [?] Enter the following letters, "dkixzp":

Menus are easy to make:

menu = qprompt.Menu()
menu.add("p", "Previous")
menu.add("n", "Next")
menu.add("q", "Quit")
choice = menu.show()
# -- MENU --
#   (p) Previous
#   (n) Next
#   (q) Quit
# [?] Enter menu selection:

The menu entry name (first parameter of add()) is returned by default but can be changed:

print(menu.show())
# [?] Enter menu selection: p
# p

print(menu.show(returns="desc"))
# [?] Enter menu selection: p
# Previous

Your menus can do cool stuff by registering functions:

def foo(a, b):
    print(a + b)
menu.add("f", "foo", foo, [1, 2])

If you just need a quick menu to call functions:

Menu(func1, func2, func3).show()

Additionally, menus can be searched with fzf by entering / at the prompt. This features uses the excellent iterfzf library by dahlia. Example of the menu fzf search feature:

_images/menu_fzf_demo.gif

Some print-like functions:

qprompt.echo("foo")
# foo

qprompt.alert("bar")
# [!] bar

qprompt.warn("baz")
# [WARNING] baz

qprompt.error("qux")
# [ERROR] qux

qprompt.fatal("ugh")
# [FATAL] ugh

Got a function that takes a while? Show that it is running with status which can be used as a function or decorator:

qprompt.status("Doing stuff...", time.sleep, [1])
# [!] Doing stuff... DONE.

@qprompt.status("Doing more stuff...")
def do_stuff():
    time.sleep(1)
do_stuff()
# [!] Doing more stuff... DONE.

Additional convenience functions:

qprompt.pause()
# Press ENTER to continue...

qprompt.hrule(width=10)
# ----------

qprompt.wrap("hello world", "hi", width=10)
# /-- hi ---
# hello world
# \---------

Check out the following additional examples of Qprompt; more can be found here:

Compatibility Note

Note that for backwards compatibility purposes, the following kwargs are equivalent:

  • blk = blank
  • dft = default
  • hdr = header
  • hlp = help
  • msg = message
  • shw = show
  • vld = valid

For example, the following calls are equivalent:

qprompt.ask_yesno(dft="y")
qprompt.ask_yesno(default="y")

Input Automation

User input can be automated using command-line arguments to the script.

Use the StdinAuto() context manager to automatically pass a list of strings to input functions:

with qprompt.StdinAuto(["foo","bar","42"]):
    print(ask_str())
    print(ask_str())
    print(ask_int())
# foo
# bar
# 42

The stdin_auto context manager will automatically pass script command-line arguments to input functions:

with qprompt.stdin_auto:
    print(ask_str())
    print(ask_str())
    print(ask_int())
# $ python example.py foo bar 42
# foo
# bar
# 42

Menus can be automated using the main() method:

menu = qprompt.Menu
menu.add("f", "Foo", some_useful_function)
menu.add("b", "Bar", another_useful_function)
menu.main()
# $ python example.py f
# some_useful_function() ran just now!

Menus can optionally loop allowing for multiple tasks to be run:

menu = qprompt.Menu
menu.add("f", "Foo", some_useful_function)
menu.add("b", "Bar", another_useful_function)
menu.main(loop=True)
# $ python example.py f b q
# some_useful_function() ran just now!
# another_useful_function() ran just now!

If no arguments are passed to the script, the input prompts will act as normal.

API Documentation

Console Output

These functions write to the console. They are essentially slight variations of the Python3 print() function and each adds a prefix to the displayed message.

qprompt.echo(text='', end='\n', flush=True)

Generic echo/print function; based off code from blessed package. Returns the printed string.

qprompt.alert(msg, **kwargs)

Prints alert message to console. Returns printed string.

qprompt.info(msg, **kwargs)

Prints info message to console. Returns printed string.

qprompt.warn(msg, **kwargs)

Prints warning message to console. Returns printed string.

qprompt.error(msg, **kwargs)

Prints error message to console. Returns printed string.

User Input

These functions prompt the user for input.

This is the generic user input function:

qprompt.ask(*args, **kwargs)

Prompts the user for input and returns the given answer. Optionally checks if answer is valid.

Params:
  • msg (str) - Message to prompt the user with.
  • fmt (func) - Function used to format user input.
  • dft (int|float|str) - Default value if input is left blank.
  • vld ([int|float|str|func]) - Valid input entries.
  • shw (bool) - If true, show the user’s input as typed.
  • blk (bool) - If true, accept a blank string as valid input. Note that supplying a default value will disable accepting blank input.

These functions accept only specific data types:

qprompt.ask_yesno(*args, **kwargs)

Prompts the user for a yes or no answer. Returns True for yes, False for no.

qprompt.ask_int(*args, **kwargs)

Prompts the user for an integer.

qprompt.ask_float(*args, **kwargs)

Prompts the user for a float.

qprompt.ask_str(*args, **kwargs)

Prompts the user for a string.

qprompt.ask_pass()

Alias for ask_str(shw=False).

Additional input functions:

qprompt.ask_captcha(length=4)

Prompts the user for a random string.

Helpers

The following are miscellaneous convenience functions:

qprompt.cast(val, typ=<type 'int'>)

Attempts to cast the given value to the given type otherwise None is returned.

qprompt.clear()

Clears the console.

qprompt.hrule(width=None, char=None)

Outputs or returns a horizontal line of the given character and width. Returns printed string.

qprompt.pause()

Pauses and waits for user interaction.

qprompt.title(msg)

Sets the title of the console window.

qprompt.status(*args, **kwargs)

Prints a status message at the start and finish of an associated function. Can be used as a function decorator or as a function that accepts another function as the first parameter.

Params:

The following parameters are available when used as a decorator:

  • msg (str) [args] - Message to print at start of func.

The following parameters are available when used as a function:

  • msg (str) [args] - Message to print at start of func.
  • func (func) - Function to call. First args if using status() as a function. Automatically provided if using status() as a decorator.
  • fargs (list) - List of args passed to func.
  • fkrgs (dict) - Dictionary of kwargs passed to func.
  • fin (str) [kwargs] - Message to print when func finishes.

Examples:

@qprompt.status("Something is happening...")
def do_something(a):
    time.sleep(a)

do_something()
# [!] Something is happening... DONE.

qprompt.status("Doing a thing...", myfunc, [arg1], {krgk: krgv})
# [!] Doing a thing... DONE.
qprompt.wrap(*args, **kwargs)

Wraps the given item content between horizontal lines. Item can be a string or a function.

Examples:

qprompt.wrap("Hi, this will be wrapped.")  # String item.
qprompt.wrap(myfunc, [arg1, arg2], {'krgk': krgv})  # Func item.

Automation

The following helpers are provided for automation:

qprompt.StdinSetup()

Sets up stdin to be supplied via setinput(); a default context manager is provided by stdin_setup.

qprompt.setinput(x)

Allows stdin to be set via function; use with stdin_setup context.

qprompt.StdinAuto()

Automatically set stdin using supplied list; a default context manager is provided by stdin_auto.