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) 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 enters main. You should not override this method.


class FileCopier(Application):
    stat = Flag("p", "copy stat info as well")

    def main(self, src, dst):
        if self.stat:
            shutil.copy2(src, dst)
            shutil.copy(src, dst)

if __name__ == "__main__":

There are several class-level attributes you may set:

  • PROGNAME - the name of the program; if None (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 to 1.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 - The color of the usage line
  • COLOR_GROUPS - A dictionary that sets colors for the groups, like Meta-switches, Switches, and Subcommands
  • SUBCOMMAND_HELPMSG - Controls the printing of extra “see subcommand -h” help message. Default is a message, set to False to remove.

A note on sub-commands: when an application is the root, its parent attribute is set to None. 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, its nested_command attribute will hold the chosen sub-application and its command-line arguments (a tuple); otherwise, it will be set to None

classmethod unbind_switches(*switch_names)[source]

Unbinds the given switch names from this application. For example

class MyApp(cli.Application):
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:

class FooApp(cli.Application):


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. If exit is True (the default), the function will exit with the appropriate return code; otherwise it will return a tuple of (inst, retcode), where inst is the application instance created internally by this function and retcode is the exit code of the application.


Setting exit to False 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 of main() is not converted to an integer (returned as-is), and exceptions are not swallowed either.

  • args – any positional arguments for main()
  • switches – command-line switches are passed as keyword arguments, e.g., foo=5 for --foo=5

Implement me (no need to call super)


Called after main() and all sub-applications have executed, to perform any necessary cleanup.

Parameters:retcode – the return code of main()

Prints help messages of all sub-commands and quits


Prints this help message and quits


Prints the program’s version and quits

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)

    @switch(["--verbose"], excludes=["--terse"], requires=["--log-to-file"])
    def set_debug(self):

    @switch(["--terse"], excludes=["--verbose"], requires=["--log-to-file"])
    def set_terse(self):
  • 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 a TypeError 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). If False, only a single occurrence of the switch is allowed; if True, it may be repeated indefinitely. The occurrences are collected into a list, so the function is only called once with the collections. For instance, for gcc -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 is False.
  • 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.


    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. If None, 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. If True, 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 is Switches.

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=<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")
  • 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 default; if it is given, the value changes to not default. Usage:

class MyApp(Application):
    verbose = Flag(["-v", "--verbose"], help = "If given, I'll be very talkative")
  • names – The switch names
  • default – The attribute’s initial value (False by default)
  • kwargs – Any of the keyword arguments accepted by switch, except for list and argtype.
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 in verbosity = 4.

  • names – The switch names
  • default – The default value (0)
  • kwargs – Any of the keyword arguments accepted by switch, except for list and argtype.
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))
  • 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_sensitive = False))
  • values – The set of values (strings)
  • case_sensitive – A keyword argument that indicates whether to use case-sensitive comparison or not. The default is False
class plumbum.cli.switches.Predicate(func)[source]

A wrapper for a single-argument function with pretty printing

Terminal size utility

plumbum.cli.termsize.get_terminal_size(default=(80, 25))[source]

Get width and height of console; works on linux, os x, windows and cygwin

Adapted from Originally from:

Progress bar

class plumbum.cli.progress.ProgressAuto(iterator=None, length=None, timer=True, body=False, has_output=False, clear=True)[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 diplayed.

  • 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)
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.

  • 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.

Called to update the progress bar


Is called when the iterator is done.


Sets next value and displays the bar

classmethod range(*value, **kargs)[source]

Fast shortcut to create a range based progress bar, assumes work done in body


This should initialize the progress bar and the iterator


Returns a string version of time remaining


Get the time remaining for the progress bar, guesses


This is the current value, as a property so setting it can be customized

classmethod wrap(iterator, length=None, **kargs)[source]

Shortcut to wrap an iterator that does not do all the work internally