Pycopia CLI toolkit

A toolkit for quickly creating interactive command interfaces. The interface is similar to a shell (command, options, and arguments), but supports “contexts”, built-in help, and colorized prompts.

You can use this to wrap other Python objects to interact with them.

Provides a standard command line interpreter for programs needing one. Supports different command contexts, customizable user interface, generic object CLI’s, and other neat stuff.

exception pycopia.CLI.CLIException(value=None)[source]
exception pycopia.CLI.CommandQuit(value=None)[source]

An exception that is used to signal quiting from a command object.

exception pycopia.CLI.CommandExit(value=None)[source]

An exception that is used to signal exiting from the command object. The command is not popped.

exception pycopia.CLI.NewCommand(value=None)[source]

Used to signal the parser to push a new command object. Raise this with an instance of BaseCommands as a value.

class pycopia.CLI.BaseCommands(ui, aliases=None)[source]

A base class that defines a holder object for command methods. It dispatches the methods when you call it with an argv-style list of arguments. The first argument must match a name of a method.

add_completion_scope(name, complist)[source]
alias(argv)[source]

alias [newalias] With no argument prints the current set of aliases. With an argument of the form alias ..., sets a new alias.

clone(cliclass=None, theme=None)[source]
commandlist(argv)[source]
cycle(argv)[source]

cycle <range> <command> [<arg>...] Cycle the variable symbol % through the range, and re-evaluate the command for each value. Range is of the form [start’:’]end[‘:’ step] Where start defaults to zero and step defaults to one. Or, range may be a list of values separated by ‘,’.

Example:
> cycle 5 printf “This is {}” %
date(argv)[source]

date [FORMAT] Display the current time and date. Optionally supply a format string.

debug(argv)[source]

debug [“on”|”off”] Enables debugging for CLI code. Enters the debugger if an exception occurs.

default_command(argv)[source]
delay(argv)

sleep <secs> Sleeps for <secs> seconds.

echo(argv)[source]

echo ... Echoes arguments back.

except_hook(ex, val, tb)[source]
exit(argv)[source]

Exits this command interpreter instance.

export(argv)[source]

export NAME=VAL Sets environment variable that new processes will inherit.

finalize()[source]
get_commands()[source]
get_completion_scope(name='commands')[source]
getopt(argv, shortopts)[source]
handle_subcommand(value)[source]
help(argv)[source]

help [-lLcia] [<commandname>]... Print a list of available commands, or information about a command, if the name is given. Options:

-l Shows only local (object specific) commands.
-c Shows only the dynamic commands.
-L Shows only local and dynamic commands.
-i Shows only the inherited commands from the parent context.
-a Shows all commands (default)
-f <filename> Write help out in RST format to file.
history(argv)[source]

history [<index>] Display the current readline history buffer.

initialize()[source]
pipe(argv)[source]

pipe <command> Runs a shell command via a pipe, and prints its stdout and stderr. You may also prefix the command with ”!” to run “pipe”.

pop_completer()[source]
printenv(argv)[source]

printenv [name ...] Shows the shell environment that processes will run with.

printf(argv)[source]

printf [<format>] <args>.... Print the arguments according to the format, or all arguments if first is not a format string. Format string has Python format syntax ({} style expansions) combined with Pycopia UI expansions.

push_completer(namespace)[source]
pyeval(argv)[source]
pyexec(argv)[source]
python(argv)[source]
quit(argv)

exit Exits this command interpreter instance.

remove_completion_scope(name)[source]
repeat(argv)[source]

repeat <interval> <command> [<args>...] Repeats a command every <interval> seconds. If <interval> is zero then loop forever (or until interrupted). If <interval> is negative then loop with a count of the absolute value of <interval>.

schedule(argv)[source]

schedule <delay> <command> [<args>...] Schedules a command to run <delay> seconds from now.

set_userinterface(ui)[source]
setenv(argv)[source]

