API

This part of the documentation lists the full API reference of all publicclasses and functions.

Decorators

click.command(name:Callable[[...],Any])Command
click.command(name:str|None,cls:type[CmdType],**attrs:Any)Callable[[Callable[[...],Any]],CmdType]
click.command(name:None=None,*,cls:type[CmdType],**attrs:Any)Callable[[Callable[[...],Any]],CmdType]
click.command(name:str|None=None,cls:None=None,**attrs:Any)Callable[[Callable[[...],Any]],Command]

Creates a newCommand and uses the decorated function ascallback. This will also automatically attach all decoratedoption()s andargument()s as parameters to the command.

The name of the command defaults to the name of the function, converted tolowercase, with underscores_ replaced by dashes-, and the suffixes_command,_cmd,_group, and_grp are removed. For example,init_data_command becomesinit-data.

All keyword arguments are forwarded to the underlying command class.For theparams argument, any decorated params are appended tothe end of the list.

Once decorated the function turns into aCommand instancethat can be invoked as a command line utility or be attached to acommandGroup.

Parameters:
  • name – The name of the command. Defaults to modifying the function’sname as described above.

  • cls – The command class to create. Defaults toCommand.

Changelog

Changed in version 8.2:The suffixes_command,_cmd,_group, and_grp areremoved when generating the name.

Changed in version 8.1:This decorator can be applied without parentheses.

Changed in version 8.1:Theparams argument can be used. Decorated params areappended to the end of the list.

click.group(name:Callable[[...],Any])Group
click.group(name:str|None,cls:type[GrpType],**attrs:Any)Callable[[Callable[[...],Any]],GrpType]
click.group(name:None=None,*,cls:type[GrpType],**attrs:Any)Callable[[Callable[[...],Any]],GrpType]
click.group(name:str|None=None,cls:None=None,**attrs:Any)Callable[[Callable[[...],Any]],Group]

Creates a newGroup with a function as callback. Thisworks otherwise the same ascommand() just that theclsparameter is set toGroup.

Changelog

Changed in version 8.1:This decorator can be applied without parentheses.

click.argument(*param_decls,cls=None,**attrs)

Attaches an argument to the command. All positional arguments arepassed as parameter declarations toArgument; all keywordarguments are forwarded unchanged (exceptcls).This is equivalent to creating anArgument instance manuallyand attaching it to theCommand.params list.

For the default argument class, refer toArgument andParameter for descriptions of parameters.

Parameters:
  • cls (type[Argument]|None) – the argument class to instantiate. This defaults toArgument.

  • param_decls (str) – Passed as positional arguments to the constructor ofcls.

  • attrs (Any) – Passed as keyword arguments to the constructor ofcls.

Return type:

Callable[[FC],FC]

click.option(*param_decls,cls=None,**attrs)

Attaches an option to the command. All positional arguments arepassed as parameter declarations toOption; all keywordarguments are forwarded unchanged (exceptcls).This is equivalent to creating anOption instance manuallyand attaching it to theCommand.params list.

For the default option class, refer toOption andParameter for descriptions of parameters.

Parameters:
  • cls (type[Option]|None) – the option class to instantiate. This defaults toOption.

  • param_decls (str) – Passed as positional arguments to the constructor ofcls.

  • attrs (Any) – Passed as keyword arguments to the constructor ofcls.

Return type:

Callable[[FC],FC]

click.password_option(*param_decls,**kwargs)

Add a--password option which prompts for a password, hidinginput and asking to enter the value again for confirmation.

Parameters:
  • param_decls (str) – One or more option names. Defaults to the singlevalue"--password".

  • kwargs (Any) – Extra arguments are passed tooption().

Return type:

Callable[[FC],FC]

click.confirmation_option(*param_decls,**kwargs)

Add a--yes option which shows a prompt before continuing ifnot passed. If the prompt is declined, the program will exit.

Parameters:
  • param_decls (str) – One or more option names. Defaults to the singlevalue"--yes".

  • kwargs (Any) – Extra arguments are passed tooption().

Return type:

Callable[[FC],FC]

click.version_option(version=None,*param_decls,package_name=None,prog_name=None,message=None,**kwargs)

Add a--version option which immediately prints the versionnumber and exits the program.

Ifversion is not provided, Click will try to detect it usingimportlib.metadata.version() to get the version for thepackage_name.

Ifpackage_name is not provided, Click will try to detect it byinspecting the stack frames. This will be used to detect theversion, so it must match the name of the installed package.

Parameters:
  • version (str |None) – The version number to show. If not provided, Clickwill try to detect it.

  • param_decls (str) – One or more option names. Defaults to the singlevalue"--version".

  • package_name (str |None) – The package name to detect the version from. Ifnot provided, Click will try to detect it.

  • prog_name (str |None) – The name of the CLI to show in the message. If notprovided, it will be detected from the command.

  • message (str |None) – The message to show. The values%(prog)s,%(package)s, and%(version)s are available. Defaults to"%(prog)s,version%(version)s".

  • kwargs (Any) – Extra arguments are passed tooption().

Raises:

RuntimeErrorversion could not be detected.

Return type:

Callable[[FC],FC]

Changelog

Changed in version 8.0:Add thepackage_name parameter, and the%(package)svalue for messages.

Changed in version 8.0:Useimportlib.metadata instead ofpkg_resources. Theversion is detected based on the package name, not the entrypoint name. The Python package name must match the installedpackage name, or be passed withpackage_name=.

click.help_option(*param_decls,**kwargs)

Pre-configured--help option which immediately prints the help pageand exits the program.

Parameters:
  • param_decls (str) – One or more option names. Defaults to the singlevalue"--help".

  • kwargs (Any) – Extra arguments are passed tooption().

Return type:

Callable[[FC],FC]

click.pass_context(f)

Marks a callback as wanting to receive the current contextobject as first argument.

Parameters:

f (t.Callable[te.Concatenate[Context,P],R])

Return type:

t.Callable[P, R]

click.pass_obj(f)

Similar topass_context(), but only pass the object on thecontext onwards (Context.obj). This is useful if that objectrepresents the state of a nested system.

Parameters:

f (t.Callable[te.Concatenate[T,P],R])

Return type:

t.Callable[P, R]

click.make_pass_decorator(object_type,ensure=False)

Given an object type this creates a decorator that will worksimilar topass_obj() but instead of passing the object of thecurrent context, it will find the innermost context of typeobject_type().

This generates a decorator that works roughly like this:

fromfunctoolsimportupdate_wrapperdefdecorator(f):@pass_contextdefnew_func(ctx,*args,**kwargs):obj=ctx.find_object(object_type)returnctx.invoke(f,obj,*args,**kwargs)returnupdate_wrapper(new_func,f)returndecorator
Parameters:
  • object_type (type[T]) – the type of the object to pass.

  • ensure (bool) – if set toTrue, a new object will be created andremembered on the context if it’s not there yet.

Return type:

t.Callable[[t.Callable[te.Concatenate[T, P], R]], t.Callable[P, R]]

click.decorators.pass_meta_key(key,*,doc_description=None)

Create a decorator that passes a key fromclick.Context.meta as the first argument to the decoratedfunction.

Parameters:
  • key (str) – Key inContext.meta to pass.

  • doc_description (str |None) – Description of the object being passed,inserted into the decorator’s docstring. Defaults to “the ‘key’key from Context.meta”.

Return type:

t.Callable[[t.Callable[te.Concatenate[T, P], R]], t.Callable[P, R]]

Changelog

Added in version 8.0.

Utilities

click.echo(message=None,file=None,nl=True,err=False,color=None)

Print a message and newline to stdout or a file. This should beused instead ofprint() because it provides better supportfor different data, files, and environments.

Compared toprint(), this does the following:

  • Ensures that the output encoding is not misconfigured on Linux.

  • Supports Unicode in the Windows console.

  • Supports writing to binary outputs, and supports writing bytesto text outputs.

  • Supports colors and styles on Windows.

  • Removes ANSI color and style codes if the output does not looklike an interactive terminal.

  • Always flushes the output.

Parameters:
  • message (Any |None) – The string or bytes to output. Other objects areconverted to strings.

  • file (IO[Any]|None) – The file to write to. Defaults tostdout.

  • err (bool) – Write tostderr instead ofstdout.

  • nl (bool) – Print a newline after the message. Enabled by default.

  • color (bool |None) – Force showing or hiding colors and other styles. Bydefault Click will remove color if the output does not look likean interactive terminal.

Return type:

None

Changelog

Changed in version 6.0:Support Unicode output on the Windows console. Click does notmodifysys.stdout, sosys.stdout.write() andprint()will still not support Unicode.

Changed in version 4.0:Added thecolor parameter.

Added in version 3.0:Added theerr parameter.

Changed in version 2.0:Support colors on Windows if colorama is installed.

click.echo_via_pager(text_or_generator,color=None)

This function takes a text and shows it via an environment specificpager on stdout.

Changelog

Changed in version 3.0:Added thecolor flag.

Parameters:
  • text_or_generator (Iterable[str]|Callable[[],Iterable[str]]|str) – the text to page, or alternatively, agenerator emitting the text to page.

  • color (bool |None) – controls if the pager supports ANSI colors or not. Thedefault is autodetection.

Return type:

None

click.prompt(text,default=None,hide_input=False,confirmation_prompt=False,type=None,value_proc=None,prompt_suffix=':',show_default=True,err=False,show_choices=True)

Prompts a user for input. This is a convenience function that canbe used to prompt a user for input later.

If the user aborts the input by sending an interrupt signal, thisfunction will catch it and raise aAbort exception.

Parameters:
  • text (str) – the text to show for the prompt.

  • default (Any |None) – the default value to use if no input happens. If thisis not given it will prompt until it’s aborted.

  • hide_input (bool) – if this is set to true then the input value willbe hidden.

  • confirmation_prompt (bool |str) – Prompt a second time to confirm thevalue. Can be set to a string instead ofTrue to customizethe message.

  • type (ParamType |Any |None) – the type to use to check the value against.

  • value_proc (Callable[[str],Any]|None) – if this parameter is provided it’s a function thatis invoked instead of the type conversion toconvert a value.

  • prompt_suffix (str) – a suffix that should be added to the prompt.

  • show_default (bool) – shows or hides the default value in the prompt.

  • err (bool) – if set to true the file defaults tostderr instead ofstdout, the same as with echo.

  • show_choices (bool) – Show or hide choices if the passed type is a Choice.For example if type is a Choice of either day or week,show_choices is true and text is “Group by” then theprompt will be “Group by (day, week): “.

Return type:

Any

Changed in version 8.3.1:A space is no longer appended to the prompt.

Changelog

Added in version 8.0:confirmation_prompt can be a custom string.

