Package plumbum.cli¶
- class plumbum.cli.application.Application(executable=None)[source]¶
The base class for CLI applications; your “entry point” class should derive from it, define the relevant switch functions and attributes, and the
main()
function. The class defines two overridable “meta switches” for version (-v
,--version
) help (-h
,--help
), and help-all (--help-all
).The signature of the main function matters: any positional arguments (e.g., non-switch arguments) given on the command line are passed to the
main()
function; if you wish to allow unlimited number of positional arguments, use varargs (*args
). The names of the arguments will be shown in the help message.The classmethod
run
serves as the entry point of the class. It parses the command-line arguments, invokes switch functions and entersmain
. You should not override this method.Usage:
class FileCopier(Application): stat = Flag("p", "copy stat info as well") def main(self, src, dst): if self.stat: shutil.copy2(src, dst) else: shutil.copy(src, dst) if __name__ == "__main__": FileCopier.run()
There are several class-level attributes you may set:
PROGNAME
- the name of the program; ifNone
(the default), it is set to the name of the executable (argv[0]
); can be in color. If only a color, will be applied to the name.VERSION
- the program’s version (defaults to1.0
, can be in color)DESCRIPTION
- a short description of your program (shown in help). If not set, the class’__doc__
will be used. Can be in color.DESCRIPTION_MORE
- a detailed description of your program (shown in help). The text will be printed by paragraphs (specified by empty lines between them). The indentation of each paragraph will be the indentation of its first line. List items are identified by their first non-whitespace character being one of ‘-’, ‘*’, and ‘/’; so that they are not combined with preceding paragraphs. Bullet ‘/’ is “invisible”, meaning that the bullet itself will not be printed to the output.USAGE
- the usage line (shown in help).COLOR_USAGE_TITLE
- The color of the usage line’s header.COLOR_USAGE
- The color of the usage line.COLOR_GROUPS
- A dictionary that sets colors for the groups, like Meta-switches, Switches, and Subcommands.COLOR_GROUP_TITLES
- A dictionary that sets colors for the group titles. If the dictionary is empty, it defaults toCOLOR_GROUPS
.SUBCOMMAND_HELPMSG
- Controls the printing of extra “see subcommand -h” help message. Default is a message, set to False to remove.ALLOW_ABBREV
- Controls whether partial switch names are supported, for example ‘–ver’ will match ‘–verbose’. Default is False for backward consistency with previous plumbum releases. Note that ambiguous abbreviations will not match, for example if –foothis and –foothat are defined, then –foo will not match.
A note on sub-commands: when an application is the root, its
parent
attribute is set toNone
. When it is used as a nested-command,parent
will point to its direct ancestor. Likewise, when an application is invoked with a sub-command, itsnested_command
attribute will hold the chosen sub-application and its command-line arguments (a tuple); otherwise, it will be set toNone
- classmethod unbind_switches(*switch_names)[source]¶
Unbinds the given switch names from this application. For example
class MyApp(cli.Application): pass MyApp.unbind_switches("--version")
- classmethod subcommand(name, subapp=None)[source]¶
Registers the given sub-application as a sub-command of this one. This method can be used both as a decorator and as a normal
classmethod
:@MyApp.subcommand("foo") class FooApp(cli.Application): pass
Or
MyApp.subcommand("foo", FooApp)
New in version 1.1.
New in version 1.3: The sub-command can also be a string, in which case it is treated as a fully-qualified class name and is imported on demand. For example,
MyApp.subcommand(“foo”, “fully.qualified.package.FooApp”)
- classmethod autocomplete(argv)[source]¶
This is supplied to make subclassing and testing argument completion methods easier
- classmethod run(argv=None, exit=True)[source]¶
Runs the application, taking the arguments from
sys.argv
by default if nothing is passed. Ifexit
isTrue
(the default), the function will exit with the appropriate return code; otherwise it will return a tuple of(inst, retcode)
, whereinst
is the application instance created internally by this function andretcode
is the exit code of the application.Note
Setting
exit
toFalse
is intendend for testing/debugging purposes only – do not override it in other situations.
- classmethod invoke(*args, **switches)[source]¶
Invoke this application programmatically (as a function), in the same way
run()
would. There are two key differences: the return value ofmain()
is not converted to an integer (returned as-is), and exceptions are not swallowed either.- Parameters:
args – any positional arguments for
main()
switches – command-line switches are passed as keyword arguments, e.g.,
foo=5
for--foo=5
- exception plumbum.cli.switches.SwitchError[source]¶
A general switch related-error (base class of all other switch errors)
- exception plumbum.cli.switches.PositionalArgumentsError[source]¶
Raised when an invalid number of positional arguments has been given
- exception plumbum.cli.switches.SwitchCombinationError[source]¶
Raised when an invalid combination of switches has been given
- exception plumbum.cli.switches.UnknownSwitch[source]¶
Raised when an unrecognized switch has been given
- exception plumbum.cli.switches.MissingArgument[source]¶
Raised when a switch requires an argument, but one was not provided
- exception plumbum.cli.switches.MissingMandatorySwitch[source]¶
Raised when a mandatory switch has not been given
- exception plumbum.cli.switches.WrongArgumentType[source]¶
Raised when a switch expected an argument of some type, but an argument of a wrong type has been given
- exception plumbum.cli.switches.SubcommandError[source]¶
Raised when there’s something wrong with sub-commands
- plumbum.cli.switches.switch(names, argtype=None, argname=None, list=False, mandatory=False, requires=(), excludes=(), help=None, overridable=False, group='Switches', envname=None)[source]¶
A decorator that exposes functions as command-line switches. Usage:
class MyApp(Application): @switch(["-l", "--log-to-file"], argtype = str) def log_to_file(self, filename): handler = logging.FileHandler(filename) logger.addHandler(handler) @switch(["--verbose"], excludes=["--terse"], requires=["--log-to-file"]) def set_debug(self): logger.setLevel(logging.DEBUG) @switch(["--terse"], excludes=["--verbose"], requires=["--log-to-file"]) def set_terse(self): logger.setLevel(logging.WARNING)
- Parameters:
names – The name(s) under which the function is reachable; it can be a string or a list of string, but at least one name is required. There’s no need to prefix the name with
-
or--
(this is added automatically), but it can be used for clarity. Single-letter names are prefixed by-
, while longer names are prefixed by--
envname – Name of environment variable to extract value from, as alternative to argv
argtype – If this function takes an argument, you need to specify its type. The default is
None
, which means the function takes no argument. The type is more of a “validator” than a real type; it can be any callable object that raises aTypeError
if the argument is invalid, or returns an appropriate value on success. If the user provides an invalid value,plumbum.cli.WrongArgumentType()
argname – The name of the argument; if
None
, the name will be inferred from the function’s signaturelist – Whether or not this switch can be repeated (e.g.
gcc -I/lib -I/usr/lib
). IfFalse
, only a single occurrence of the switch is allowed; ifTrue
, it may be repeated indefinitely. The occurrences are collected into a list, so the function is only called once with the collections. For instance, forgcc -I/lib -I/usr/lib
, the function will be called with["/lib", "/usr/lib"]
.mandatory – Whether or not this switch is mandatory; if a mandatory switch is not given,
MissingMandatorySwitch
is raised. The default isFalse
.requires –
A list of switches that this switch depends on (“requires”). This means that it’s invalid to invoke this switch without also invoking the required ones. In the example above, it’s illegal to pass
--verbose
or--terse
without also passing--log-to-file
. By default, this list is empty, which means the switch has no prerequisites. If an invalid combination is given,SwitchCombinationError
is raised.Note that this list is made of the switch names; if a switch has more than a single name, any of its names will do.
Note
There is no guarantee on the (topological) order in which the actual switch functions will be invoked, as the dependency graph might contain cycles.
excludes –
A list of switches that this switch forbids (“excludes”). This means that it’s invalid to invoke this switch if any of the excluded ones are given. In the example above, it’s illegal to pass
--verbose
along with--terse
, as it will result in a contradiction. By default, this list is empty, which means the switch has no prerequisites. If an invalid combination is given,SwitchCombinationError
is raised.Note that this list is made of the switch names; if a switch has more than a single name, any of its names will do.
help – The help message (description) for this switch; this description is used when
--help
is given. IfNone
, the function’s docstring will be used.overridable – Whether or not the names of this switch are overridable by other switches. If
False
(the default), having another switch function with the same name(s) will cause an exception. IfTrue
, this is silently ignored.group – The switch’s group; this is a string that is used to group related switches together when
--help
is given. The default group isSwitches
.
- Returns:
The decorated function (with a
_switch_info
attribute)
- plumbum.cli.switches.autoswitch(*args, **kwargs)[source]¶
A decorator that exposes a function as a switch, “inferring” the name of the switch from the function’s name (converting to lower-case, and replacing underscores with hyphens). The arguments are the same as for
switch
.
- class plumbum.cli.switches.SwitchAttr(names, argtype=<class 'str'>, default=None, list=False, argname='VALUE', **kwargs)[source]¶
A switch that stores its result in an attribute (descriptor). Usage:
class MyApp(Application): logfile = SwitchAttr(["-f", "--log-file"], str) def main(self): if self.logfile: open(self.logfile, "w")
- Parameters:
names – The switch names
argtype – The switch argument’s (and attribute’s) type
default – The attribute’s default value (
None
)argname – The switch argument’s name (default is
"VALUE"
)kwargs – Any of the keyword arguments accepted by
switch
- class plumbum.cli.switches.Flag(names, default=False, **kwargs)[source]¶
A specialized
SwitchAttr
for boolean flags. If the flag is not given, the value of this attribute isdefault
; if it is given, the value changes tonot default
. Usage:class MyApp(Application): verbose = Flag(["-v", "--verbose"], help = "If given, I'll be very talkative")
- Parameters:
names – The switch names
default – The attribute’s initial value (
False
by default)kwargs – Any of the keyword arguments accepted by
switch
, except forlist
andargtype
.
- class plumbum.cli.switches.CountOf(names, default=0, **kwargs)[source]¶
A specialized
SwitchAttr
that counts the number of occurrences of the switch in the command line. Usage:class MyApp(Application): verbosity = CountOf(["-v", "--verbose"], help = "The more, the merrier")
If
-v -v -vv
is given in the command-line, it will result inverbosity = 4
.- Parameters:
names – The switch names
default – The default value (0)
kwargs – Any of the keyword arguments accepted by
switch
, except forlist
andargtype
.
- class plumbum.cli.switches.positional(*args, **kargs)[source]¶
Runs a validator on the main function for a class. This should be used like this:
class MyApp(cli.Application): @cli.positional(cli.Range(1,10), cli.ExistingFile) def main(self, x, *f): # x is a range, f's are all ExistingFile's)
Or, Python 3 only:
class MyApp(cli.Application): def main(self, x : cli.Range(1,10), *f : cli.ExistingFile): # x is a range, f's are all ExistingFile's)
If you do not want to validate on the annotations, use this decorator ( even if empty) to override annotation validation.
Validators should be callable, and should have a
.choices()
function with possible choices. (For future argument completion, for example)Default arguments do not go through the validator.
#TODO: Check with MyPy
- class plumbum.cli.switches.Range(start, end)[source]¶
A switch-type validator that checks for the inclusion of a value in a certain range. Usage:
class MyApp(Application): age = SwitchAttr(["--age"], Range(18, 120))
- Parameters:
start – The minimal value
end – The maximal value
- class plumbum.cli.switches.Set(*values: str | Callable[[str], str], case_sensitive: bool = False, csv: bool | str = False, all_markers: collections.abc.Set[str] = frozenset({}))[source]¶
A switch-type validator that checks that the value is contained in a defined set of values. Usage:
class MyApp(Application): mode = SwitchAttr(["--mode"], Set("TCP", "UDP", case_sensitive = False)) num = SwitchAttr(["--num"], Set("MIN", "MAX", int, csv = True))
- Parameters:
values – The set of values (strings), or other callable validators, or types, or any other object that can be compared to a string.
case_sensitive – A keyword argument that indicates whether to use case-sensitive comparison or not. The default is
False
csv – splits the input as a comma-separated-value before validating and returning a list. Accepts
True
,False
, or a string for the separatorall_markers – When a user inputs any value from this set, all values are iterated over. Something like {“*”, “all”} would be a potential setting for this option.
- class plumbum.cli.switches.Predicate(func)[source]¶
A wrapper for a single-argument function with pretty printing
- plumbum.cli.terminal.readline(message: str = '') str [source]¶
Gets a line of input from the user (stdin)
- plumbum.cli.terminal.ask(question: str, default: bool | None = None) bool [source]¶
Presents the user with a yes/no question.
- Parameters:
question – The question to ask
default – If
None
, the user must answer. IfTrue
orFalse
, lack of response is interpreted as the default option
- Returns:
the user’s choice
- plumbum.cli.terminal.choose(question, options, default=None)[source]¶
Prompts the user with a question and a set of options, from which the user needs to choose.
- Parameters:
question – The question to ask
options – A set of options. It can be a list (of strings or two-tuples, mapping text to returned-object) or a dict (mapping text to returned-object).``
default – If
None
, the user must answer. Otherwise, lack of response is interpreted as this answer
- Returns:
The user’s choice
Example:
ans = choose("What is your favorite color?", ["blue", "yellow", "green"], default = "yellow") # `ans` will be one of "blue", "yellow" or "green" ans = choose("What is your favorite color?", {"blue" : 0x0000ff, "yellow" : 0xffff00 , "green" : 0x00ff00}, default = 0x00ff00) # this will display "blue", "yellow" and "green" but return a numerical value
- plumbum.cli.terminal.prompt(question, type=<class 'str'>, default=NotImplemented, validator=<function <lambda>>)[source]¶
Presents the user with a validated question, keeps asking if validation does not pass.
- Parameters:
question – The question to ask
type – The type of the answer, defaults to str
default – The default choice
validator – An extra validator called after type conversion, can raise ValueError or return False to trigger a retry.
- Returns:
the user’s choice
- plumbum.cli.terminal.get_terminal_size(default: Tuple[int, int] = (80, 25)) Tuple[int, int] [source]¶
Get width and height of console; works on linux, os x, windows and cygwin
Adapted from https://gist.github.com/jtriley/1108174 Originally from: http://stackoverflow.com/questions/566746/how-to-get-console-window-width-in-python
- class plumbum.cli.terminal.Progress(iterator=None, length=None, timer=True, body=False, has_output=False, clear=True)[source]¶
Terminal size utility¶
- plumbum.cli.termsize.get_terminal_size(default: Tuple[int, int] = (80, 25)) Tuple[int, int] [source]¶
Get width and height of console; works on linux, os x, windows and cygwin
Adapted from https://gist.github.com/jtriley/1108174 Originally from: http://stackoverflow.com/questions/566746/how-to-get-console-window-width-in-python
Progress bar¶
- class plumbum.cli.progress.ProgressBase(iterator=None, length=None, timer=True, body=False, has_output=False, clear=True)[source]¶
Base class for progress bars. Customize for types of progress bars.
- Parameters:
iterator – The iterator to wrap with a progress bar
length – The length of the iterator (will use
__len__
if None)timer – Try to time the completion status of the iterator
body – True if the slow portion occurs outside the iterator (in a loop, for example)
has_output – True if the iteration body produces output to the screen (forces rewrite off)
clear – Clear the progress bar afterwards, if applicable.
- property value¶
This is the current value, as a property so setting it can be customized
- class plumbum.cli.progress.Progress(iterator=None, length=None, timer=True, body=False, has_output=False, clear=True)[source]¶
- class plumbum.cli.progress.ProgressIPy(*args, **kargs)[source]¶
-
- property value¶
This is the current value, -1 allowed (automatically fixed for display)
- class plumbum.cli.progress.ProgressAuto(*args, **kargs)[source]¶
Automatically selects the best progress bar (IPython HTML or text). Does not work with qtconsole (as that is correctly identified as identical to notebook, since the kernel is the same); it will still iterate, but no graphical indication will be displayed.
- Parameters:
iterator – The iterator to wrap with a progress bar
length – The length of the iterator (will use
__len__
if None)timer – Try to time the completion status of the iterator
body – True if the slow portion occurs outside the iterator (in a loop, for example)