setenv NAME VALUE Sets the environment variable NAME to VALUE, like C shell.

sleep(argv)[source]

sleep <secs> Sleeps for <secs> seconds.

spawn(argv)[source]

spawn <command>... Spawn another process (uses a pty). You may also prefix the command with “%” to run spawn.

stop(argv)[source]

Stops a repeating command.

stty(argv)[source]

stty <args> Sets or clears tty flags. May also use “clear”, “reset”, “sane”.

subshell(io, env=None, aliases=None, theme=None)[source]
time(argv)[source]

time <command> [<args>...] Display the time, in ms, a command takes to run. Result also stored in LASTTIME environment variable.

unalias(argv)[source]

unalias <alias> Remove the named alias from the alias list.

unset(argv)[source]

unset <envar> Unsets the environment variable.

class pycopia.CLI.DictCLI(ui, aliases=None)[source]

Wrap a dictionary-like object and edit it.

clear(argv)[source]

Clears the mapping.

delete(argv)[source]

delete <key> Deletes the given key from the mapping.

get(argv)[source]

get <key> Gets and prints the named value.

has_key(argv)[source]

has_key <key> Report whether or not the mapping has the given key.

initialize()[source]
items(argv)[source]

Show mapping items.

keys(argv)[source]

Show all mapping keys.

length(argv)[source]

Display the length of this mapping object.

pop(argv)[source]

pop <key> Pops the given key from the mapping.

set(argv)[source]

set [-t <type>] <name> <value> Set the mapping key to value. Specify a type of the value with the -t option. If not provided the value is simply evaluated.

values(argv)[source]

Show all mapping values.

class pycopia.CLI.ListCLI(ui, aliases=None)[source]

Wrap a list-like object and edit it.

append(argv)[source]

append <object>... Append object to end of list.

count(argv)[source]

count <object> Show number of occurences of <object>.

delete(argv)[source]

delete <index> Remove <index> node.

extend(argv)[source]

extend <object>... Extend list by appending elements from the given items.

index(argv)[source]

index value [start [stop]] Show first index of value.

initialize()[source]
insert(argv)[source]

insert <index> <object> Insert object before index.

ls(argv)

show Display list contents.

pop(argv)[source]

pop [<index>] Remove and print item at index (default last).

remove(argv)[source]

remove <value> Remove first occurrence of <value>

reverse(argv)[source]

Reverse list, in place.

set(argv)[source]

set [-t <type>] <i> <value> Set the list index to value. Specify a type of the value with the -t option. If not provided the value is simply evaluated.

show(argv)[source]

Display list contents.

sort(argv)[source]

Sort list, in place.

class pycopia.CLI.GenericCLI(ui, aliases=None)[source]

GenericCLI() Generic Object editor commands. Wraps any object and allows inspecting and altering it. Use the get_generic_cli() factory function to get one of these with extra methods/commands that correspond to the wrapped objects methods.

call(argv)[source]

call <name> <arg1>... Calls the named method with the following arguments converted to “likely types”.

delete(argv)[source]

delete <name> Delete the named attribute.

dir(argv)

ls Display a list of the wrapped objects attributes and their types.

get(argv)[source]

get <name> Gets and prints the named attribute.

ls(argv)[source]

Display a list of the wrapped objects attributes and their types.

set(argv)[source]

set [-t <type>] <name> <value> Sets the named attribute to a new value. The value will be converted into a likely suspect, but you can specify a type with the -t flag.

show(argv)[source]

show [<name>] Shows a named attribute of the object, or the object itself if no argument given.

subshell(io, env=None, aliases=None, theme=None)[source]
class pycopia.CLI.FileCLI(ui, aliases=None)[source]

Commands for file-like objects.

interact(argv)[source]

Read and write to the file object. Works best with Process objects.

read(argv)[source]

read [amt] Read <amt> bytes of data.

write(argv)[source]

write <data> Writes the arguments to the file.