Added in version 7.0:Added theshow_choices parameter.

Added in version 6.0:Added unicode support for cmd.exe on Windows.

Added in version 4.0:Added theerr parameter.

click.confirm(text,default=False,abort=False,prompt_suffix=':',show_default=True,err=False)

Prompts for confirmation (yes/no question).

If the user aborts the input by sending a interrupt signal thisfunction will catch it and raise aAbort exception.

Parameters:
  • text (str) – the question to ask.

  • default (bool |None) – The default value to use when no input is given. IfNone, repeat until input is given.

  • abort (bool) – if this is set toTrue a negative answer aborts theexception by raisingAbort.

  • prompt_suffix (str) – a suffix that should be added to the prompt.

  • show_default (bool) – shows or hides the default value in the prompt.

  • err (bool) – if set to true the file defaults tostderr instead ofstdout, the same as with echo.

Return type:

bool

Changed in version 8.3.1:A space is no longer appended to the prompt.

Changelog

Changed in version 8.0:Repeat until input is given ifdefault isNone.

Added in version 4.0:Added theerr parameter.

click.progressbar(*,length:int,label:str|None=None,hidden:bool=False,show_eta:bool=True,show_percent:bool|None=None,show_pos:bool=False,fill_char:str='#',empty_char:str='-',bar_template:str='%(label)s [%(bar)s] %(info)s',info_sep:str=' ',width:int=36,file:TextIO|None=None,color:bool|None=None,update_min_steps:int=1)ProgressBar[int]
click.progressbar(iterable:Iterable[V]|None=None,length:int|None=None,label:str|None=None,hidden:bool=False,show_eta:bool=True,show_percent:bool|None=None,show_pos:bool=False,item_show_func:Callable[[V|None],str|None]|None=None,fill_char:str='#',empty_char:str='-',bar_template:str='%(label)s [%(bar)s] %(info)s',info_sep:str=' ',width:int=36,file:TextIO|None=None,color:bool|None=None,update_min_steps:int=1)ProgressBar[V]

This function creates an iterable context manager that can be usedto iterate over something while showing a progress bar. It willeither iterate over theiterable orlength items (that are countedup). While iteration happens, this function will print a renderedprogress bar to the givenfile (defaults to stdout) and will attemptto calculate remaining time and more. By default, this progress barwill not be rendered if the file is not a terminal.

The context manager creates the progress bar. When the contextmanager is entered the progress bar is already created. With everyiteration over the progress bar, the iterable passed to the bar isadvanced and the bar is updated. When the context manager exits,a newline is printed and the progress bar is finalized on screen.

Note: The progress bar is currently designed for use cases where thetotal progress can be expected to take at least several seconds.Because of this, the ProgressBar class object won’t displayprogress that is considered too fast, and progress where the timebetween steps is less than a second.

No printing must happen or the progress bar will be unintentionallydestroyed.

Example usage:

withprogressbar(items)asbar:foriteminbar:do_something_with(item)

Alternatively, if no iterable is specified, one can manually update theprogress bar through theupdate() method instead of directlyiterating over the progress bar. The update method accepts the numberof steps to increment the bar with:

withprogressbar(length=chunks.total_bytes)asbar:forchunkinchunks:process_chunk(chunk)bar.update(chunks.bytes)

Theupdate() method also takes an optional value specifying thecurrent_item at the new position. This is useful when usedtogether withitem_show_func to customize the output for eachmanual step:

withclick.progressbar(length=total_size,label='Unzipping archive',item_show_func=lambdaa:a.filename)asbar:forarchiveinzip_file:archive.extract()bar.update(archive.size,archive)
Parameters:
  • iterable – an iterable to iterate over. If not provided the lengthis required.

  • length – the number of items to iterate over. By default theprogressbar will attempt to ask the iterator about itslength, which might or might not work. If an iterable isalso provided this parameter can be used to override thelength. If an iterable is not provided the progress barwill iterate over a range of that length.

  • label – the label to show next to the progress bar.

  • hidden – hide the progressbar. Defaults toFalse. When no tty isdetected, it will only print the progressbar label. Setting this toFalse also disables that.

  • show_eta – enables or disables the estimated time display. This isautomatically disabled if the length cannot bedetermined.

  • show_percent – enables or disables the percentage display. Thedefault isTrue if the iterable has a length orFalse if not.

  • show_pos – enables or disables the absolute position display. Thedefault isFalse.

  • item_show_func – A function called with the current item whichcan return a string to show next to the progress bar. If thefunction returnsNone nothing is shown. The current item canbeNone, such as when entering and exiting the bar.

  • fill_char – the character to use to show the filled part of theprogress bar.

  • empty_char – the character to use to show the non-filled part ofthe progress bar.

  • bar_template – the format string to use as template for the bar.The parameters in it arelabel for the label,bar for the progress bar andinfo for theinfo section.

  • info_sep – the separator between multiple info items (eta etc.)

  • width – the width of the progress bar in characters, 0 means fullterminal width

  • file – The file to write to. If this is not a terminal thenonly the label is printed.

  • color – controls if the terminal supports ANSI colors or not. Thedefault is autodetection. This is only needed if ANSIcodes are included anywhere in the progress bar outputwhich is not the case by default.

  • update_min_steps – Render only when this many updates havecompleted. This allows tuning for very fast iterators.

Changelog

Added in version 8.2:Thehidden argument.

Changed in version 8.0:Output is shown even if execution time is less than 0.5 seconds.

Changed in version 8.0:item_show_func shows the current item, not the previous one.

Changed in version 8.0:Labels are echoed if the output is not a TTY. Reverts a changein 7.0 that removed all output.

Added in version 8.0:Theupdate_min_steps parameter.

Added in version 4.0:Thecolor parameter andupdate method.

Added in version 2.0.

click.clear()

Clears the terminal screen. This will have the effect of clearingthe whole visible space of the terminal and moving the cursor to thetop left. This does not do anything if not connected to a terminal.

Changelog

Added in version 2.0.

Return type:

None

click.style(text,fg=None,bg=None,bold=None,dim=None,underline=None,overline=None,italic=None,blink=None,reverse=None,strikethrough=None,reset=True)

Styles a text with ANSI styles and returns the new string. Bydefault the styling is self contained which means that at the endof the string a reset code is issued. This can be prevented bypassingreset=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'))click.echo(click.style('More colors',fg=(255,12,128),bg=117))

Supported color names:

  • black (might be a gray)

  • red

  • green

  • yellow (might be an orange)

  • blue

  • magenta

  • cyan

  • white (might be light gray)

  • bright_black

  • bright_red

  • bright_green

  • bright_yellow

  • bright_blue

  • bright_magenta

  • bright_cyan

  • bright_white

  • reset (reset the color code only)

If the terminal supports it, color may also be specified as:

  • An integer in the interval [0, 255]. The terminal must support8-bit/256-color mode.

  • An RGB tuple of three integers in [0, 255]. The terminal mustsupport 24-bit/true-color mode.

Seehttps://en.wikipedia.org/wiki/ANSI_color andhttps://gist.github.com/XVilka/8346728 for more information.

Parameters:
  • text (Any) – the string to style with ansi codes.

  • fg (int |tuple[int,int,int]|str |None) – if provided this will become the foreground color.

  • bg (int |tuple[int,int,int]|str |None) – if provided this will become the background color.

  • bold (bool |None) – if provided this will enable or disable bold mode.

  • dim (bool |None) – if provided this will enable or disable dim mode. This isbadly supported.

  • underline (bool |None) – if provided this will enable or disable underline.

  • overline (bool |None) – if provided this will enable or disable overline.

  • italic (bool |None) – if provided this will enable or disable italic.

  • blink (bool |None) – if provided this will enable or disable blinking.

  • reverse (bool |None) – if provided this will enable or disable inverserendering (foreground becomes background and theother way round).

  • strikethrough (bool |None) – if provided this will enable or disablestriking through text.

  • reset (bool) – by default a reset-all code is added at the end of thestring which means that styles do not carry over. Thiscan be disabled to compose styles.

Return type:

str

Changelog

Changed in version 8.0:A non-stringmessage is converted to a string.

Changed in version 8.0:Added support for 256 and RGB color codes.

Changed in version 8.0:Added thestrikethrough,italic, andoverlineparameters.

Changed in version 7.0:Added support for bright colors.

Added in version 2.0.

click.unstyle(text)

Removes ANSI styling information from a string. Usually it’s notnecessary to use this function as Click’s echo function willautomatically remove styling if necessary.

Changelog

Added in version 2.0.

Parameters:

text (str) – the text to remove style information from.

Return type:

str

click.secho(message=None,file=None,nl=True,err=False,color=None,**styles)

This function combinesecho() andstyle() into onecall. 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 functionsdepending on which one they go with.

Non-string types will be converted tostr. However,bytes are passed directly toecho() without applyingstyle. If you want to style bytes that represent text, callbytes.decode() first.

Changelog

Changed in version 8.0:A non-stringmessage is converted to a string. Bytes arepassed through without style applied.

Added in version 2.0.

Parameters:
Return type:

None

click.edit(text:bytes|bytearray,editor:str|None=None,env:Mapping[str,str]|None=None,require_save:bool=False,extension:str='.txt')bytes|None
click.edit(text:str,editor:str|None=None,env:Mapping[str,str]|None=None,require_save:bool=True,extension:str='.txt')str|None
click.edit(text:None=None,editor:str|None=None,env:Mapping[str,str]|None=None,require_save:bool=True,extension:str='.txt',filename:str|Iterable[str]|None=None)None

Edits the given text in the defined editor. If an editor is given(should be the full path to the executable but the regular operatingsystem search path is used for finding the executable) it overridesthe detected editor. Optionally, some environment variables can beused. If the editor is closed without changes,None is returned. Incase a file is edited directly the return value is alwaysNone andrequire_save andextension are ignored.

If the editor cannot be opened aUsageError is raised.

Note for Windows: to simplify cross-platform usage, the newlines areautomatically converted from POSIX to Windows and vice versa. As such,the message here will have\n as newline markers.

Parameters:
  • text – the text to edit.

  • editor – optionally the editor to use. Defaults to automaticdetection.

  • env – environment variables to forward to the editor.

  • require_save – if this is true, then not saving in the editorwill make the return value becomeNone.

  • extension – the extension to tell the editor about. This defaultsto.txt but changing this might change syntaxhighlighting.

  • filename – if provided it will edit this file instead of theprovided text contents. It will not use a temporaryfile as an indirection in that case. If the editor supportsediting multiple files at once, a sequence of files may bepassed as well. Invokeclick.file once per file insteadif multiple files cannot be managed at once or editing thefiles serially is desired.

Changelog

