This is the main documentation for Qprompt, a Python library for quickly creating user input prompts and various related functionality.
For more information:
Readme - https://github.com/jeffrimko/Qprompt/blob/master/README.adoc - Main readme file.
GitHub - https://github.com/jeffrimko/Qprompt - Main version control repository.
PyPI - https://pypi.python.org/pypi/qprompt - Package index page.
Introduction¶
This project provides a Python 2.7/3.5+ 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.
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.5+ 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 feature uses the excellent iterfzf library by dahlia. Example of the menu fzf search feature:
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:
examples/ask_1.py - Basic info prompting.
examples/menu_1.py - Basic menu usage.
examples/display_1.py - Basic display functions.
examples/status_1.py - Basic status function usage.
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)¶
- 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(msg='Enter input', fmt=None, dft=None, vld=None, shw=True, blk=False, hlp=None, qstr=True, multi=False, **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; blank input will be accepted even if the vld parameter is supplied. Note that supplying a default value will disable accepting blank input.
These functions accept only specific data types:
- qprompt.ask_yesno(msg='Proceed?', dft=None, **kwargs)¶
Prompts the user for a yes or no answer. Returns True for yes, False for no.
- qprompt.ask_int(msg='Enter an integer', dft=None, vld=None, hlp=None, **kwargs)¶
Prompts the user for an integer.
- qprompt.ask_float(msg='Enter a float', dft=None, vld=None, hlp=None, **kwargs)¶
Prompts the user for a float.
- qprompt.ask_str(msg='Enter a string', dft=None, vld=None, shw=True, blk=True, hlp=None, **kwargs)¶
Prompts the user for a string.
- qprompt.ask_pass(*, msg='Enter password', dft=None, vld=None, shw=False, blk=True, hlp=None, **kwargs)¶
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=<class '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(item, args=None, krgs=None, **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.
The following convenience context manager is provided:
- qprompt.Wrap(width=None, char='', **kwargs)¶
Context manager that wraps content between horizontal lines.
Examples:
with qprompt.Wrap(): qprompt.echo("Hello world!")
Automation¶
The following helpers are provided for automation:
- qprompt.StdinSetup(stream=None)¶
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(auto=None)¶
Automatically set stdin using supplied list; a default context manager is provided by stdin_auto.