class pycopia.CLI.Completer(namespace)[source]
complete(text, state)[source]
static get_class_members(klass, rv=None)[source]
static get_globals()[source]
class pycopia.CLI.Shell(*iargs, **ikwargs)[source]

A simple class for testing object wrappers.

callme(*args, **kwargs)[source]
class pycopia.CLI.CommandParser(cmdobj=None, logfile=None, historyfile=None)[source]

Reads an IO stream and parses input similar to Bourne shell syntax. Calls command methods for each line. Handles readline completer.

VARCHARS = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_?'
close()[source]
command_setup(obj, prompt=None)[source]
commands
feed(text)[source]
initialize()[source]

initializer.

Responsible for setting self._fsm to a parser FSM implementing the CLI syntax.

interact(cmd=None)[source]
parse(url)[source]
parseFile(fo)[source]
pop_command(returnval=None)[source]
push_command(newcmd)[source]
reset(newcmd=None)[source]
pycopia.CLI.globargv(argv)[source]
pycopia.CLI.breakout_args(argv, namespace=None)[source]

convert a list of string arguments (with possible keyword=arg pairs) to the most likely objects.

pycopia.CLI.clieval(val)[source]
pycopia.CLI.get_generic_cmd(obj, ui, cliclass=<class 'pycopia.CLI.GenericCLI'>, aliases=None, gbl=None)[source]

get a GenericCLI (or other) command set wrapping any class instance object. The wrapped objects public methods have CLI command counterparts automatically created.

pycopia.CLI.get_generic_clone(obj, cli, cliclass=<class 'pycopia.CLI.GenericCLI'>, theme=None)[source]

Return a generic clone of an existing Command object.

pycopia.CLI.get_generic_cli(obj, cliclass=GenericCLI, env=None, aliases=None)[source]

Returns a generic CLI object with command methods mirroring the public methods in the supplied object. Ready to interact() with!

pycopia.CLI.get_history_file(obj)[source]

Utility to form a useful history file name from an object instance.

pycopia.CLI.run_cli_wrapper(argv, wrappedclass=<class 'pycopia.CLI.Shell'>, cliclass=<class 'pycopia.CLI.GenericCLI'>, theme=None)[source]

Instantiate a class object (the wrappedclass), and run a CLI wrapper on it.

pycopia.CLI.run_cli(cmdclass, io, env=None, logfile=None, theme=None, historyfile=None)[source]
pycopia.CLI.run_generic_cli(cmdclass=<class 'pycopia.CLI.BaseCommands'>)[source]
pycopia.CLI.get_cli(cmdclass, env=None, aliases=None, logfile=None, paged=False, theme=None, historyfile=None)[source]
pycopia.CLI.get_terminal_ui(env=None, paged=False, theme=None)[source]
pycopia.CLI.get_ui(ioc=<class 'pycopia.IO.ConsoleIO'>, uic=<class 'pycopia.UI.UserInterface'>, themec=<class 'pycopia.UI.ANSITheme'>, env=None)[source]

User Interface base classes and themes.

class pycopia.UI.ANSITheme(ps1='> ', ps2='more> ', ps3='choose', ps4='-> ')[source]

Defines tunable parameters for the UserInterface, to provide different color schemes and prompts.

class pycopia.UI.BasicTheme(ps1='> ', ps2='more> ', ps3='choose', ps4='-> ')[source]
pycopia.UI.DefaultTheme

alias of ANSITheme

class pycopia.UI.FormatWrapper(obj, ui, format)[source]

Wrap any object with a format.

The format string should have an ‘%O’ component that will be expanded to the stringified object given here.