Changed in version 8.2.0:filename now accepts anyIterable[str] in addition to astrif theeditor supports editing multiple files at once.

click.launch(url,wait=False,locate=False)

This function launches the given URL (or filename) in the defaultviewer application for this file type. If this is an executable, itmight launch the executable in a new session. The return value isthe exit code of the launched application. Usually,0 indicatessuccess.

Examples:

click.launch('https://click.palletsprojects.com/')click.launch('/my/downloaded/file',locate=True)
Changelog

Added in version 2.0.

Parameters:
  • url (str) – URL or filename of the thing to launch.

  • wait (bool) – Wait for the program to exit before returning. Thisonly works if the launched program blocks. In particular,xdg-open on Linux does not block.

  • locate (bool) – if this is set toTrue then instead of launching theapplication associated with the URL it will attempt tolaunch a file manager with the file located. Thismight have weird effects if the URL does not point tothe filesystem.

Return type:

int

click.getchar(echo=False)

Fetches a single character from the terminal and returns it. Thiswill always return a unicode character and under certain rarecircumstances this might return more than one character. Thesituations which more than one character is returned is when forwhatever reason multiple characters end up in the terminal buffer orstandard input was not actually a terminal.

Note that this will always read from the terminal, even if somethingis piped into the standard input.

Note for Windows: in rare cases when typing non-ASCII characters, thisfunction might wait for a second character and then return both at once.This is because certain Unicode characters look like special-key markers.

Changelog

Added in version 2.0.

Parameters:

echo (bool) – if set toTrue, the character read will also show up onthe terminal. The default is to not show it.

Return type:

str

click.pause(info=None,err=False)

This command stops execution and waits for the user to press anykey to continue. This is similar to the Windows batch “pause”command. If the program is not run through a terminal, this commandwill instead do nothing.

Changelog

Added in version 4.0:Added theerr parameter.

Added in version 2.0.

Parameters:
  • info (str |None) – The message to print before pausing. Defaults to"Pressanykeytocontinue...".

  • err (bool) – if set to message goes tostderr instead ofstdout, the same as with echo.

Return type:

None

click.get_binary_stream(name)

Returns a system stream for byte processing.

Parameters:

name (Literal['stdin','stdout','stderr']) – the name of the stream to open. Valid names are'stdin','stdout' and'stderr'

Return type:

BinaryIO

click.get_text_stream(name,encoding=None,errors='strict')

Returns a system stream for text processing. This usually returnsa wrapped stream around a binary stream returned fromget_binary_stream() but it also can take shortcuts for alreadycorrectly configured streams.

Parameters:
  • name (Literal['stdin','stdout','stderr']) – the name of the stream to open. Valid names are'stdin','stdout' and'stderr'

  • encoding (str |None) – overrides the detected default encoding.

  • errors (str |None) – overrides the default error mode.

Return type:

TextIO

click.open_file(filename,mode='r',encoding=None,errors='strict',lazy=False,atomic=False)

Open a file, with extra behavior to handle'-' to indicatea standard stream, lazy open on write, and atomic write. Similar tothe behavior of theFile param type.

If'-' is given to openstdout orstdin, the stream iswrapped so that using it in a context manager will not close it.This makes it possible to use the function without accidentallyclosing a standard stream:

withopen_file(filename)asf:...
Parameters:
  • filename (str |PathLike[str]) – The name or Path of the file to open, or'-' forstdin/stdout.

  • mode (str) – The mode in which to open the file.

  • encoding (str |None) – The encoding to decode or encode a file opened intext mode.

  • errors (str |None) – The error handling mode.

  • lazy (bool) – Wait to open the file until it is accessed. For readmode, the file is temporarily opened to raise access errorsearly, then closed until it is read again.

  • atomic (bool) – Write to a temporary file and replace the given fileon close.

Return type:

IO[Any]

Changelog

Added in version 3.0.

click.get_app_dir(app_name,roaming=True,force_posix=False)

Returns the config folder for the application. The default behavioris to return whatever is most appropriate for the operating system.

To give you an idea, for an app called"FooBar", something likethe following folders could be returned:

Mac OS X:

~/Library/ApplicationSupport/FooBar

Mac OS X (POSIX):

~/.foo-bar

Unix:

~/.config/foo-bar

Unix (POSIX):

~/.foo-bar

Windows (roaming):

C:\Users\<user>\AppData\Roaming\FooBar

Windows (not roaming):

C:\Users\<user>\AppData\Local\FooBar

Changelog

Added in version 2.0.

Parameters:
  • app_name (str) – the application name. This should be properly capitalizedand can contain whitespace.

  • roaming (bool) – controls if the folder should be roaming or not on Windows.Has no effect otherwise.

  • force_posix (bool) – if this is set toTrue then on any POSIX system thefolder will be stored in the home folder with a leadingdot instead of the XDG config home or darwin’sapplication support folder.

Return type:

str

click.format_filename(filename,shorten=False)

Format a filename as a string for display. Ensures the filename can bedisplayed by replacing any invalid bytes or surrogate escapes in the namewith the replacement character.

Invalid bytes or surrogate escapes will raise an error when written to astream witherrors="strict". This will typically happen withstdoutwhen the locale is something likeen_GB.UTF-8.

Many scenariosare safe to write surrogates though, due to PEP 538 andPEP 540, including:

  • Writing tostderr, which useserrors="backslashreplace".

  • The system hasLANG=C.UTF-8,C, orPOSIX. Python opensstdout and stderr witherrors="surrogateescape".

  • None ofLANG/LC_* are set. Python assumesLANG=C.UTF-8.

  • Python is started in UTF-8 mode withPYTHONUTF8=1 or-Xutf8.Python opens stdout and stderr witherrors="surrogateescape".

Parameters:
  • filename (str |bytes |PathLike[str]|PathLike[bytes]) – formats a filename for UI display. This will also convertthe filename into unicode without failing.

  • shorten (bool) – this optionally shortens the filename to strip of thepath that leads up to it.

Return type:

str

Commands

click.BaseCommand

alias of_BaseCommand

classclick.Command(name,context_settings=None,callback=None,params=None,help=None,epilog=None,short_help=None,options_metavar='[OPTIONS]',add_help_option=True,no_args_is_help=False,hidden=False,deprecated=False)

Commands are the basic building block of command line interfaces inClick. A basic command handles command line parsing and might dispatchmore parsing to commands nested below it.

Parameters:
  • name (str |None) – the name of the command to use unless a group overrides it.

  • context_settings (cabc.MutableMapping[str,t.Any]|None) – an optional dictionary with defaults that arepassed to the context object.

  • callback (t.Callable[...,t.Any]|None) – the callback to invoke. This is optional.

  • params (list[Parameter]|None) – the parameters to register with this command. This canbe eitherOption orArgument objects.

  • help (str |None) – the help string to use for this command.

  • epilog (str |None) – like the help string but it’s printed at the end of thehelp page after everything else.

  • short_help (str |None) – the short help to use for this command. This isshown on the command listing of the parent command.

  • add_help_option (bool) – by default each command registers a--helpoption. This can be disabled by this parameter.

  • no_args_is_help (bool) – this controls what happens if no arguments areprovided. This option is disabled by default.If enabled this will add--help as argumentif no arguments are passed

  • hidden (bool) – hide this command from help outputs.

  • deprecated (bool |str) – IfTrue or non-empty string, issues a messageindicating that the command is deprecated and highlightsits deprecation in –help. The message can be customizedby using a string as the value.

  • options_metavar (str |None)

Changelog

Changed in version 8.2:This is the base class for all commands, notBaseCommand.deprecated can be set to a string as well to customize thedeprecation message.

Changed in version 8.1:help,epilog, andshort_help are stored unprocessed,all formatting is done when outputting help text, not at init,and is done even if not using the@command decorator.

Changed in version 8.0:Added arepr showing the command name.

Changed in version 7.1:Added theno_args_is_help parameter.

Changed in version 2.0:Added thecontext_settings parameter.

context_class

alias ofContext

allow_extra_args=False

the default for theContext.allow_extra_args flag.

allow_interspersed_args=True

the default for theContext.allow_interspersed_args flag.

ignore_unknown_options=False

the default for theContext.ignore_unknown_options flag.

name

the name the command thinks it has. Upon registering a commandon aGroup the group will default the command namewith this information. You should instead use theContext'sinfo_name attribute.

context_settings:MutableMapping[str,Any]

an optional dictionary with defaults passed to the context.

callback

the callback to execute when the command fires. This might beNone in which case nothing happens.

params:list[Parameter]

the list of parameters for this command in the order theyshould show up in the help page and execute. Eager parameterswill automatically be handled before non eager ones.

get_usage(ctx)

Formats the usage line into a string and returns it.

Callsformat_usage() internally.

Parameters:

ctx (Context)

Return type:

str

format_usage(ctx,formatter)

Writes the usage line into the formatter.

This is a low-level method called byget_usage().

Parameters:
Return type:

None

collect_usage_pieces(ctx)

Returns all the pieces that go into the usage line and returnsit as a list of strings.

Parameters:

ctx (Context)

Return type:

list[str]

get_help_option_names(ctx)

Returns the names for the help option.

Parameters:

ctx (Context)

Return type:

list[str]

get_help_option(ctx)

Returns the help option object.

Skipped ifadd_help_option isFalse.

Changelog

Changed in version 8.1.8:The help option is now cached to avoid creating it multiple times.

Parameters:

ctx (Context)

Return type:

Option | None

make_parser(ctx)

Creates the underlying option parser for this command.

Parameters:

ctx (Context)

Return type:

_OptionParser

get_help(ctx)

Formats the help into a string and returns it.

Callsformat_help() internally.

Parameters:

ctx (Context)

Return type:

str

get_short_help_str(limit=45)

Gets short help for the command or makes it by shortening thelong help string.

Parameters:

limit (int)

Return type:

str

format_help(ctx,formatter)

Writes the help into the formatter if it exists.

This is a low-level method called byget_help().

This calls the following methods:

Parameters:
Return type:

None

format_help_text(ctx,formatter)

Writes the help text to the formatter if it exists.

Parameters:
Return type:

None

format_options(ctx,formatter)

Writes all the options into the formatter if they exist.

Parameters:
Return type:

None

format_epilog(ctx,formatter)

Writes the epilog into the formatter if it exists.

Parameters:
Return type:

None

make_context(info_name,args,parent=None,**extra)

This function when given an info name and arguments will kickoff the parsing and create a newContext. It does notinvoke the actual command callback though.

To quickly customize the context class used without overridingthis method, set thecontext_class attribute.

