Package plumbum.cli¶
-
class
plumbum.cli.application.
Application
(executable)[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
) and help (-h
,--help
).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 entermain
. 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]
)VERSION
- the program’s version (defaults to1.0
)DESCRIPTION
- a short description of your program (shown in help). If not set, the class’__doc__
will be used.USAGE
- the usage line (shown in help)
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 be 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("--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 subcommand can also be a string, in which case it is treated as a fully-qualified class name and is imported on demand. For examples,
MyApp.subcommand(“foo”, “fully.qualified.package.FooApp”)
-
classmethod
run
(argv=['/usr/bin/sphinx-build', '-b', 'pickle', '-d', '_build/doctrees', '.', '_build/pickle'], exit=True)[source]¶ Runs the application, taking the arguments from
sys.argv
by default. 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 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
- args – any positional arguments for
-
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 subcommands
-
plumbum.cli.switches.
switch
(names, argtype=None, argname=None, list=False, mandatory=False, requires=(), excludes=(), help=None, overridable=False, group='Switches')[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--
- 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 signature - list – 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)- 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
-
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=<type '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 is thedefault
; 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.
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, **kwargs)[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_insensitive = False))
Parameters: - values – The set of values (strings)
- case_insensitive – A keyword argument that indicates whether to use case-sensitive
comparison or not. The default is
True
-
class
plumbum.cli.switches.
Predicate
(func)[source]¶ A wrapper for a single-argument function with pretty printing
Terminal-related utilities
-
plumbum.cli.terminal.
get_terminal_size
()[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
-
plumbum.cli.terminal.
ask
(question, default=None)[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 need 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