This part of the documentation lists the full API reference of all public classes and functions.
Creates a new Command and uses the decorated function as callback. This will also automatically attach all decorated option()s and argument()s as parameters to the command.
The name of the command defaults to the name of the function. If you want to change that, you can pass the intended name as the first argument.
All keyword arguments are forwarded to the underlying command class.
Once decorated the function turns into a Command instance that can be invoked as a command line utility or be attached to a command Group.
Parameters: |
|
---|
Creates a new Group with a function as callback. This works otherwise the same as command() just that the cls parameter is set to Group.
Attaches an option to the command. All positional arguments are passed as parameter declarations to Argument; all keyword arguments are forwarded unchanged. This is equivalent to creating an Option instance manually and attaching it to the Command.params list.
Attaches an option to the command. All positional arguments are passed as parameter declarations to Option; all keyword arguments are forwarded unchanged. This is equivalent to creating an Option instance manually and attaching it to the Command.params list.
Shortcut for password prompts.
This is equivalent to decorating a function with option() with the following parameters:
@click.command()
@click.option('--password', prompt=True, confirmation_prompt=True,
hide_input=True)
def changeadmin(password):
pass
Shortcut for confirmation prompts that can be ignored by passing --yes as parameter.
This is equivalent to decorating a function with option() with the following parameters:
def callback(ctx, param, value):
if not value:
ctx.abort()
@click.command()
@click.option('--yes', is_flag=True, callback=callback,
expose_value=False, prompt='Do you want to continue?')
def dropdb():
pass
Adds a --version option which immediately ends the program printing out the version number. This is implemented as an eager option that prints the version and exits the program in the callback.
Parameters: |
|
---|
Adds a --help option which immediately ends the program printing out the help page. This is usually unnecessary to add as this is added by default to all commands unless suppressed.
Like version_option(), this is implemented as eager option that prints in the callback and exits.
All arguments are forwarded to option().
Marks a callback as wanting to receive the current context object as first argument.
Similar to pass_context(), but only pass the object on the context onwards (Context.obj). This is useful if that object represents the state of a nested system.
Given an object type this creates a decorator that will work similar to pass_obj() but instead of passing the object of the current context, it will find the innermost context of type object_type().
This generates a decorator that works roughly like this:
from functools import update_wrapper
def decorator(f):
@pass_context
def new_func(ctx, *args, **kwargs):
obj = ctx.find_object(object_type)
return ctx.invoke(f, obj, *args, **kwargs)
return update_wrapper(new_func, f)
return decorator
Parameters: |
|
---|
Prints a message plus a newline to the given file or stdout. On first sight, this looks like the print function, but it has improved support for handling Unicode and binary data that does not fail no matter how badly configured the system is.
Primarily it means that you can print binary data as well as Unicode data on both 2.x and 3.x to the given file in the most appropriate way possible. This is a very carefree function as in that it will try its best to not fail.
In addition to that, if colorama is installed, the echo function will also support clever handling of ANSI codes. Essentially it will then do the following:
Changed in version 2.0: Starting with version 2.0 of Click, the echo function will work with colorama if it’s installed.
New in version 3.0: The err parameter was added.
Changed in version 4.0: Added the color flag.
Parameters: |
|
---|
This function takes a text and shows it via an environment specific pager on stdout.
Changed in version 3.0: Added the color flag.
Parameters: |
|
---|
Prompts a user for input. This is a convenience function that can be used to prompt a user for input later.
If the user aborts the input by sending a interrupt signal, this function will catch it and raise a Abort exception.
New in version 4.0: Added the err parameter.
Parameters: |
|
---|
Prompts for confirmation (yes/no question).
If the user aborts the input by sending a interrupt signal this function will catch it and raise a Abort exception.
New in version 4.0: Added the err parameter.
Parameters: |
|
---|
This function creates an iterable context manager that can be used to iterate over something while showing a progress bar. It will either iterate over the iterable or length items (that are counted up). While iteration happens, this function will print a rendered progress bar to the given file (defaults to stdout) and will attempt to calculate remaining time and more. By default, this progress bar will not be rendered if the file is not a terminal.
The context manager creates the progress bar. When the context manager is entered the progress bar is already displayed. With every iteration over the progress bar, the iterable passed to the bar is advanced and the bar is updated. When the context manager exits, a newline is printed and the progress bar is finalized on screen.
No printing must happen or the progress bar will be unintentionally destroyed.
Example usage:
with progressbar(items) as bar:
for item in bar:
do_something_with(item)
New in version 2.0.
New in version 4.0: Added the color parameter.
Parameters: |
|
---|
Clears the terminal screen. This will have the effect of clearing the whole visible space of the terminal and moving the cursor to the top left. This does not do anything if not connected to a terminal.
New in version 2.0.
Styles a text with ANSI styles and returns the new string. By default the styling is self contained which means that at the end of the string a reset code is issued. This can be prevented by passing reset=False.
Examples:
click.echo(click.style('Hello World!', fg='green'))
click.echo(click.style('ATTENTION!', blink=True))
click.echo(click.style('Some things', reverse=True, fg='cyan'))
Supported color names:
New in version 2.0.
Parameters: |
|
---|
Removes ANSI styling information from a string. Usually it’s not necessary to use this function as Click’s echo function will automatically remove styling if necessary.
New in version 2.0.
Parameters: | text – the text to remove style information from. |
---|
This function combines echo() and style() into one call. As such the following two calls are the same:
click.secho('Hello World!', fg='green')
click.echo(click.style('Hello World!', fg='green'))
All keyword arguments are forwarded to the underlying functions depending on which one they go with.
New in version 2.0.
Edits the given text in the defined editor. If an editor is given (should be the full path to the executable but the regular operating system search path is used for finding the executable) it overrides the detected editor. Optionally, some environment variables can be used. If the editor is closed without changes, None is returned. In case a file is edited directly the return value is always None and require_save and extension are ignored.
If the editor cannot be opened a UsageError is raised.
Note for Windows: to simplify cross-platform usage, the newlines are automatically converted from POSIX to Windows and vice versa. As such, the message here will have \n as newline markers.
Parameters: |
|
---|
This function launches the given URL (or filename) in the default viewer application for this file type. If this is an executable, it might launch the executable in a new session. The return value is the exit code of the launched application. Usually, 0 indicates success.
Examples:
click.launch('http://click.pocoo.org/')
click.launch('/my/downloaded/file', locate=True)
New in version 2.0.
Parameters: |
|
---|
Fetches a single character from the terminal and returns it. This will always return a unicode character and under certain rare circumstances this might return more than one character. The situations which more than one character is returned is when for whatever reason multiple characters end up in the terminal buffer or standard input was not actually a terminal.
Note that this will always read from the terminal, even if something is piped into the standard input.
New in version 2.0.
Parameters: | echo – if set to True, the character read will also show up on the terminal. The default is to not show it. |
---|
This command stops execution and waits for the user to press any key to continue. This is similar to the Windows batch “pause” command. If the program is not run through a terminal, this command will instead do nothing.
New in version 2.0.
New in version 4.0: Added the err parameter.
Parameters: |
|
---|
Returns the current size of the terminal as tuple in the form (width, height) in columns and rows.
Returns a system stream for byte processing. This essentially returns the stream from the sys module with the given name but it solves some compatibility issues between different Python versions. Primarily this function is necessary for getting binary streams on Python 3.
Parameters: | name – the name of the stream to open. Valid names are 'stdin', 'stdout' and 'stderr' |
---|
Returns a system stream for text processing. This usually returns a wrapped stream around a binary stream returned from get_binary_stream() but it also can take shortcuts on Python 3 for already correctly configured streams.
Parameters: |
|
---|
This is similar to how the File works but for manual usage. Files are opened non lazy by default. This can open regular files as well as stdin/stdout if '-' is passed.
If stdin/stdout is returned the stream is wrapped so that the context manager will not close the stream accidentally. This makes it possible to always use the function like this without having to worry to accidentally close a standard stream:
with open_file(filename) as f:
...
New in version 3.0.
Parameters: |
|
---|
Returns the config folder for the application. The default behavior is to return whatever is most appropriate for the operating system.
To give you an idea, for an app called "Foo Bar", something like the following folders could be returned:
New in version 2.0.
Parameters: |
|
---|
Formats a filename for user display. The main purpose of this function is to ensure that the filename can be displayed at all. This will decode the filename to unicode if necessary in a way that it will not fail. Optionally, it can shorten the filename to not include the full path to the filename.
Parameters: |
|
---|
The base command implements the minimal API contract of commands. Most code will never use this as it does not implement a lot of useful functionality but it can act as the direct subclass of alternative parsing methods that do not depend on the Click parser.
For instance, this can be used to bridge Click and other systems like argparse or docopt.
Because base commands do not implement a lot of the API that other parts of Click take for granted, they are not supported for all operations. For instance, they cannot be used with the decorators usually and they have no built-in callback system.
Changed in version 2.0: Added the context_settings parameter.
Parameters: |
|
---|
the default for the Context.allow_extra_args flag.
the default for the Context.allow_interspersed_args flag.
an optional dictionary with defaults passed to the context.
the default for the Context.ignore_unknown_options flag.
Given a context, this invokes the command. The default implementation is raising a not implemented error.
This is the way to invoke a script with all the bells and whistles as a command line application. This will always terminate the application after a call. If this is not wanted, SystemExit needs to be caught.
This method is also available by directly calling the instance of a Command.
New in version 3.0: Added the standalone_mode flag to control the standalone mode.
Parameters: |
|
---|
This function when given an info name and arguments will kick off the parsing and create a new Context. It does not invoke the actual command callback though.
Parameters: |
|
---|
the name the command thinks it has. Upon registering a command on a Group the group will default the command name with this information. You should instead use the Context‘s info_name attribute.
Given a context and a list of arguments this creates the parser and parses the arguments, then modifies the context as necessary. This is automatically invoked by make_context().
Commands are the basic building block of command line interfaces in Click. A basic command handles command line parsing and might dispatch more parsing to commands nested below it.
Changed in version 2.0: Added the context_settings parameter.
Parameters: |
|
---|
the callback to execute when the command fires. This might be None in which case nothing happens.
Returns all the pieces that go into the usage line and returns it as a list of strings.
Writes the epilog into the formatter if it exists.
Writes the help into the formatter if it exists.
This calls into the following methods:
Writes the help text to the formatter if it exists.
Writes all the options into the formatter if they exist.
Writes the usage line into the formatter.
Formats the help into a string and returns it. This creates a formatter and will call into the following formatting methods:
Returns the help option object.
Returns the names for the help option.
Given a context, this invokes the attached callback (if it exists) in the right way.
Creates the underlying option parser for this command.
the list of parameters for this command in the order they should show up in the help page and execute. Eager parameters will automatically be handled before non eager ones.
A multi command is the basic implementation of a command that dispatches to subcommands. The most common version is the Command.
Parameters: |
|
---|
Extra format methods for multi methods that adds all the commands after the options.
Given a context and a command name, this returns a Command object if it exists or returns None.
Returns a list of subcommand names in the order they should appear.
The result callback that is stored. This can be set or overridden with the resultcallback() decorator.
Adds a result callback to the chain command. By default if a result callback is already registered this will chain them but this can be disabled with the replace parameter. The result callback is invoked with the return value of the subcommand (or the list of return values from all subcommands if chaining is enabled) as well as the parameters as they would be passed to the main callback.
Example:
@click.group()
@click.option('-i', '--input', default=23)
def cli(input):
return 42
@cli.resultcallback()
def process_result(result, input):
return result + input
New in version 3.0.
Parameters: | replace – if set to True an already existing result callback will be removed. |
---|
A group allows a command to have subcommands attached. This is the most common way to implement nesting in Click.
Parameters: | commands – a dictionary of commands. |
---|
Registers another Command with this group. If the name is not provided, the name of the command is used.
A shortcut decorator for declaring and attaching a command to the group. This takes the same arguments as command() but immediately registers the created command with this instance by calling into add_command().
the registered subcommands by their exported names.
A shortcut decorator for declaring and attaching a group to the group. This takes the same arguments as group() but immediately registers the created command with this instance by calling into add_command().
A command collection is a multi command that merges multiple multi commands together into one. This is a straightforward implementation that accepts a list of different multi commands as sources and provides all the commands for each of them.
Adds a new multi command to the chain dispatcher.
The list of registered multi commands.
A parameter to a command comes in two versions: they are either Options or Arguments. Other subclasses are currently not supported by design as some of the internals for parsing are intentionally not finalized.
Some settings are supported by both options and arguments.
Changed in version 2.0: Changed signature for parameter callback to also be passed the parameter. In Click 2.0, the old callback format will still work, but it will raise a warning to give you change to migrate the code easier.
Parameters: |
|
---|
Given a context variable this calculates the default value.
Given a value and context this runs the logic to convert the value as necessary.
Given a value this runs it properly through the type system. This automatically handles things like nargs and multiple.
Options are usually optional values on the command line and have some extra features that arguments don’t have.
All other parameters are passed onwards to the parameter constructor.
Parameters: |
|
---|
Arguments are positional parameters to a command. They generally provide fewer features than options but can have infinite nargs and are required by default.
All parameters are passed onwards to the parameter constructor.
The context is a special internal object that holds state relevant for the script execution at every single level. It’s normally invisible to commands unless they opt-in to getting access to it.
The context is useful as it can pass internal objects around and can control special execution features such as reading data from environment variables.
A context can be used as context manager in which case it will call close() on teardown.
New in version 2.0: Added the resilient_parsing, help_option_names, token_normalize_func parameters.
New in version 3.0: Added the allow_extra_args and allow_interspersed_args parameters.
New in version 4.0: Added the color, ignore_unknown_options, and max_content_width parameters.
Parameters: |
|
---|
Aborts the script.
Indicates if the context allows extra args or if it should fail on parsing.
New in version 3.0.
Indicates if the context allows mixing of arguments and options or not.
New in version 3.0.
the leftover arguments.
This decorator remembers a function as callback that should be executed when the context tears down. This is most useful to bind resource handling to the script execution. For instance, file objects opened by the File type will register their close callbacks here.
Parameters: | f – the function to execute on teardown. |
---|
Invokes all close callbacks.
Controls if styling output is wanted or not.
The computed command path. This is used for the usage information on the help page. It’s automatically created by combining the info names of the chain of contexts to the root.
Like find_object() but sets the innermost object to a new instance of object_type if it does not exist.
Exits the application with a given exit code.
Aborts the execution of the program with a specific error message.
Parameters: | message – the error message to fail with. |
---|
Finds the closest object of a given type.
Finds the outermost context.
Similar to invoke() but fills in default keyword arguments from the current context if the other command expects it. This cannot invoke callbacks directly, only other commands.
Helper method to get formatted help page for the current context and command.
Helper method to get formatted usage string for the current context and command.
The names for the help options.
Instructs click to ignore options that a command does not understand and will store it on the context for later processing. This is primarily useful for situations where you want to call into external programs. Generally this pattern is strongly discouraged because it’s not possibly to losslessly forward all arguments.
New in version 4.0.
the descriptive information name
Invokes a command callback in exactly the way it expects. There are two ways to invoke this method:
Note that before Click 3.2 keyword arguments were not properly filled in against the intention of this code and no context was created. For more information about this change and why it was done in a bugfix release see Upgrading to 3.2.
This flag indicates if a subcommand is going to be executed. A group callback can use this information to figure out if it’s being executed directly or because the execution flow passes onwards to a subcommand. By default it’s None, but it can be the name of the subcommand to execute.
If chaining is enabled this will be set to '*' in case any commands are executed. It is however not possible to figure out which ones. If you require this knowledge you should use a resultcallback().
Looks up the default for a parameter name. This by default looks into the default_map if available.
Creates the formatter for the help and usage output.
The maximum width of formatted content (None implies a sensible default which is 80 for most things).
the user object stored.
the parsed parameters except if the value is hidden in which case it’s not remembered.
the parent context or None if none exists.
Indicates if resilient parsing is enabled. In that case Click will do its best to not cause any failures.
The width of the terminal (None is autodetection).
An optional normalization function for tokens. This is options, choices, commands etc.
A unicode string parameter type which is the implicit default. This can also be selected by using str as type.
An integer parameter. This can also be selected by using int as type.
A floating point value parameter. This can also be selected by using float as type.
A boolean parameter. This is the default for boolean flags. This can also be selected by using bool as a type.
A UUID parameter.
A dummy parameter type that just does nothing. From a user’s perspective this appears to just be the same as STRING but internally no string conversion takes place. This is necessary to achieve the same bytes/unicode behavior on Python 2/3 in situations where you want to not convert argument types. This is usually useful when working with file paths as they can appear in bytes and unicode.
For path related uses the Path type is a better choice but there are situations where an unprocessed type is useful which is why it is is provided.
New in version 4.0.
Declares a parameter to be a file for reading or writing. The file is automatically closed once the context tears down (after the command finished working).
Files can be opened for reading or writing. The special value - indicates stdin or stdout depending on the mode.
By default, the file is opened for reading text data, but it can also be opened in binary mode or for writing. The encoding parameter can be used to force a specific encoding.
The lazy flag controls if the file should be opened immediately or upon first IO. The default is to be non lazy for standard input and output streams as well as files opened for reading, lazy otherwise.
Starting with Click 2.0, files can also be opened atomically in which case all writes go into a separate file in the same folder and upon completion the file will be moved over to the original location. This is useful if a file regularly read by other users is modified.
See File Arguments for more information.
The path type is similar to the File type but it performs different checks. First of all, instead of returning a open file handle it returns just the filename. Secondly, it can perform various basic checks about what the file or directory should be.
Parameters: |
|
---|
The choice type allows a value to checked against a fixed set of supported values. All of these values have to be strings.
See Choice Options for an example.
A parameter that works similar to click.INT but restricts the value to fit into a range. The default behavior is to fail if the value falls outside the range, but it can also be silently clamped between the two edges.
See Range Options for an example.
Helper for converting values through types. The following is necessary for a valid type:
Converts the value. This is not invoked for values that are None (the missing value).
if a list of this type is expected and the value is pulled from a string environment variable, this is what splits it up. None means any whitespace. For all parameters the general rule is that whitespace splits them up. The exception are paths and files which are split by os.path.pathsep by default (”:” on Unix and ”;” on Windows).
Helper method to fail with an invalid value message.
Returns the metavar default for this param if it provides one.
Optionally might return extra information about a missing parameter.
New in version 2.0.
the descriptive name of this type
Given a value from an environment variable this splits it up into small chunks depending on the defined envvar list splitter.
If the splitter is set to None, which means that whitespace splits, then leading and trailing whitespace is ignored. Otherwise, leading and trailing splitters usually lead to empty items being included.
An exception that Click can handle and show to the user.
An internal signalling exception that signals Click to abort.
An internal exception that signals a usage error. This typically aborts any further handling.
Parameters: |
|
---|
An exception that formats out a standardized error message for a bad parameter. This is useful when thrown from a callback or type as Click will attach contextual information to it (for instance, which parameter it is).
New in version 2.0.
Parameters: |
|
---|
Raised if a file cannot be opened.
Raised if click attempted to handle an option that does not exist.
New in version 4.0.
Raised if an option is generally supplied but the use of the option was incorrect. This is for instance raised if the number of arguments for an option is not correct.
New in version 4.0.
This class helps with formatting text-based help pages. It’s usually just needed for very special internal cases, but it’s also exposed so that developers can write their own fancy outputs.
At present, it always writes into memory.
Parameters: |
|
---|
Decreases the indentation.
Returns the buffer contents.
Increases the indentation.
A context manager that increases the indentation.
Helpful context manager that writes a paragraph, a heading, and the indents.
Parameters: | name – the section name that is written as heading. |
---|
Writes a unicode string into the internal buffer.
Writes a definition list into the buffer. This is how options and commands are usually formatted.
Parameters: |
|
---|
Writes a heading into the buffer.
Writes a paragraph into the buffer.
Writes re-indented text into the buffer. This rewraps and preserves paragraphs.
Writes a usage line into the buffer.
Parameters: |
|
---|
A helper function that intelligently wraps text. By default, it assumes that it operates on a single paragraph of text but if the preserve_paragraphs parameter is provided it will intelligently handle paragraphs (defined by two empty lines).
If paragraphs are handled, a paragraph can be prefixed with an empty line containing the \b character (\x08) to indicate that no rewrapping should happen in that block.
Parameters: |
|
---|
The option parser is an internal class that is ultimately used to parse options and arguments. It’s modelled after optparse and brings a similar but vastly simplified API. It should generally not be used directly as the high level Click classes wrap it for you.
It’s not nearly as extensible as optparse or argparse as it does not implement features that are implemented on a higher level (such as types or defaults).
Parameters: | ctx – optionally the Context where this parser should go with. |
---|
Adds a positional argument named dest to the parser.
The obj can be used to identify the option in the order list that is returned from the parser.
Adds a new option named dest to the parser. The destination is not inferred (unlike with optparse) and needs to be explicitly provided. Action can be any of store, store_const, append, appnd_const or count.
The obj can be used to identify the option in the order list that is returned from the parser.
This controls how the parser deals with interspersed arguments. If this is set to False, the parser will stop on the first non-option. Click uses this to implement nested subcommands safely.
This tells the parser how to deal with unknown options. By default it will error out (which is sensible), but there is a second mode where it will ignore it and continue processing after shifting all the unknown options into the resulting args.
Parses positional arguments and returns (values, args, order) for the parsed options and arguments as well as the leftover arguments if there are any. The order is a list of objects as they appear on the command line. If arguments appear multiple times they will be memorized multiple times as well.
The CLI runner provides functionality to invoke a Click command line script for unittesting purposes in a isolated environment. This only works in single-threaded systems without any concurrency as it changes the global interpreter state.
Parameters: |
|
---|
Given a command object it will return the default program name for it. The default is the name attribute or "root" if not set.
Invokes a command in an isolated environment. The arguments are forwarded directly to the command line script, the extra keyword arguments are passed to the main() function of the command.
This returns a Result object.
New in version 3.0: The catch_exceptions parameter was added.
Changed in version 3.0: The result object now has an exc_info attribute with the traceback if available.
Parameters: |
|
---|
A context manager that creates a temporary folder and changes the current working directory to it for isolated filesystem tests.
A context manager that sets up the isolation for invoking of a command line tool. This sets up stdin with the given input data and os.environ with the overrides from the given dictionary. This also rebinds some internals in Click to be mocked (like the prompt functionality).
This is automatically done in the invoke() method.
Parameters: |
|
---|
Returns the environment overrides for invoking a script.
Holds the captured result of an invoked CLI script.
The traceback
The exception that happend if one did.
The exit code as integer.
The output as unicode string.
The output as bytes.
The runner that created the result