Parameters:
  • info_name (str |None) – the info name for this invocation. Generally thisis the most descriptive name for the script orcommand. For the toplevel script it’s usuallythe name of the script, for commands below it’sthe name of the command.

  • args (list[str]) – the arguments to parse as list of strings.

  • parent (Context |None) – the parent context if available.

  • extra (Any) – extra keyword arguments forwarded to the contextconstructor.

Return type:

Context

Changelog

Changed in version 8.0:Added thecontext_class attribute.

invoke(ctx)

Given a context, this invokes the attached callback (if it exists)in the right way.

Parameters:

ctx (Context)

Return type:

Any

shell_complete(ctx,incomplete)

Return a list of completions for the incomplete value. Looksat the names of options and chained multi-commands.

Any command could be part of a chained multi-command, so siblingcommands are valid at any point during command completion.

Parameters:
  • ctx (Context) – Invocation context for this command.

  • incomplete (str) – Value being completed. May be empty.

Return type:

list[CompletionItem]

Changelog

Added in version 8.0.

main(args:Sequence[str]|None=None,prog_name:str|None=None,complete_var:str|None=None,standalone_mode:Literal[True]=True,**extra:Any)NoReturn
main(args:Sequence[str]|None=None,prog_name:str|None=None,complete_var:str|None=None,standalone_mode:bool=True,**extra:Any)Any

This is the way to invoke a script with all the bells andwhistles as a command line application. This will always terminatethe application after a call. If this is not wanted,SystemExitneeds to be caught.

This method is also available by directly calling the instance ofaCommand.

Parameters:
  • args – the arguments that should be used for parsing. If notprovided,sys.argv[1:] is used.

  • prog_name – the program name that should be used. By defaultthe program name is constructed by taking the filename fromsys.argv[0].

  • complete_var – the environment variable that controls thebash completion support. The default is"_<prog_name>_COMPLETE" with prog_name inuppercase.

  • standalone_mode – the default behavior is to invoke the scriptin standalone mode. Click will thenhandle exceptions and convert them intoerror messages and the function will neverreturn but shut down the interpreter. Ifthis is set toFalse they will bepropagated to the caller and the returnvalue of this function is the return valueofinvoke().

  • windows_expand_args – Expand glob patterns, user dir, andenv vars in command line args on Windows.

  • extra – extra keyword arguments are forwarded to the contextconstructor. SeeContext for more information.

Changelog

Changed in version 8.0.1:Added thewindows_expand_args parameter to allowdisabling command line arg expansion on Windows.

Changed in version 8.0:When taking arguments fromsys.argv on Windows, globpatterns, user dir, and env vars are expanded.

Changed in version 3.0:Added thestandalone_mode parameter.

click.MultiCommand

alias of_MultiCommand

classclick.Group(name=None,commands=None,invoke_without_command=False,no_args_is_help=None,subcommand_metavar=None,chain=False,result_callback=None,**kwargs)

A group is a command that nests other commands (or more groups).

Parameters:
  • name (str |None) – The name of the group command.

  • commands (cabc.MutableMapping[str,Command]|cabc.Sequence[Command]|None) – Map names toCommand objects. Can be a list, whichwill useCommand.name as the keys.

  • invoke_without_command (bool) – Invoke the group’s callback even if asubcommand is not given.

  • no_args_is_help (bool |None) – If no arguments are given, show the group’s help andexit. Defaults to the opposite ofinvoke_without_command.

  • subcommand_metavar (str |None) – How to represent the subcommand argument in help.The default will represent whetherchain is set or not.

  • chain (bool) – Allow passing more than one subcommand argument. After parsinga command’s arguments, if any arguments remain another command will bematched, and so on.

  • result_callback (t.Callable[...,t.Any]|None) – A function to call after the group’s andsubcommand’s callbacks. The value returned by the subcommand is passed.Ifchain is enabled, the value will be a list of values returned byall the commands. Ifinvoke_without_command is enabled, the valuewill be the value returned by the group’s callback, or an empty list ifchain is enabled.

  • kwargs (t.Any) – Other arguments passed toCommand.

Changelog

Changed in version 8.2:Merged with and replaces theMultiCommand base class.

Changed in version 8.0:Thecommands argument can be a list of command objects.

allow_extra_args=True

the default for theContext.allow_extra_args flag.

allow_interspersed_args=False

the default for theContext.allow_interspersed_args flag.

command_class:type[Command]|None=None

If set, this is used by the group’scommand() decoratoras the defaultCommand class. This is useful to make allsubcommands use a custom command class.

Changelog

Added in version 8.0.

group_class:type[Group]|type[type]|None=None

If set, this is used by the group’sgroup() decoratoras the defaultGroup class. This is useful to make allsubgroups use a custom group class.

If set to the special valuetype (literallygroup_class=type), this group’s class will be used as thedefault class. This makes a custom group class continue to makecustom groups.

Changelog

Added in version 8.0.

commands:MutableMapping[str,Command]

The registered subcommands by their exported names.

add_command(cmd,name=None)

Registers anotherCommand with this group. If the nameis not provided, the name of the command is used.

Parameters:
Return type:

None

command(__func:Callable[[...],Any])Command
command(*args:Any,**kwargs:Any)Callable[[Callable[[...],Any]],Command]

A shortcut decorator for declaring and attaching a command tothe group. This takes the same arguments ascommand() andimmediately registers the created command with this group bycallingadd_command().

To customize the command class used, set thecommand_class attribute.

Changelog

Changed in version 8.1:This decorator can be applied without parentheses.

Changed in version 8.0:Added thecommand_class attribute.

group(__func:Callable[[...],Any])Group
group(*args:Any,**kwargs:Any)Callable[[Callable[[...],Any]],Group]

A shortcut decorator for declaring and attaching a group tothe group. This takes the same arguments asgroup() andimmediately registers the created group with this group bycallingadd_command().

To customize the group class used, set thegroup_classattribute.

Changelog

Changed in version 8.1:This decorator can be applied without parentheses.

Changed in version 8.0:Added thegroup_class attribute.

result_callback(replace=False)

Adds a result callback to the command. By default if aresult callback is already registered this will chain them butthis can be disabled with thereplace parameter. The resultcallback is invoked with the return value of the subcommand(or the list of return values from all subcommands if chainingis enabled) as well as the parameters as they would be passedto the main callback.

Example:

@click.group()@click.option('-i','--input',default=23)defcli(input):return42@cli.result_callback()defprocess_result(result,input):returnresult+input
Parameters:

replace (bool) – if set toTrue an already existing resultcallback will be removed.

Return type:

Callable[[F],F]

Changelog

Changed in version 8.0:Renamed fromresultcallback.

Added in version 3.0.

get_command(ctx,cmd_name)

Given a context and a command name, this returns aCommandobject if it exists or returnsNone.

Parameters:
Return type:

Command | None

list_commands(ctx)

Returns a list of subcommand names in the order they should appear.

Parameters:

ctx (Context)

Return type:

list[str]

collect_usage_pieces(ctx)

Returns all the pieces that go into the usage line and returnsit as a list of strings.

Parameters:

ctx (Context)

Return type:

list[str]

format_options(ctx,formatter)

Writes all the options into the formatter if they exist.

Parameters:
Return type:

None

format_commands(ctx,formatter)

Extra format methods for multi methods that adds all the commandsafter the options.

Parameters:
Return type:

None

invoke(ctx)

Given a context, this invokes the attached callback (if it exists)in the right way.

Parameters:

ctx (Context)

Return type:

Any

shell_complete(ctx,incomplete)

Return a list of completions for the incomplete value. Looksat the names of options, subcommands, and chainedmulti-commands.

Parameters:
  • ctx (Context) – Invocation context for this command.

  • incomplete (str) – Value being completed. May be empty.

Return type:

list[CompletionItem]

Changelog

Added in version 8.0.

classclick.CommandCollection(name=None,sources=None,**kwargs)

AGroup that looks up subcommands on other groups. If a commandis not found on this group, each registered source is checked in order.Parameters on a source are not added to this group, and a source’s callbackis not invoked when invoking its commands. In other words, this “flattens”commands in many groups into this one group.

Parameters:
  • name (str |None) – The name of the group command.

  • sources (list[Group]|None) – A list ofGroup objects to look up commands from.

  • kwargs (t.Any) – Other arguments passed toGroup.

Changelog

Changed in version 8.2:This is a subclass ofGroup. Commands are looked up first on thisgroup, then each of its sources.

sources:list[Group]

The list of registered groups.

add_source(group)

Add a group as a source of commands.

Parameters:

group (Group)

Return type:

None

get_command(ctx,cmd_name)

Given a context and a command name, this returns aCommandobject if it exists or returnsNone.

Parameters:
Return type:

Command | None

list_commands(ctx)

Returns a list of subcommand names in the order they should appear.

Parameters:

ctx (Context)

Return type:

list[str]

Parameters

classclick.Parameter(param_decls=None,type=None,required=False,default=UNSET,callback=None,nargs=None,multiple=False,metavar=None,expose_value=True,is_eager=False,envvar=None,shell_complete=None,deprecated=False)

A parameter to a command comes in two versions: they are eitherOptions orArguments. Other subclasses are currentlynot supported by design as some of the internals for parsing areintentionally not finalized.

Some settings are supported by both options and arguments.

Parameters:
  • param_decls (cabc.Sequence[str]|None) – the parameter declarations for this option orargument. This is a list of flags or argumentnames.

  • type (types.ParamType |t.Any |None) – the type that should be used. Either aParamTypeor a Python type. The latter is converted into the formerautomatically if supported.

  • required (bool) – controls if this is optional or not.

  • default (t.Any |t.Callable[[],t.Any]|None) – the default value if omitted. This can also be a callable,in which case it’s invoked when the default is neededwithout any arguments.

  • callback (t.Callable[[Context,Parameter,t.Any],t.Any]|None) – A function to further process or validate the valueafter type conversion. It is called asf(ctx,param,value)and must return the value. It is called for all sources,including prompts.

  • nargs (int |None) – the number of arguments to match. If not1 the returnvalue is a tuple instead of single value. The default fornargs is1 (except if the type is a tuple, then it’sthe arity of the tuple). Ifnargs=-1, all remainingparameters are collected.

  • metavar (str |None) – how the value is represented in the help page.

  • expose_value (bool) – if this isTrue then the value is passed onwardsto the command callback and stored on the context,otherwise it’s skipped.

  • is_eager (bool) – eager values are processed before non eager ones. Thisshould not be set for arguments or it will inverse theorder of processing.

  • envvar (str |cabc.Sequence[str]|None) – environment variable(s) that are used to provide a default value forthis parameter. This can be a string or a sequence of strings. If a sequence isgiven, only the first non-empty environment variable is used for the parameter.

  • shell_complete (t.Callable[[Context,Parameter,str],list[CompletionItem]|list[str]]|None) – A function that returns custom shellcompletions. Used instead of the param’s type completion ifgiven. Takesctx,param,incomplete and must return a listofCompletionItem or a list ofstrings.

  • deprecated (bool |str) – IfTrue or non-empty string, issues a messageindicating that the argument is deprecated and highlightsits deprecation in –help. The message can be customizedby using a string as the value. A deprecated parametercannot be required, a ValueError will be raised otherwise.

  • multiple (bool)