class pycopia.UI.Theme(ps1='> ', ps2='more> ', ps3='choose', ps4='-> ')[source]
BLACK = ''
BLUE = ''
BOLD = ''
BRIGHT = ''
BRIGHTBLUE = ''
BRIGHTCYAN = ''
BRIGHTGREEN = ''
BRIGHTMAGENTA = ''
BRIGHTRED = ''
BRIGHTWHITE = ''
BRIGHTYELLOW = ''
CYAN = ''
DEFAULT = ''
GREEN = ''
GREY = ''
MAGENTA = ''
NORMAL = ''
RED = ''
RESET = ''
UNDERSCORE = ''
WHITE = ''
YELLOW = ''
help_created = ''
help_inherited = ''
help_local = ''
ps1

primary prompt

ps2

more input needed

ps3

choose prompt

ps4

text input prompt

exception pycopia.UI.UIError[source]
exception pycopia.UI.UIFindError[source]
class pycopia.UI.UserInterface(io, env=None, theme=None)[source]

An ANSI terminal user interface for CLIs.

IO
Print(*objs)[source]
choose(somelist, defidx=0, prompt=None)[source]
choose_key(somemap, default=None, prompt=None)[source]
choose_multiple(somelist, chosen=None, prompt=None)[source]
choose_multiple_from_map(somemap, chosen=None, prompt=None)[source]
choose_value(somemap, default=None, prompt=None)[source]
clone(theme=None)[source]
close()[source]
edit_text(text, prompt=None)[source]
error(text)[source]
finalize()[source]
format(ps)[source]

Expand percent-exansions in a string and return the result.

format_wrap(obj, formatstring)[source]
get_IO()[source]
get_key(prompt='')[source]
get_password(prompt='Password: ')[source]
get_text(msg=None)[source]
get_value(prompt, default=None)[source]
get_winsize()[source]
help_created(text)[source]
help_inherited(text)[source]
help_local(text)[source]
initialize(*args)[source]
more_user_input()[source]
pprint(obj)[source]
print_list(clist, indent=0)[source]
print_obj(obj, nl=1)[source]
printf(text)[source]

Print text run through the expansion formatter.

prompt_format(ps)[source]

Expand percent-exansions in a string for readline prompts.

register_format_expansion(key, func)[source]

Register a percent-expansion function for the format method. The function must take one argument, and return a string. The argument is the character expanded on.

register_prompt_expansion(key, func)[source]

Register a percent-expansion function for the prompt format method. The function must take one argument, and return a string. The argument is the character expanded on.

set_IO(io)[source]
set_environ(env)[source]
set_theme(theme)[source]
unregister_format_expansion(key)[source]
user_input(prompt=None)[source]
warning(text)[source]
write(text)[source]
yes_no(prompt, default=True)[source]
pycopia.UI.function_repr(func)[source]
pycopia.UI.get_userinterface(uiname='UserInterface', ioname='IO.ConsoleIO', themename=None)[source]
pycopia.UI.method_repr(method)[source]
pycopia.UI.safe_repr(value)[source]

Return a representational string of the given object.

Large or recursive objects or detected and clipped.

Input/Output objects.

class pycopia.IO.ConsoleErrorIO[source]
close()[source]
errlog(text)[source]
fileno()[source]
isatty()[source]
raw_input(prompt='')[source]
class pycopia.IO.ConsoleIO[source]
close()[source]
errlog(text)[source]
fileno()[source]
isatty()[source]
raw_input(prompt='')[source]

Examples

These are complete CLI implementations that let you navigate some hierarchical configuration formats and edit them interactively.

Command interface to a JSON object. Used for interactive editing of JSON backed configuration files.

pycopia.jsoncli.jsoncli(argv)[source]

jsoncli [-?D] <configfile>...

Provides an interactive CLI for editing a JSON format config file.

Options:
-? = This help text. -D = Debug on.

COmmand interface to a plistconfig object. Used for interactive editing.

pycopia.plistcli.plistcli(argv)[source]

plistcli [-?D] <configfile>...

Provides an interactive CLI for editing a property list file.

Options:
-? = This help text. -D = Debug on.

Table Of Contents

Previous topic

Pycopia core package

Next topic

Pycopia enhanced debugger package