Code Reference


The essence of guacamole.

This module defines the three essential core classes: Ingredient, Bowl, Context. All of those have stable APIs.

class guacamole.core.Ingredient[source]

Part of guacamole.

Ingredients are a mechanism for inserting functionality into Guacamole. The sequence of calls to ingredient methods is as follows:

The added method is where an ingredient can advertise itself to other ingredients that it explicitly collaborates with.

The preparse method is where ingredients can have a peek at the command line arguments. This can serve to optimize further actions. Essentially guacamole allows applications to parse arguments twice and limit the actions needed to do that correctly to the essential minimum required.

The early initialization method can be used to do additional initialization. It can take advantage of the fact that the whole command line arguments are now known and may have been analyzed further by the preparse method.

The parse method is where applications are expected to fully understand command line arguments. This method can abort subsequent execution if arguments are wrong in in some way. After parsing command line arguments the application should be ready for execution.

The late initialization method mimics the early initialization method but is called after parsing all of the command line arguments. Again, it can be used to prepare addiotional resources necessary for a given application.

The dispatch method is where applications execute the bulk of their actions. Dispatching is typically done with one of the standard ingredients which will locate the appropriate method to call into the application.

Depending on the outcome of the dispatch (if an exception is raised or not) one of dispatch_succeeded()`() or dispatch_failed() is called.

This is the last method called on all ingredients.

Each of those methods is called with a context argument (Context:). A context is a free-for-all environment where ingredients can pass data around. There is no name-spacing. Ingredients should advertise what they do with the context and what to expect.


Ingredient method called before anything else.


Ingredient method called to build the early parser.


Ingredient method called to build the full parser.


Ingredient method for dispatching (execution).


The first ingredient that implements this method and returns something other than None will stop command dispatch!


Ingredient method called when dispatching fails.


Ingredient method called when dispatching is correct.


Ingredient method for early initialization.


Ingredient method for late initialization.


Ingredient method called to parse command line arguments.


Ingredient method called to pre-parse command line aruments.


Ingredient method called after all other methods.

class guacamole.core.Context[source]

Context for making guacamole with ingredients.

A context object is created and maintained throughout the life-cycle of an executing tool. A context is passed as argument to all ingredient methods.

Since context has no fixed API anything can be stored and loaded. Particular ingredients document how they use the context object.

class guacamole.core.Bowl(ingredients)[source]

A vessel for preparing guacamole out of ingredients.


Each Bowl is single-use. If you eat it you need to get another one as this one is dirty and cannot be reused.


Add a single spice the bowl.


Eat the guacamole.

Parameters:argv – Command line arguments or None. None means that sys.argv is used
Returns:Whatever is returned by the first ingredient that agrees to perform the command dispatch.

The eat method is called to run the application, as if it was invoked from command line directly.


Check if a given spice is being used.

This method can be used to construct checks if an optional ingredient feature should be enabled or not. Spices are simply strings that describe optional features.

APIs for guacamole add-on developers.

This module contains the public APIs for add-on developers. Add-ons (or plug-ins) for guacamole are called ingredients. The Ingredient class contains a description of available add-on methods.

Ingredients are somewhat similar to Django middleware as they can influence the execution of an application across its life-cycle. All of core guacamole features are implemented as ingredients. Developers are encouraged to read core ingredients to understand how to formulate their own design.

Ingredient APIs are public. They will be maintained for backwards compatibility. Since Guacamole doesn’t automatically enable any third-party ingredients, application developers that wish to use them need to use the guacamole.core module to create their own guacamole out of available ingredients. Ingredient developers are recommended in documenting how to use each ingredient this way.

In addition this module contains the public APIs for creating custom mixes of guacamole. A custom mix begins with a Bowl with any number of Ingredient objects added.

If you are familiar with the Command class you should know that they are using the recipe system internally. They refer to pre-made recipes that put particular ingredients into the bowl for a ready dish.

If you wish to build a custom experience on top of guacamole, please provide a new recipe class. Recipes are how applications should interact with any guacamole mixtures.


Mechanism to use ingredients to dispatch and invoke commands.


Get a list of ingredients for making guacamole.

Returns:A list of initialized ingredients.
Raises:RecipeError – If the recipe is wrong. This is a developer error. Do not handle this exception. Consult the error message to understand what the problem is and correct the recipe instead.
main(argv=None, exit=True)[source]

Shortcut to prepare a bowl of guacamole and eat it.

  • argv – Command line arguments or None. None means that sys.argv is used
  • exit – Raise SystemExit after finishing execution

Whatever is returned by the eating the guacamole.


Whatever is raised by eating the guacamole.


This method always either raises and exception or returns an object. The way it behaves depends on the value of the exit argument.

This method can be used to quickly take a recipe, prepare the guacamole and eat it. It is named main as it is applicable as the main method of an application.

The exit argument controls if main returns normally or raises SystemExit. By default it will raise SystemExit (it will either wrap the return value with SystemExit or re-raise the SystemExit exception again). If SystemExit is raised but exit is False the argument to SystemExit is unwrapped and returned instead.


Prepare a bowl with the ingredients specified by this recipe.

Returns:A new Bowl instance with all the ingredients prepared.

Exception raised when the recipe for guacamole is incorrect.

This exception is only used when a set of ingredients is ordered correctly or has some missing elements. Each time this exception is raised it is accompanied by a detailed message that should help you to resolve the problem.


This exception should not be handled, it is a developer error.

Recipe for using guacamole to run commands.

This module contains sock recipes for guacamole. Stock recipes allow application developers to use use simple-to-understand design patterns to get predictable runtime behiavior.

Currently, guacamole ships with two such recipes, for creating simple commands and for creating hierarhical command groups. They are captured by the Command and Group classes respectively.


A single-purpose command.

Single purpose commands are the most commonly known tools in command line environments. Tools such as ls, mkdir or vim all fall in this class. A command is essentially a named action that can be invoked from the terminal emulator or other command line environment specific to a given operating system.

To create a new command simply create a custom class and override the invoked() method. Put all of your custom code there. If you want to interact with command line arguments then please also override the register_arguments() method.

Have a look at example applications for details of how to do this. You can use them as a starting point for your own application as they are licensed very liberally.


Get the identifier of the application.


Application identifier is looked up using the app_id attribute.

The syntax of a valid command identifier is REVERSE-DNS-NAME:ID. For example, "com.example.product:command". This identifier must not contain characters that are hostile to the file systems. It’s best to stick to ASCII characters and digits.

On Mac OS X this will be used as a directory name rooted in ~/Library/Preferences/. On Linux and other systems this will be used as directory name rooted in $XDG_CONFIG_HOME and $XDG_CACHE_HOME. On Windows it will be used as a directory name rooted in the per-user AppData folder.


If this method returns None then logging and configuration services are disabled. It is strongly recommended to implement this method and return a correct value as it enhances application behavior.


Get the name of the application.


Application name is looked up using the app_name attribute.

Application name differs from executable name. The executable might be called my-app or myapp while the application might be called My Application.


Get the name of the application vendor.

The name should be a human readable name, like "Joe Developer" or "Big Corporation Ltd."


Application vendor name is looked up using the app_vendor attribute.


Get the leading, multi-line description of this command.

Returns:self.description, if defined
Returns:A substring of the class docstring between the first line (which is discarded) and the string @EPILOG@, if present, or the end of the docstring, if any
Returns:None, otherwise

The description string will be displayed after the usage string but before any of the detailed argument descriptions.

Please consider following good practice by keeping the description line short enough not to require scrolling but useful enough to provide additional information that cannot be inferred from the name of the command or other arguments. Stating the purpose of the command is highly recommended.


Get the trailing, multi-line description of this command.

Returns:self.epilog, if defined
Returns:A substring of the class docstring between the string @EPILOG and the end of the docstring, if defined
Returns:None, otherwise

The epilog is similar to the description string but it is instead printed after the section containing detailed descriptions of all of the command line arguments.

Please consider following good practice by providing additional details about how the command can be used, perhaps an example or a reference to means of finding additional documentation.


Get the single-line help of this command., if defined
Returns:The first line of the docstring, without the trailing dot, if present.
Returns:None, otherwise

Get the name of the application executable.


If this method returns None then the executable name is guessed from sys.argv[0].


Get a list of spices requested by this command.

Feature flags are a mechanism that allows application developers to control ingredients (switch them on or off) as well as to control how some ingredients behave.

Returns:self.spices, if defined. This should be a set of strings. Each string represents as single flag. Ingredients should document the set of flags they understand and use.
Returns:An empty set otherwise

Some flags have a generic meaning, you can scope a flag to a given ingredient using the name: prefix where the name is the name of the ingredient.


Get the usage string associated with this command.

Returns:self.usage, if defined
Returns:None, otherwise

The usage string typically contains the list of available, abbreviated options, mandatory arguments and other arguments. Its purpose is to quickly inform the user on the basic syntax used by the command.

It is perfectly fine not to customize this method as the default is to compute an appropriate usage string out of all the arguments. Consider implementing this method in a customized way if your command has highly complicated syntax and you want to provide an alternative, more terse usage string instead.


Get the version reported by this executable.


If this method returns None then the --version option is disabled.


Get the gettext translation domain associated with this command.

The value returned will be used to select translations to global calls to gettext() and ngettext() everywhere in python.


If this method returns None then all i18n services are disabled.


Get the path of the gettext translation catalogs for this command.

This value is used to bind the domain returned by get_gettext_domain() to a specific directory.


If this method returns None then standard, system-wide locations are used (on compatibles systems). In practical terms, on Windows, you may need to use it to have access to localization data.


Get a list of sub-commands of this command.

Returns:self.sub_commands, if defined. This is a sequence of pairs (name, cls) where name is the name of the sub command and cls is a command class (not an object). The name can be None if the command has a version of get_cmd_name() that returns an useful value.
Returns:An empty tuple otherwise

Applications can create hierarchical commands by defining the sub_commands attribute. Many developers are familiar with nested commands, for example git commit is a sub-command of the git command. All commands can be nested this way.


Callback called when the command gets invoked.

Parameters:context – The guacamole context object.
Returns:The return value is returned by the executable. It should be an integer between 0 and 255. Other values are will likely won’t work at all.

The context argument can be used to access command line arguments and other information that guacamole provides.

main(argv=None, exit=True)[source]

Shortcut for running a command.

See for details.


Callback called to register command-specific arguments.

Parameters:parser – Argument parser (from argparse) specific to this command.

A recipe for using commands.


Get a list of ingredients for guacamole.


Package with ingredients bundled with guacamole.


Ingredient for arranging commands into a tree structure.

class guacamole.ingredients.cmdtree.CommandTreeBuilder(command)[source]

Ingredient for arranging commands into a tree of instances.

Since commands and sub-commands are specified as classes there has to be an ingredient that instantiates them and resolves all the naming ambiguities. Here it is.

This component acts early, in its added() method.


Ingredient method called before anything else.

Here this method just builds the full command tree and stores it inside the context as the cmd_tree attribute. The structure of the tree is explained by the build_cmd_tree() function.

class guacamole.ingredients.cmdtree.CommandTreeDispatcher[source]

Ingredient for dispatching commands hierarchically.

This ingredient builds on the CommandTreeBuilder ingredient. It implements the dispatch() method that recurses from the top (root) of the command tree down to the appropriate leaf, calling the invoke() method of each command.

The process stops on the first command that returns a value other than None, raises an exception or until a leaf command is reached. THe ability to return early allows commands to perform some sanity checks or short- circuit execution that is hard to express using standard parser APIs.

Lastly, a command can return a generator, this is treated as a sign that the generator implements a context-manager-like API. In this case the generator is called exactly twice and can be used to manage resources during the lifetime of all sub-commands.


Dispatch execution to the invoke() method of selected commands.

class guacamole.ingredients.cmdtree.cmd_tree_node(cmd_name, cmd_obj, children)

A named tuple for representing the hierarchy of commands.


Alias for field number 2


Alias for field number 0


Alias for field number 1


Ingredients for using arparse for parsing command line arguments.

This module contains two ingredients. The main one is the ParserIngredient. It is responsible for handling all of the command line parsing and command argument registration. It is a part of the recipe for the command class. Note that command dispatch is not handled by this ingredient (see CommandTreeIngredient).

The second ingredient is AutocompleteIngredient which relies on the third-party argcomplete module to add support for automatic command line completion to supported shells (bash).

class guacamole.ingredients.argparse.AutocompleteIngredient[source]

Ingredient for adding shell auto-completion.


This component is not widely tested due to difficulty of providing actual integration. It might be totally broken.


To effectively get tab completion you need to have the argcomplete package installed. In addition, a per-command initialization command has to be created and sourced by the shell. Look at argcomplete documentation for details.


Optionally trigger argument completion in the invoking shell.

This method is called to see if bash argument completion is requested and to honor the request, if needed. This causes the process to exit (early) without giving other ingredients a chance to initialize or shut down.

Due to the way argcomple works, no other ingredient can print() anything to stdout prior to this point.

class guacamole.ingredients.argparse.ParserIngredient[source]

Ingredient for using argparse to parse command line arguments.

This ingredient uses the following Ingredient methods:

  • build_early_parser()
  • preparse()
  • build_parser()
  • parse()

The main parser is constructed in, unsurprisingly, the build_parser() method and stored in the context as parser. Other ingredients can be added after the ParserIngredient and can extend the available arguments (on the root parser) by using standard argparse APIs such as parser.add_argument() or parser.add_argument_group(). This parser is used to handle all of command line in the parse() method.

While most users won’t concern themselves with this design decision, there is also a second parser, called the early parser, that is used to pre-parse the command line arguments. This can be used as a way to optimize subsequent actions as, perhaps, knowing which commands are going to be invoked there will be no need to instantiate and prepare all of the commands in the command tree.

Currently this feature is not used. To take advantage of this knowledge you can look at the context.early_args object which contains the result of parsing the command line with the early parser. The early parser is a simple parser consisting of --help, --version (if applicable) and rest. The rest argument can be used as a hint as to what is coming next (e.g. if it matches a name of a command we know to exist)

After parsing is done the results of parsing the command line are stored in the context.args attribute. This is commonly accessed by individual commands from their invoke() methods.


Create the early argument parser.

This method creates the early argparse argument parser. The early parser doesn’t know about any of the sub-commands so it can be used much earlier during the start-up process (before commands are loaded and initialized).


Create the final argument parser.

This method creates the non-early (full) argparse argument parser. Unlike the early counterpart it is expected to have knowledge of the full command tree.

This method relies on context.cmd_tree and produces context.parser. Other ingredients can interact with the parser up until parse() is called.


Parse command line arguments.

This method relies on context.argv and context.early_parser and produces context.args. Note that .argv is modified by preparse() so it actually has _less_ things in it.

The context.args object is the return value from argparse. It is the dict/object like namespace object.


Parse a portion of command line arguments with the early parser.

This method relies on context.argv and context.early_parser and produces context.early_args.

The context.early_args object is the return value from argparse. It is the dict/object like namespace object.


Ingredient for reacting to application crashes.

class guacamole.ingredients.crash.VerboseCrashHandler[source]

Ingredient for reacting to crashes with a traceback.

You can add this ingredient into your recipe to react to application crashes. It will simply print the exception, as stored in context.exc_type, context.exc_value and context.traceback and raise SystemExit(1).


Print the unhandled exception and exit the application.


Ingredients for using ANSI command sequences.

class guacamole.ingredients.ansi.ANSI[source]

Numerous ANSI constants.

See also

Original specification in the Standard ECMA 48, page 61 (75th page of the PDF).

Wikipedia article about ANSI escape code.

Command for erasing the whole display
Command for erasing the current line
Command for resetting all SGR attributes
SGR code for resetting all attributes

Causes text to be rendered with bold face font or, alternatively, to be rendered with bright color variant. This code is widely supported on Linux. It is not supported on Windows.

Alternate spelling of :attr:`sgr_bold`.
SGR code that activates faint color subset
Alternate spelling of ``sgr_faint``
SGR code that activates italic font face
SGR code that activates underline mode
SGR code that activates slow blinking of characters
SGR code that activates fast blinking of characters
SGR code that activates reverse-video mode
SGR code that activates double-underline mode
static cmd_sgr(sgr_list)[source]

Get a SGR (Set Graphics Rendition) code.

static sgr_bg_indexed(i)[source]

Get SGR (Set Graphics Rendition) background indexed color.

static sgr_bg_rgb(r, g, b)[source]

Get SGR (Set Graphics Rendition) background RGB color.

static sgr_fg_indexed(i)[source]

Get SGR (Set Graphics Rendition) foreground indexed color.

static sgr_fg_rgb(r, g, b)[source]

Get SGR (Set Graphics Rendition) foreground RGB color.

class guacamole.ingredients.ansi.ANSIFormatter(enabled=None)[source]

Formatter for ANSI Set Graphics Rendition codes.

An instance of this class is inserted into the context object as ansi. Using the fact that ANSIFormatter is callable one can easily add ANSI control sequences for foreground and background color as well as text attributes.

aprint(*values, **kwargs)

ANSI formatting-aware print().

This method is a version of print() (function) that understands additional ansi control parameters.

  • value – The values to print, same as with print()
  • sep – Separator between values, same as with print()
  • end – Terminator of the line, same as with print()
  • file – File to print to, same as with print()
  • flush – Flag that controls stream flush behavior, same as with print()
  • fg – Foreground color, same as with __call__().
  • bg – Background color, same as with __call__().
  • style – Text style, same as with __call__().
  • reset – Flag that controls if ANSI attributes are reset at the end, same as with __call__().
  • sgr – Additonal (custom) Set Graphics Rendition directives, same as with __call__().


This implementation only works on Python 3

cmd(cmd, *args)[source]

Get an ANSI control sequence, if the formatter is enabled.


Flag indicating if text style is enabled.

This property is useful to let applications customize their behavior if they know color support is desired and enabled.

class guacamole.ingredients.ansi.ANSIIngredient(enable=None)[source]

Ingredient for colorizing output.


Ingredient method called before anything else.

guacamole.ingredients.ansi.ansi_cmd(cmd, *args)[source]

Get ANSI command code by name.

guacamole.ingredients.ansi.ansi_sgr(text, fg=None, bg=None, style=None, reset=True, **sgr)[source]

Apply desired SGR commands to given text.

  • text – Text or anything convertible to text
  • fg – (optional) Foreground color. Choose one of black, red, green, yellow, blue, magenta cyan or white. Note that the bright SGR impacts effective color in most implementations.
guacamole.ingredients.ansi.get_intensity(r, g, b)[source]

Get the gray level intensity of the given rgb triplet.


Get the visible counter-color.