Changelog

Changed in version 8.2.0:Introduction ofdeprecated.

Changed in version 8.2:Adding duplicate parameter names to aCommand willresult in aUserWarning being shown.

Changed in version 8.2:Adding duplicate parameter names to aCommand willresult in aUserWarning being shown.

Changed in version 8.0:process_value validates required parameters and boundednargs, and invokes the parameter callback before returningthe value. This allows the callback to validate prompts.full_process_value is removed.

Changed in version 8.0:autocompletion is renamed toshell_complete and has newsemantics described above. The old name is deprecated and willbe removed in 8.1, until then it will be wrapped to match thenew requirements.

Changed in version 8.0:Formultiple=True,nargs>1, the default must be a list oftuples.

Changed in version 8.0:Setting a default is no longer required fornargs>1, it willdefault toNone.multiple=True ornargs=-1 willdefault to().

Changed in version 7.1:Empty environment variables are ignored rather than taking theempty string value. This makes it possible for scripts to clearvariables if they can’t unset them.

Changed in version 2.0:Changed signature for parameter callback to also be passed theparameter. The old callback format will still work, but it willraise a warning to give you a chance to migrate the code easier.

to_info_dict()

Gather information that could be useful for a tool generatinguser-facing documentation.

Useclick.Context.to_info_dict() to traverse the entireCLI structure.

Changed in version 8.3.0:ReturnsNone for thedefault if it was not set.

Changelog

Added in version 8.0.

Return type:

dict[str,Any]

propertyhuman_readable_name:str

Returns the human readable name of this parameter. This is thesame as the name for options, but the metavar for arguments.

get_default(ctx:Context,call:Literal[True]=True)Any|None
get_default(ctx:Context,call:bool=True)Any|Callable[[],Any]|None

Get the default for the parameter. TriesContext.lookup_default() first, then the local default.

Parameters:
  • ctx – Current context.

  • call – If the default is a callable, call it. Disable toreturn the callable instead.

Changelog

Changed in version 8.0.2:Type casting is no longer performed when getting a default.

Changed in version 8.0.1:Type casting can fail in resilient parsing mode. Invaliddefaults will not prevent showing help text.

Changed in version 8.0:Looks atctx.default_map first.

Changed in version 8.0:Added thecall parameter.

type_cast_value(ctx,value)

Convert and validate a value against the parameter’stype,multiple, andnargs.

Parameters:
Return type:

Any

get_error_hint(ctx)

Get a stringified version of the param for use in error messages toindicate which param caused the error.

Parameters:

ctx (Context)

Return type:

str

shell_complete(ctx,incomplete)

Return a list of completions for the incomplete value. If ashell_complete function was given during init, it is used.Otherwise, thetypeshell_complete() function is used.

Parameters:
  • ctx (Context) – Invocation context for this command.

  • incomplete (str) – Value being completed. May be empty.

Return type:

list[CompletionItem]

Changelog

Added in version 8.0.

classclick.Option(param_decls=None,show_default=None,prompt=False,confirmation_prompt=False,prompt_required=True,hide_input=False,is_flag=None,flag_value=UNSET,multiple=False,count=False,allow_from_autoenv=True,type=None,help=None,hidden=False,show_choices=True,show_envvar=False,deprecated=False,**attrs)

Options are usually optional values on the command line andhave some extra features that arguments don’t have.

All other parameters are passed onwards to the parameter constructor.

Parameters:
  • show_default (bool |str |None) – Show the default value for this option in itshelp text. Values are not shown by default, unlessContext.show_default isTrue. If this value is astring, it shows that string in parentheses instead of theactual value. This is particularly useful for dynamic options.For single option boolean flags, the default remains hidden ifits value isFalse.

  • show_envvar (bool) – Controls if an environment variable should beshown on the help page and error messages.Normally, environment variables are not shown.

  • prompt (bool |str) – If set toTrue or a non empty string then theuser will be prompted for input. If set toTrue the promptwill be the option name capitalized. A deprecated option cannot beprompted.

  • confirmation_prompt (bool |str) – Prompt a second time to confirm thevalue if it was prompted for. Can be set to a string instead ofTrue to customize the message.

  • prompt_required (bool) – If set toFalse, the user will beprompted for input only when the option was specified as a flagwithout a value.

  • hide_input (bool) – If this isTrue then the input on the promptwill be hidden from the user. This is useful for password input.

  • is_flag (bool |None) – forces this option to act as a flag. The default isauto detection.

  • flag_value (t.Any) – which value should be used for this flag if it’senabled. This is set to a boolean automatically ifthe option string contains a slash to mark two options.

  • multiple (bool) – if this is set toTrue then the argument is acceptedmultiple times and recorded. This is similar tonargsin how it works but supports arbitrary number ofarguments.

  • count (bool) – this flag makes an option increment an integer.

  • allow_from_autoenv (bool) – if this is enabled then the value of thisparameter will be pulled from an environmentvariable in case a prefix is defined on thecontext.

  • help (str |None) – the help string.

  • hidden (bool) – hide this option from help outputs.

  • attrs (t.Any) – Other command arguments described inParameter.

  • param_decls (cabc.Sequence[str]|None)

  • type (types.ParamType |t.Any |None)

  • show_choices (bool)

  • deprecated (bool |str)

Changelog

Changed in version 8.2:envvar used withflag_value will always use theflag_value,previously it would use the value of the environment variable.

Changed in version 8.1:Help text indentation is cleaned here instead of only in the@option decorator.

Changed in version 8.1:Theshow_default parameter overridesContext.show_default.

Changed in version 8.1:The default of a single option boolean flag is not shown if thedefault value isFalse.

Changed in version 8.0.1:type is detected fromflag_value if given.

classclick.Argument(param_decls,required=None,**attrs)

Arguments are positional parameters to a command. They generallyprovide fewer features than options but can have infinitenargsand are required by default.

All parameters are passed onwards to the constructor ofParameter.

Parameters:
  • param_decls (cabc.Sequence[str])

  • required (bool |None)

  • attrs (t.Any)

Context

classclick.Context(command,parent=None,info_name=None,obj=None,auto_envvar_prefix=None,default_map=None,terminal_width=None,max_content_width=None,resilient_parsing=False,allow_extra_args=None,allow_interspersed_args=None,ignore_unknown_options=None,help_option_names=None,token_normalize_func=None,color=None,show_default=None)

The context is a special internal object that holds state relevantfor the script execution at every single level. It’s normally invisibleto commands unless they opt-in to getting access to it.

The context is useful as it can pass internal objects around and cancontrol special execution features such as reading data fromenvironment variables.

A context can be used as context manager in which case it will callclose() on teardown.

Parameters:
  • command (Command) – the command class for this context.

  • parent (Context |None) – the parent context.

  • info_name (str |None) – the info name for this invocation. Generally thisis the most descriptive name for the script orcommand. For the toplevel script it is usuallythe name of the script, for commands below it it’sthe name of the script.

  • obj (t.Any |None) – an arbitrary object of user data.

  • auto_envvar_prefix (str |None) – the prefix to use for automatic environmentvariables. If this isNone then readingfrom environment variables is disabled. Thisdoes not affect manually set environmentvariables which are always read.

  • default_map (cabc.MutableMapping[str,t.Any]|None) – a dictionary (like object) with default valuesfor parameters.

  • terminal_width (int |None) – the width of the terminal. The default isinherit from parent context. If no contextdefines the terminal width then autodetection will be applied.

  • max_content_width (int |None) – the maximum width for content rendered byClick (this currently only affects helppages). This defaults to 80 characters ifnot overridden. In other words: even if theterminal is larger than that, Click will notformat things wider than 80 characters bydefault. In addition to that, formatters mightadd some safety mapping on the right.

  • resilient_parsing (bool) – if this flag is enabled then Click willparse without any interactivity or callbackinvocation. Default values will also beignored. This is useful for implementingthings such as completion support.

  • allow_extra_args (bool |None) – if this is set toTrue then extra argumentsat the end will not raise an error and will bekept on the context. The default is to inheritfrom the command.

  • allow_interspersed_args (bool |None) – if this is set toFalse then optionsand arguments cannot be mixed. Thedefault is to inherit from the command.

  • ignore_unknown_options (bool |None) – instructs click to ignore options it doesnot know and keeps them for laterprocessing.

  • help_option_names (list[str]|None) – optionally a list of strings that define howthe default help parameter is named. Thedefault is['--help'].

  • token_normalize_func (t.Callable[[str],str]|None) – an optional function that is used tonormalize tokens (options, choices,etc.). This for instance can be used toimplement case insensitive behavior.

  • color (bool |None) – controls if the terminal supports ANSI colors or not. Thedefault is autodetection. This is only needed if ANSIcodes are used in texts that Click prints which is bydefault not the case. This for instance would affecthelp output.

  • show_default (bool |None) – Show the default value for commands. If thisvalue is not set, it defaults to the value from the parentcontext.Command.show_default overrides this default for thespecific command.

Changelog

Changed in version 8.2:Theprotected_args attribute is deprecated and will be removed inClick 9.0.args will contain remaining unparsed tokens.

Changed in version 8.1:Theshow_default parameter is overridden byCommand.show_default, instead of the other way around.

Changed in version 8.0:Theshow_default parameter defaults to the value from theparent context.

Changed in version 7.1:Added theshow_default parameter.

Changed in version 4.0:Added thecolor,ignore_unknown_options, andmax_content_width parameters.

Changed in version 3.0:Added theallow_extra_args andallow_interspersed_argsparameters.

Changed in version 2.0:Added theresilient_parsing,help_option_names, andtoken_normalize_func parameters.

formatter_class

alias ofHelpFormatter

parent

the parent context orNone if none exists.

command

theCommand for this context.

info_name

the descriptive information name

params:dict[str,Any]

Map of parameter names to their parsed values. Parameterswithexpose_value=False are not stored.

args:list[str]

the leftover arguments.

obj:Any

the user object stored.

invoked_subcommand:str|None

This flag indicates if a subcommand is going to be executed. Agroup callback can use this information to figure out if it’sbeing executed directly or because the execution flow passesonwards to a subcommand. By default it’s None, but it can bethe name of the subcommand to execute.

If chaining is enabled this will be set to'*' in caseany commands are executed. It is however not possible tofigure out which ones. If you require this knowledge youshould use aresult_callback().

terminal_width:int|None

The width of the terminal (None is autodetection).

max_content_width:int|None

The maximum width of formatted content (None implies a sensibledefault which is 80 for most things).

allow_extra_args

Indicates if the context allows extra args or if it shouldfail on parsing.

Changelog

Added in version 3.0.

allow_interspersed_args:bool

Indicates if the context allows mixing of arguments andoptions or not.

Changelog

Added in version 3.0.

ignore_unknown_options:bool

Instructs click to ignore options that a command does notunderstand and will store it on the context for laterprocessing. This is primarily useful for situations where youwant to call into external programs. Generally this pattern isstrongly discouraged because it’s not possibly to losslesslyforward all arguments.

Changelog

Added in version 4.0.

help_option_names:list[str]

The names for the help options.

token_normalize_func:Callable[[str],str]|None

An optional normalization function for tokens. This isoptions, choices, commands etc.

resilient_parsing:bool

Indicates if resilient parsing is enabled. In that case Clickwill do its best to not cause any failures and default valueswill be ignored. Useful for completion.

color:bool|None

Controls if styling output is wanted or not.

show_default:bool|None

Show option default values when formatting help text.

to_info_dict()

Gather information that could be useful for a tool generatinguser-facing documentation. This traverses the entire CLIstructure.

withContext(cli)asctx:info=ctx.to_info_dict()
Changelog

Added in version 8.0.

Return type:

dict[str,Any]

scope(cleanup=True)

This helper method can be used with the context object to promoteit to the current thread local (seeget_current_context()).The default behavior of this is to invoke the cleanup functions whichcan be disabled by settingcleanup toFalse. The cleanupfunctions are typically used for things such as closing file handles.

If the cleanup is intended the context object can also be directlyused as a context manager.

Example usage:

withctx.scope():assertget_current_context()isctx

This is equivalent:

withctx:assertget_current_context()isctx
Changelog

Added in version 5.0.

Parameters:

cleanup (bool) – controls if the cleanup functions should be run ornot. The default is to run these functions. Insome situations the context only wants to betemporarily pushed in which case this can be disabled.Nested pushes automatically defer the cleanup.

Return type:

Iterator[Context]

propertymeta:dict[str,Any]

This is a dictionary which is shared with all the contextsthat are nested. It exists so that click utilities can store somestate here if they need to. It is however the responsibility ofthat code to manage this dictionary well.

The keys are supposed to be unique dotted strings. For instancemodule paths are a good choice for it. What is stored in there isirrelevant for the operation of click. However what is important isthat code that places data here adheres to the general semantics ofthe system.

Example usage:

LANG_KEY=f'{__name__}.lang'defset_language(value):ctx=get_current_context()ctx.meta[LANG_KEY]=valuedefget_language():returnget_current_context().meta.get(LANG_KEY,'en_US')
Changelog

Added in version 5.0.

make_formatter()

Creates theHelpFormatter for the help andusage output.

To quickly customize the formatter class used without overridingthis method, set theformatter_class attribute.

Changelog

Changed in version 8.0:Added theformatter_class attribute.

Return type:

HelpFormatter

with_resource(context_manager)

Register a resource as if it were used in awithstatement. The resource will be cleaned up when the context ispopped.

Usescontextlib.ExitStack.enter_context(). It calls theresource’s__enter__() method and returns the result. Whenthe context is popped, it closes the stack, which calls theresource’s__exit__() method.

To register a cleanup function for something that isn’t acontext manager, usecall_on_close(). Or use somethingfromcontextlib to turn it into a context manager first.

@click.group()@click.option("--name")@click.pass_contextdefcli(ctx):ctx.obj=ctx.with_resource(connect_db(name))
Parameters:

context_manager (AbstractContextManager[V]) – The context manager to enter.

Returns:

Whatevercontext_manager.__enter__() returns.

Return type:

V

Changelog

Added in version 8.0.

call_on_close(f)

Register a function to be called when the context tears down.

This can be used to close resources opened during the scriptexecution. Resources that support Python’s context managerprotocol which would be used in awith statement should beregistered withwith_resource() instead.

Parameters:

f (Callable[[...],Any]) – The function to execute on teardown.

Return type:

Callable[[…],Any]

close()

Invoke all close callbacks registered withcall_on_close(), and exit all context managers enteredwithwith_resource().

Return type:

None

propertycommand_path:str

The computed command path. This is used for theusageinformation on the help page. It’s automatically created bycombining the info names of the chain of contexts to the root.

find_root()

Finds the outermost context.

Return type:

Context

find_object(object_type)

Finds the closest object of a given type.

Parameters:

object_type (type[V])

Return type:

V | None

ensure_object(object_type)

Likefind_object() but sets the innermost object to anew instance ofobject_type if it does not exist.

Parameters:

object_type (type[V])

Return type:

V

lookup_default(name:str,call:Literal[True]=True)Any|None
lookup_default(name:str,call:Literal[False]=True)Any|Callable[[],Any]|None

Get the default for a parameter fromdefault_map.

Parameters:
  • name – Name of the parameter.

  • call – If the default is a callable, call it. Disable toreturn the callable instead.

Changelog

Changed in version 8.0:Added thecall parameter.

fail(message)

Aborts the execution of the program with a specific errormessage.

Parameters:

message (str) – the error message to fail with.

Return type:

NoReturn

abort()

Aborts the script.

Return type:

NoReturn

exit(code=0)

Exits the application with a given exit code.

Changelog

Changed in version 8.2:Callbacks and context managers registered withcall_on_close()andwith_resource() are closed before exiting.

Parameters:

code (int)

Return type:

NoReturn

get_usage()

Helper method to get formatted usage string for the currentcontext and command.

Return type:

str

get_help()

Helper method to get formatted help page for the currentcontext and command.

Return type:

str

invoke(callback:Callable[[...],V],/,*args:Any,**kwargs:Any)V
invoke(callback:Command,/,*args:Any,**kwargs:Any)Any

Invokes a command callback in exactly the way it expects. Thereare two ways to invoke this method:

  1. the first argument can be a callback and all other arguments andkeyword arguments are forwarded directly to the function.

  2. the first argument is a click command object. In that case allarguments are forwarded as well but proper click parameters(options and click arguments) must be keyword arguments and Clickwill fill in defaults.

Changelog

Changed in version 8.0:Allkwargs are tracked inparams so they will bepassed ifforward() is called at multiple levels.

Changed in version 3.2:A new context is created, and missing arguments use default values.

forward(cmd,/,*args,**kwargs)

Similar toinvoke() but fills in default keywordarguments from the current context if the other command expectsit. This cannot invoke callbacks directly, only other commands.

Changelog

Changed in version 8.0:Allkwargs are tracked inparams so they will bepassed ifforward is called at multiple levels.

Parameters:
Return type:

Any

set_parameter_source(name,source)

Set the source of a parameter. This indicates the locationfrom which the value of the parameter was obtained.

Parameters:
Return type:

None

get_parameter_source(name)

Get the source of a parameter. This indicates the locationfrom which the value of the parameter was obtained.

This can be useful for determining when a user specified a valueon the command line that is the same as the default value. Itwill beDEFAULT only if thevalue was actually taken from the default.

Parameters:

name (str) – The name of the parameter.

Return type:

ParameterSource

Changelog

Changed in version 8.0:ReturnsNone if the parameter was not provided from anysource.

click.get_current_context(silent:Literal[False]=False)Context
click.get_current_context(silent:bool=False)Context|None

Returns the current click context. This can be used as a way toaccess the current context object from anywhere. This is a more implicitalternative to thepass_context() decorator. This function isprimarily useful for helpers such asecho() which might beinterested in changing its behavior based on the current context.

To push the current context,Context.scope() can be used.

Changelog

Added in version 5.0.

Parameters:

silent – if set toTrue the return value isNone if no contextis available. The default behavior is to raise aRuntimeError.

classclick.core.ParameterSource(*values)

This is anEnum that indicates the source of aparameter’s value.

Useclick.Context.get_parameter_source() to get thesource for a parameter by name.

Changelog

Changed in version 8.0:UseEnum and drop thevalidate method.

Changed in version 8.0:Added thePROMPT value.

COMMANDLINE=1

The value was provided by the command line args.

ENVIRONMENT=2

The value was provided with an environment variable.

DEFAULT=3

Used the default specified by the parameter.

DEFAULT_MAP=4

Used a default provided byContext.default_map.

PROMPT=5

Used a prompt to confirm a default or provide a value.

Types

click.STRING=STRING
Parameters:
Return type:

t.Any

click.INT=INT
Parameters:
Return type:

t.Any

click.FLOAT=FLOAT
Parameters:
Return type:

t.Any

click.BOOL=BOOL
Parameters:
Return type:

t.Any

click.UUID=UUID
Parameters:
Return type:

t.Any

click.UNPROCESSED=UNPROCESSED
Parameters:
Return type:

t.Any

classclick.File(mode='r',encoding=None,errors='strict',lazy=None,atomic=False)

Declares a parameter to be a file for reading or writing. The fileis automatically closed once the context tears down (after the commandfinished 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 beopened in binary mode or for writing. The encoding parameter can be usedto force a specific encoding.

Thelazy flag controls if the file should be opened immediately or uponfirst IO. The default is to be non-lazy for standard input and outputstreams as well as files opened for reading,lazy otherwise. When opening afile lazily for reading, it is still opened temporarily for validation, butwill not be held open until first IO. lazy is mainly useful when openingfor writing to avoid creating the file until it is needed.

Files can also be opened atomically in which case all writes go into aseparate file in the same folder and upon completion the file willbe moved over to the original location. This is useful if a fileregularly read by other users is modified.

SeeFile Arguments for more information.

Changelog

Changed in version 2.0:Added theatomic parameter.

Parameters:
classclick.Path(exists=False,file_okay=True,dir_okay=True,writable=False,readable=True,resolve_path=False,allow_dash=False,path_type=None,executable=False)

ThePath type is similar to theFile type, butreturns the filename instead of an open file. Various checks can beenabled to validate the type of file and permissions.

Parameters:
  • exists (bool) – The file or directory needs to exist for the value tobe valid. If this is not set toTrue, and the file does notexist, then all further checks are silently skipped.

  • file_okay (bool) – Allow a file as a value.

  • dir_okay (bool) – Allow a directory as a value.

  • readable (bool) – if true, a readable check is performed.

  • writable (bool) – if true, a writable check is performed.

  • executable (bool) – if true, an executable check is performed.

  • resolve_path (bool) – Make the value absolute and resolve anysymlinks. A~ is not expanded, as this is supposed to bedone by the shell only.

  • allow_dash (bool) – Allow a single dash as a value, which indicatesa standard stream (but does not open it). Useopen_file() to handle opening this value.

  • path_type (type[t.Any]|None) – Convert the incoming path value to this type. IfNone, keep Python’s default, which isstr. Useful toconvert topathlib.Path.

Changelog

Changed in version 8.1:Added theexecutable parameter.

Changed in version 8.0:Allow passingpath_type=pathlib.Path.

Changed in version 6.0:Added theallow_dash parameter.

classclick.Choice(choices,case_sensitive=True)

The choice type allows a value to be checked against a fixed setof supported values.

You may pass any iterable value which will be converted to a tupleand thus will only be iterated once.

The resulting value will always be one of the originally passed choices.Seenormalize_choice() for more info on the mapping of stringsto choices. SeeChoice for an example.

Parameters:
  • case_sensitive (bool) – Set to false to make choices caseinsensitive. Defaults to true.

  • choices (cabc.Iterable[ParamTypeValue])

Changelog

Changed in version 8.2.0:Non-strchoices are now supported. It can additionally be anyiterable. Before you were not recommended to pass anything but a list ortuple.

Added in version 8.2.0:Choice normalization can be overridden vianormalize_choice().

name:str='choice'

the descriptive name of this type

to_info_dict()

Gather information that could be useful for a tool generatinguser-facing documentation.

Useclick.Context.to_info_dict() to traverse the entireCLI structure.

Changelog

Added in version 8.0.

Return type:

dict[str,Any]

normalize_choice(choice,ctx)

Normalize a choice value, used to map a passed string to a choice.Each choice must have a unique normalized value.

By default usesContext.token_normalize_func() and if not casesensitive, convert it to a casefolded value.

Changelog

Added in version 8.2.0.

Parameters:
  • choice (ParamTypeValue)

  • ctx (Context |None)

Return type:

str

get_metavar(param,ctx)

Returns the metavar default for this param if it provides one.

Parameters:
Return type:

str | None

get_missing_message(param,ctx)

Message shown when no choice is passed.

Changelog

Changed in version 8.2.0:Addedctx argument.

Parameters:
Return type:

str

convert(value,param,ctx)

For a given value from the parser, normalize it and find itsmatching normalized value in the list of choices. Then return thematched “original” choice.

Parameters:
Return type:

ParamTypeValue

get_invalid_choice_message(value,ctx)

Get the error message when the given choice is invalid.

Parameters:
  • value (t.Any) – The invalid value.

  • ctx (Context |None)

Return type:

str

Changelog

Added in version 8.2.

shell_complete(ctx,param,incomplete)

Complete choices that start with the incomplete value.

Parameters:
  • ctx (Context) – Invocation context for this command.

  • param (Parameter) – The parameter that is requesting completion.

  • incomplete (str) – Value being completed. May be empty.

Return type:

list[CompletionItem]

Changelog

Added in version 8.0.

classclick.IntRange(min=None,max=None,min_open=False,max_open=False,clamp=False)

Restrict anclick.INT value to a range of acceptedvalues. SeeInt and Float Ranges.

Ifmin ormax are not passed, any value is accepted in thatdirection. Ifmin_open ormax_open are enabled, thecorresponding boundary is not included in the range.

Ifclamp is enabled, a value outside the range is clamped to theboundary instead of failing.

Changelog

Changed in version 8.0:Added themin_open andmax_open parameters.

Parameters:
classclick.FloatRange(min=None,max=None,min_open=False,max_open=False,clamp=False)

Restrict aclick.FLOAT value to a range of acceptedvalues. SeeInt and Float Ranges.

Ifmin ormax are not passed, any value is accepted in thatdirection. Ifmin_open ormax_open are enabled, thecorresponding boundary is not included in the range.

Ifclamp is enabled, a value outside the range is clamped to theboundary instead of failing. This is not supported if eitherboundary is markedopen.

Changelog

Changed in version 8.0:Added themin_open andmax_open parameters.

Parameters:
classclick.DateTime(formats=None)

The DateTime type converts date strings intodatetime objects.

The format strings which are checked are configurable, but default to somecommon (non-timezone aware) ISO 8601 formats.

When specifyingDateTime formats, you should only pass a list or a tuple.Other iterables, like generators, may lead to surprising results.

The format strings are processed usingdatetime.strptime, and thisconsequently defines the format strings which are allowed.

Parsing is tried using each format, in order, and the first format whichparses successfully is used.

Parameters:

formats (cabc.Sequence[str]|None) – A list or tuple of date format strings, in the order inwhich they should be tried. Defaults to'%Y-%m-%d','%Y-%m-%dT%H:%M:%S','%Y-%m-%d%H:%M:%S'.

classclick.Tuple(types)

The default behavior of Click is to apply a type on a value directly.This works well in most cases, except for whennargs is set to a fixedcount and different types should be used for different items. In thiscase theTuple type can be used. This type can only be usedifnargs is set to a fixed number.

For more information seeMulti Value Options as Tuples.

This can be selected by using a Python tuple literal as a type.

Parameters:

types (cabc.Sequence[type[t.Any]|ParamType]) – a list of types that should be used for the tuple items.

classclick.ParamType

Represents the type of a parameter. Validates and converts valuesfrom the command line or Python into the correct type.

To implement a custom type, subclass and implement at least thefollowing:

  • Thename class attribute must be set.

  • Calling an instance of the type withNone must returnNone. This is already implemented by default.

  • convert() must convert string values to the correct type.

  • convert() must accept values that are already the correcttype.

  • It must be able to convert a value if thectx andparamarguments areNone. This can occur when converting promptinput.

name:str

the descriptive name of this type

envvar_list_splitter:ClassVar[str|None]=None

if a list of this type is expected and the value is pulled from astring environment variable, this is what splits it up.Nonemeans any whitespace. For all parameters the general rule is thatwhitespace splits them up. The exception are paths and files whichare split byos.path.pathsep by default (“:” on Unix and “;” onWindows).

to_info_dict()

Gather information that could be useful for a tool generatinguser-facing documentation.

Useclick.Context.to_info_dict() to traverse the entireCLI structure.

Changelog

Added in version 8.0.

Return type:

dict[str,Any]

get_metavar(param,ctx)

Returns the metavar default for this param if it provides one.

Parameters:
Return type:

str | None

get_missing_message(param,ctx)

Optionally might return extra information about a missingparameter.

Changelog

Added in version 2.0.

Parameters:
Return type:

str | None

convert(value,param,ctx)

Convert the value to the correct type. This is not called ifthe value isNone (the missing value).

This must accept string values from the command line, as well asvalues that are already the correct type. It may also convertother compatible types.

Theparam andctx arguments may beNone in certainsituations, such as when converting prompt input.

If the value cannot be converted, callfail() with adescriptive message.

Parameters:
  • value (t.Any) – The value to convert.

  • param (Parameter |None) – The parameter that is using this type to convertits value. May beNone.

  • ctx (Context |None) – The current context that arrived at this value. MaybeNone.

Return type:

t.Any

split_envvar_value(rv)

Given a value from an environment variable this splits it upinto small chunks depending on the defined envvar list splitter.

If the splitter is set toNone, which means that whitespace splits,then leading and trailing whitespace is ignored. Otherwise, leadingand trailing splitters usually lead to empty items being included.

Parameters:

rv (str)

Return type:

Sequence[str]

fail(message,param=None,ctx=None)

Helper method to fail with an invalid value message.

Parameters:
Return type:

t.NoReturn

shell_complete(ctx,param,incomplete)

Return a list ofCompletionItem objects for theincomplete value. Most types do not provide completions, butsome do, and this allows custom types to provide customcompletions as well.

Parameters:
  • ctx (Context) – Invocation context for this command.

  • param (Parameter) – The parameter that is requesting completion.

  • incomplete (str) – Value being completed. May be empty.

Return type:

list[CompletionItem]

Changelog

Added in version 8.0.

Exceptions

exceptionclick.ClickException(message)

An exception that Click can handle and show to the user.

Parameters:

message (str)

Return type:

None

exceptionclick.Abort

An internal signalling exception that signals Click to abort.

exceptionclick.UsageError(message,ctx=None)

An internal exception that signals a usage error. This typicallyaborts any further handling.

Parameters:
  • message (str) – the error message to display.

  • ctx (Context |None) – optionally the context that caused this error. Click willfill in the context automatically in some situations.

Return type:

None

exceptionclick.BadParameter(message,ctx=None,param=None,param_hint=None)

An exception that formats out a standardized error message for abad parameter. This is useful when thrown from a callback or type asClick will attach contextual information to it (for instance, whichparameter it is).

Changelog

Added in version 2.0.

Parameters:
  • param (Parameter |None) – the parameter object that caused this error. This canbe left out, and Click will attach this info itselfif possible.

  • param_hint (cabc.Sequence[str]|str |None) – a string that shows up as parameter name. Thiscan be used as alternative toparam in caseswhere custom validation should happen. If it isa string it’s used as such, if it’s a list theneach item is quoted and separated.

  • message (str)

  • ctx (Context |None)

Return type:

None

exceptionclick.FileError(filename,hint=None)

Raised if a file cannot be opened.

Parameters:
  • filename (str)

  • hint (str |None)

Return type:

None

exceptionclick.NoSuchOption(option_name,message=None,possibilities=None,ctx=None)

Raised if click attempted to handle an option that does notexist.

Changelog

Added in version 4.0.

Parameters:
  • option_name (str)

  • message (str |None)

  • possibilities (cabc.Sequence[str]|None)

  • ctx (Context |None)

Return type:

None

exceptionclick.BadOptionUsage(option_name,message,ctx=None)

Raised if an option is generally supplied but the use of the optionwas incorrect. This is for instance raised if the number of argumentsfor an option is not correct.

Changelog

Added in version 4.0.

Parameters:
  • option_name (str) – the name of the option being used incorrectly.

  • message (str)

  • ctx (Context |None)

Return type:

None

exceptionclick.BadArgumentUsage(message,ctx=None)

Raised if an argument is generally supplied but the use of the argumentwas incorrect. This is for instance raised if the number of valuesfor an argument is not correct.

Changelog

Added in version 6.0.

Parameters:
Return type:

None

Formatting

classclick.HelpFormatter(indent_increment=2,width=None,max_width=None)

This class helps with formatting text-based help pages. It’susually just needed for very special internal cases, but it’s alsoexposed so that developers can write their own fancy outputs.

At present, it always writes into memory.

Parameters:
  • indent_increment (int) – the additional increment for each level.

  • width (int |None) – the width for the text. This defaults to the terminalwidth clamped to a maximum of 78.

  • max_width (int |None)

write(string)

Writes a unicode string into the internal buffer.

Parameters:

string (str)

Return type:

None

indent()

Increases the indentation.

Return type:

None

dedent()

Decreases the indentation.

Return type:

None

write_usage(prog,args='',prefix=None)

Writes a usage line into the buffer.

Parameters:
  • prog (str) – the program name.

  • args (str) – whitespace separated list of arguments.

  • prefix (str |None) – The prefix for the first line. Defaults to"Usage:".

Return type:

None

write_heading(heading)

Writes a heading into the buffer.

Parameters:

heading (str)

Return type:

None

write_paragraph()

Writes a paragraph into the buffer.

Return type:

None

write_text(text)

Writes re-indented text into the buffer. This rewraps andpreserves paragraphs.

Parameters:

text (str)

Return type:

None

write_dl(rows,col_max=30,col_spacing=2)

Writes a definition list into the buffer. This is how optionsand commands are usually formatted.

Parameters:
  • rows (Sequence[tuple[str,str]]) – a list of two item tuples for the terms and values.

  • col_max (int) – the maximum width of the first column.

  • col_spacing (int) – the number of spaces between the first andsecond column.

Return type:

None

section(name)

Helpful context manager that writes a paragraph, a heading,and the indents.

Parameters:

name (str) – the section name that is written as heading.

Return type:

Iterator[None]

indentation()

A context manager that increases the indentation.

Return type:

Iterator[None]

getvalue()

Returns the buffer contents.

Return type:

str

click.wrap_text(text,width=78,initial_indent='',subsequent_indent='',preserve_paragraphs=False)

A helper function that intelligently wraps text. By default, itassumes that it operates on a single paragraph of text but if thepreserve_paragraphs parameter is provided it will intelligentlyhandle paragraphs (defined by two empty lines).

If paragraphs are handled, a paragraph can be prefixed with an emptyline containing the\b character (\x08) to indicate thatno rewrapping should happen in that block.

Parameters:
  • text (str) – the text that should be rewrapped.

  • width (int) – the maximum width for the text.

  • initial_indent (str) – the initial indent that should be placed on thefirst line as a string.

  • subsequent_indent (str) – the indent string that should be placed oneach consecutive line.

  • preserve_paragraphs (bool) – if this flag is set then the wrapping willintelligently handle paragraphs.

Return type:

str

Parsing

click.OptionParser

alias of_OptionParser

Shell Completion

SeeShell Completion for information about enabling andcustomizing Click’s shell completion system.

classclick.shell_completion.CompletionItem(value,type='plain',help=None,**kwargs)

Represents a completion value and metadata about the value. Thedefault metadata istype to indicate special shell handling,andhelp if a shell supports showing a help string next to thevalue.

Arbitrary parameters can be passed when creating the object, andaccessed usingitem.attr. If an attribute wasn’t passed,accessing it returnsNone.

Parameters:
  • value (t.Any) – The completion suggestion.

  • type (str) – Tells the shell script to provide special completionsupport for the type. Click uses"dir" and"file".

  • help (str |None) – String shown next to the value if supported.

  • kwargs (t.Any) – Arbitrary metadata. The built-in implementationsdon’t use this, but custom type completions paired with customshell support could use it.

classclick.shell_completion.ShellComplete(cli,ctx_args,prog_name,complete_var)

Base class for providing shell completion support. A subclass fora given shell will override attributes and methods to implement thecompletion instructions (source andcomplete).

Parameters:
  • cli (Command) – Command being called.

  • prog_name (str) – Name of the executable in the shell.

  • complete_var (str) – Name of the environment variable that holdsthe completion instruction.

  • ctx_args (cabc.MutableMapping[str,t.Any])

Changelog

Added in version 8.0.

name:ClassVar[str]

Name to register the shell as withadd_completion_class().This is used in completion instructions ({name}_source and{name}_complete).

source_template:ClassVar[str]

Completion script template formatted bysource(). This mustbe provided by subclasses.

propertyfunc_name:str

The name of the shell function defined by the completionscript.

source_vars()

Vars for formattingsource_template.

By default this providescomplete_func,complete_var,andprog_name.

Return type:

dict[str,Any]

source()

Produce the shell script that defines the completionfunction. By default this%-style formatssource_template with the dict returned bysource_vars().

Return type:

str

get_completion_args()

Use the env vars defined by the shell script to return atuple ofargs,incomplete. This must be implemented bysubclasses.

Return type:

tuple[list[str],str]

get_completions(args,incomplete)

Determine the context and last complete command or parameterfrom the complete args. Call that object’sshell_completemethod to get the completions for the incomplete value.

Parameters:
  • args (list[str]) – List of complete args before the incomplete value.

  • incomplete (str) – Value being completed. May be empty.

Return type:

list[CompletionItem]

format_completion(item)

Format a completion item into the form recognized by theshell script. This must be implemented by subclasses.

Parameters:

item (CompletionItem) – Completion item to format.

Return type:

str

complete()

Produce the completion data to send back to the shell.

By default this callsget_completion_args(), gets thecompletions, then callsformat_completion() for eachcompletion.

Return type:

str

click.shell_completion.add_completion_class(cls,name=None)

Register aShellComplete subclass under the given name.The name will be provided by the completion instruction environmentvariable during completion.

Parameters:
  • cls (ShellCompleteType) – The completion class that will handle completion for theshell.

  • name (str |None) – Name to register the class under. Defaults to theclass’sname attribute.

Return type:

ShellCompleteType

Testing

classclick.testing.CliRunner(charset='utf-8',env=None,echo_stdin=False,catch_exceptions=True)

The CLI runner provides functionality to invoke a Click command linescript for unittesting purposes in a isolated environment. This onlyworks in single-threaded systems without any concurrency as it changes theglobal interpreter state.

Parameters:
  • charset (str) – the character set for the input and output data.

  • env (cabc.Mapping[str,str |None]|None) – a dictionary with environment variables for overriding.

  • echo_stdin (bool) – if this is set toTrue, then reading from<stdin> writesto<stdout>. This is useful for showing examples insome circumstances. Note that regular promptswill automatically echo the input.

  • catch_exceptions (bool) – Whether to catch any exceptions other thanSystemExit when runninginvoke().

Changelog

Changed in version 8.2:Added thecatch_exceptions parameter.

Changed in version 8.2:mix_stderr parameter has been removed.

get_default_prog_name(cli)

Given a command object it will return the default program namefor it. The default is thename attribute or"root" if notset.

Parameters:

cli (Command)

Return type:

str

make_env(overrides=None)

Returns the environment overrides for invoking a script.

Parameters:

overrides (Mapping[str,str |None]|None)

Return type:

Mapping[str,str | None]

isolation(input=None,env=None,color=False)

A context manager that sets up the isolation for invoking of acommand line tool. This sets up<stdin> with the given input dataandos.environ with the overrides from the given dictionary.This also rebinds some internals in Click to be mocked (like theprompt functionality).

This is automatically done in theinvoke() method.

Parameters:
  • input (str |bytes |IO[Any]|None) – the input stream to put intosys.stdin.

  • env (Mapping[str,str |None]|None) – the environment overrides as dictionary.

  • color (bool) – whether the output should contain color codes. Theapplication can still override this explicitly.

Return type:

Iterator[tuple[BytesIO,BytesIO,BytesIO]]

Changelog

Added in version 8.2:An additional output stream is returned, which is a mix of<stdout> and<stderr> streams.

Changed in version 8.2:Always returns the<stderr> stream.

Changed in version 8.0:<stderr> is opened witherrors="backslashreplace"instead of the default"strict".

Changed in version 4.0:Added thecolor parameter.

invoke(cli,args=None,input=None,env=None,catch_exceptions=None,color=False,**extra)

Invokes a command in an isolated environment. The arguments areforwarded directly to the command line script, theextra keywordarguments are passed to themain() function ofthe command.

This returns aResult object.

Parameters:
  • cli (Command) – the command to invoke

  • args (str |cabc.Sequence[str]|None) – the arguments to invoke. It may be given as an iterableor a string. When given as string it will be interpretedas a Unix shell command. More details atshlex.split().

  • input (str |bytes |t.IO[t.Any]|None) – the input data forsys.stdin.

  • env (cabc.Mapping[str,str |None]|None) – the environment overrides.

  • catch_exceptions (bool |None) – Whether to catch any other exceptions thanSystemExit. IfNone, the valuefromCliRunner is used.

  • extra (t.Any) – the keyword arguments to pass tomain().

  • color (bool) – whether the output should contain color codes. Theapplication can still override this explicitly.

Return type:

Result

Changelog

Added in version 8.2:The result object has theoutput_bytes attribute withthe mix ofstdout_bytes andstderr_bytes, as the user wouldsee it in its terminal.

Changed in version 8.2:The result object always returns thestderr_bytes stream.

Changed in version 8.0:The result object has thereturn_value attribute withthe value returned from the invoked command.

Changed in version 4.0:Added thecolor parameter.

Changed in version 3.0:Added thecatch_exceptions parameter.

Changed in version 3.0:The result object has theexc_info attribute with thetraceback if available.

isolated_filesystem(temp_dir=None)

A context manager that creates a temporary directory andchanges the current working directory to it. This isolates teststhat affect the contents of the CWD to prevent them frominterfering with each other.

Parameters:

temp_dir (str |PathLike[str]|None) – Create the temporary directory under thisdirectory. If given, the created directory is not removedwhen exiting.

Return type:

Iterator[str]

Changelog

Changed in version 8.0:Added thetemp_dir parameter.

classclick.testing.Result(runner,stdout_bytes,stderr_bytes,output_bytes,return_value,exit_code,exception,exc_info=None)

Holds the captured result of an invoked CLI script.

Parameters:
  • runner (CliRunner) – The runner that created the result

  • stdout_bytes (bytes) – The standard output as bytes.

  • stderr_bytes (bytes) – The standard error as bytes.

  • output_bytes (bytes) – A mix ofstdout_bytes andstderr_bytes, as theuser would see it in its terminal.

  • return_value (t.Any) – The value returned from the invoked command.

  • exit_code (int) – The exit code as integer.

  • exception (BaseException |None) – The exception that happened if one did.

  • exc_info (tuple[type[BaseException],BaseException,TracebackType]|None) – Exception information (exception type, exception instance,traceback type).

Changelog

Changed in version 8.2:stderr_bytes no longer optional,output_bytes introduced andmix_stderr has been removed.

Added in version 8.0:Addedreturn_value.

propertyoutput:str

The terminal output as unicode string, as the user would see it.

Changelog

Changed in version 8.2:No longer a proxy forself.stdout. Now has its own independent streamthat is mixing<stdout> and<stderr>, in the order they were written.

propertystdout:str

The standard output as unicode string.

propertystderr:str

The standard error as unicode string.

Changelog

Changed in version 8.2:No longer raise an exception, always returns the<stderr> string.