Internals

clik

The command line interface kit.

Clik is a tool for writing complex command-line interfaces with minimal boilerplate and bookkeeping.

This top-level package pulls together the end user API from the various modules within clik.

author:Joe Joyce <joe@decafjoe.com>
copyright:Copyright (c) Joe Joyce and contributors, 2009-2019.
license:BSD
clik.__version__ = '0.92.5'

Current version.

Type:str

clik.app

Top-level App class and helpers.

author:Joe Joyce <joe@decafjoe.com>
copyright:Copyright (c) Joe Joyce and contributors, 2009-2019.
license:BSD
clik.app.current_app

Magic variable containing the active application instance.

Type:clik.magic.Magicclik.app.App
clik.app.parser

Magic variable containing the current parser.

Type:clik.magic.Magicclik.argparse.ArgumentParser
clik.app.args

Magic variable containing parsed arguments.

Type:clik.magic.Magicargparse.Namespace
clik.app.g

Magic variable containing globals.

Type:clik.magic.Magicclik.app.AttributeDict
clik.app.run_children

Magic variable containing the function to run child commands.

Type:clik.magic.Magic
clik.app.unknown_args

Magic variable containing unknown arguments.

Type:clik.magic.Magiclist
clik.app.app(fn=None, name=None)[source]

Decorate the main application generator function.

If the decorator is given no arguments, the name of the application is the name of the decorated generator function:

# Application will be named 'myapp' in this case
@app
def myapp():
    yield

The application name can be set by passing a string to name:

# Application will be named 'theapp' in this case
@app(name='theapp')
def myapp():
    yield
Parameters:
  • fn – Main application generator function. Name of the application will be set to fn.__name__.
  • name – Overrides name of application. Must not be used with the fn argument (if used with fn, name is ignored).
Returns:

App if fn is None, otherwise a decorator returning App.

class clik.app.App(fn, name=None)[source]

Bases: clik.command.Command

clik.Command subclass that implements the main() method.

main() is the user-level API for starting the application.

main(argv=None, exit=<built-in function exit>)[source]

Start the application.

Parameters:
  • argv – Optional list of command-line arguments. If not supplied, this defaults to sys.argv.
  • exit (fn(integer_exit_code)) – Optional function to call on exit. If not supplied, this defaults to sys.exit().
Returns:

Return value of exit

clik.argparse

Most of the hackery that makes clik tick.

author:Joe Joyce <joe@decafjoe.com>
copyright:Copyright (c) Joe Joyce and contributors, 2009-2019.
license:BSD
clik.argparse.ALLOW_UNKNOWN = '_clik_unknown'

Name of the argument that contains whether to allow unknown arguments.

Type:str
exception clik.argparse.ArgumentParserExit(code)[source]

Raised instead of allowing argparse to call sys.exit().

code = None

Exit code.

Type:int
exception clik.argparse.BareUnsupportedFeatureError(feature)[source]

Raised when using a feature that is not supported by bare commands.

feature = None

Feature that is unsupported.

Type:str
class clik.argparse.HelpFormatter(prog, indent_increment=2, max_help_position=24, width=None)[source]

Bases: argparse.HelpFormatter

Format usage with no trailing newline on usage.

class clik.argparse.ArgumentParser(*args, **kwargs)[source]

Bases: argparse.ArgumentParser

argparse.ArgumentParser specialized for clik.

_clik_bare_arguments()[source]

Context manager for bare command mode.

When the parser is in bare command mode, it disallows certain features (like positional args and mutually exclusive groups). In addition, the argument destinations are recorded in order to do some post-processing before running the selected command.

add_argument(*args, **kwargs)[source]

Override default behavior to disallow posargs in bare commands.

Raise:BareUnsupportedFeatureError if adding a positional argument to a bare command.
add_mutually_exclusive_group(*args, **kwargs)[source]

Override default behavior to disallow mutex groups in bare commands.

Raise:BareUnsupportedFeatureError if adding a mutually exclusive group to a bare command.
allow_unknown_args()[source]

Allow unknown arguments, putting them in clik.unknown_args.

Raise:UnknownArgsUnsupportedError if this parser has subparsers – unknown arguments are allowed only on leaf commands.
exit(status=0, message=None)[source]

Override default behavior to avoid interpreter exit.

By default, the parser calls sys.exit(). In certain situations – namely testing – we don’t actually want to exit the Python interpreter.

So instead of exiting, this throws an ArgumentParserExit exception which can be caught by the caller.

Parameters:
  • status (int) – Exit status.
  • message (str) – Optional message. If supplied, will be printed to sys.stderr before raising the exception.
Raise:

ArgumentParserExit

format_help()[source]

Override default behavior to support formatting bare commands.

format_usage()[source]

Override default behavior to use clik’s formatter.

clik.command

All the recursive, argument-parsin’, context-managin’ goodness.

author:Joe Joyce <joe@decafjoe.com>
copyright:Copyright (c) Joe Joyce and contributors, 2009-2019.
license:BSD
clik.command.catch = <object object>

Globally-unique value used by commands to indicate they want clik to send the exception (if one occurred) in addition to the child exit code in response to a yield.

Type:object
clik.command.ARGS = 'args'

Name of the magic variable containing the parsed arguments.

Type:str
clik.command.STACK = '_clik_stack'

Name of the argument that contains the stack of commands to be run.

Type:str
clik.command.SHOW_SUBCOMMANDS = 3

If a parent has more than this number of subcommands, the help output will {command} instead of the full list of subcommands.

Type:int
exception clik.command.BareAlreadyRegisteredError(command)[source]

Raised when a bare command has already been registered.

command = None

Command caller was trying to register as the bare command.

Type:Command
class clik.command.Command(ctx, fn, name=None, alias=None, aliases=None)[source]

Bases: object

The invisible backend driving most of what the user interacts with.

__init__(ctx, fn, name=None, alias=None, aliases=None)[source]

Initialize the command object.

Parameters:
  • ctx (clik.context.Context) – Context object.
  • fn – Generator function – the actual command.
  • name (str) – Name of the command or None. If None, name will be fn.__name__.
  • alias (str) – Command alias or None. If None, the command has no aliases. If this and aliases are both supplied, alias will be prepended to the aliases list.
  • aliases (list or None) – List of additional aliases for the command or None.
__call__(fn=None, name=None, alias=None, aliases=None)[source]

Add subcommands to this command.

Basic use:

@myapp
def mysubcommand():
    yield

Customizing the subcommand:

@myapp(name='subcommand', alias='sub', aliases=['s'])
def mysubcommand():
    yield
Parameters:
  • fn – Generator function or None. If fn is supplied, all other arguments are ignored.
  • name (str) – Name of the command or None.
  • alias (str) – Command alias. See __init__() for information on how aliases are handled.
  • aliases (list or None) – List of additional aliases for the command or None.
_configure_parser(parser, parent=None, stack=None)[source]
_check_bare_arguments()[source]
_run(child=False)[source]
_aliases = None

Tuple of aliases for this command.

Type:tuple of str
_bare = None

Command instance for the bare command or None if bare command is not set.

Type:Command or None
_children = None

List of child commands.

Type:list of Command instances
_ctx = None

Context object for this command. This context is shared between all command instances associated with a clik.app.App.

Type:clik.context.Context
_fn = None

Generator function – the actual command.

Type:generator function
_generator = None

In-progress generator for _fn. This is the object that we call generator.send() and generator.next() on.

Type:generator
_name = None

Canonical name of the command.

Type:str
_parent = None

Parent command. For the root clik.app.App instance, this is None. Set in _configure_parser().

Type:Command or None
_parser = None

Parser for this command. Set in _configure_parser().

Type:clik.argparse.ArgumentParser

clik.compat

Python compatibility helpers.

author:Joe Joyce <joe@decafjoe.com>
copyright:Copyright (c) Joe Joyce and contributors, 2009-2019.
license:BSD
clik.compat.PY2

Indicates whether we are on Python 2.

Type:bool
clik.compat.PY26

Indicates whether we are on Python 2.6.

Type:bool
clik.compat.PY33

Indicates whether we are on Python 3.3.

Type:bool

clik.context

Manage bindings for clik.magic.Magic variables.

author:Joe Joyce <joe@decafjoe.com>
copyright:Copyright (c) Joe Joyce and contributors, 2009-2019.
license:BSD
exception clik.context.LockedMagicError(name)[source]

Raised when trying to acquire a magvar that is already acquired.

name = None

Name of the magic variable that is locked.

Type:str
exception clik.context.MagicNameConflictError(name)[source]

Raised when trying to register an already-registered magvar.

name = None

Name of the magic variable that is already registered.

Type:str
exception clik.context.UnregisteredMagicNameError(name)[source]

Raised when trying to access an unregistered magic variable.

name = None

Name of the magic variable that is unregistered.

Type:str
exception clik.context.UnboundMagicError(name)[source]

Raised when trying to access a magic variable that is not bound.

name = None

Name of the magic variable that is unbound.

Type:str
class clik.context.Context[source]

Bases: object

Bindings manager for magic variables.

__call__(**kwargs)[source]

Context manager for push() -ing kwargs during a code block.

Example:

context = Context()
context.register('foo')
with context(foo='bar'):
    pass  # do some stuff

Before the block, each key/value pair in kwargs is passed to push(). After the block, each key is pop() -ped.

acquire(*magic_variables)[source]

Context manager to lock magic_variables from use by other contexts.

Only one context at a time is allowed to control the binding of a magic variable. Using this context manager ensures the caller can safely manipulate the binding without interference from other contexts:

foo = Magic('foo')
context1 = Context()
context1.register('foo')
context2 = Context()
context2.register('foo')
with context1.acquire(foo):
    with context1(foo='bar'):
        pass  # do some stuff
    with context2.acquire(foo):
        # BOOM! LockedMagicError gets thrown

Before the block, each of the magic_variables is checked to see if it currently has a context. If so, LockedMagicError is thrown. Otherwise, the context is set to this instance.

After the block, the context for each magic variable is reset to None, freeing it up for use by other contexts.

Raise:LockedMagicError if one of magic_variables is already acquired
get(name)[source]

Return currently-bound value of magic variable named name.

Parameters:name (str) – Name of magic variable.
Raise:UnregisteredMagicNameError if name is not registered
Raise:UnboundMagicError if variable is not currently bound
pop(name)[source]

Pop and return the current value off the variable’s stack.

This rebinds the variable to the next-highest item on the stack.

Parameters:name (str) – Name of magic variable.
Raise:UnregisteredMagicNameError if name is not registered
Raise:UnboundMagicError if variable is not currently bound
push(name, obj)[source]

Push a value on to a variable’s stack, rebinding its current value.

Parameters:
  • name (str) – Name of magic variable.
  • obj – New value to push on to the stack.
Raise:

UnregisteredMagicNameError if name is not registered

register(name)[source]

Register a magic variable name.

Requiring registration prevents accidental conflicts between modules. If two modules (which may not know about each other) both try to register the same magic variable, clik will thrown an exception.

Parameters:name (str) – Name of magic variable.
Raise:MagicNameConflictError if name is already registered
unregister(name)[source]

Unregister a magic variable name.

Parameters:name (str) – Name of magic variable.
Raise:UnregisteredMagicNameError if name is not registered

clik.magic

Slightly adapted version of Werkzeug’s werkzeug.local.LocalProxy.

Original code licensed from the Werkzeug Team under the following terms:

Copyright (c) 2014 by the Werkzeug Team, see AUTHORS for more details.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

  • Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
  • Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
  • The names of the contributors may not be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

copyright:Copyright (c) 2014 by the Werkzeug Team
authors:See Werkzeug’s AUTHORS file
license:BSD
class clik.magic.Magic(name)[source]

clik.util

The ever-present utilities module.

author:Joe Joyce <joe@decafjoe.com>
copyright:Copyright (c) Joe Joyce and contributors, 2009-2019.
license:BSD
class clik.util.AttributeDict[source]

Bases: dict

Simple dict wrapper that allows key access via attribute.

Example:

d = AttributeDict(foo='bar', baz='qux')
d['foo']      # 'bar'
d.foo         # 'bar'
d['baz']      # 'qux'
d.baz         # 'qux'
d.foo = 'bup'
d['foo']      # 'bup'
d.foo         # 'bup'
del d.foo
d.foo         # KeyError
__delattr__(name)[source]

Delete via attribute name.

__getattr__(name)[source]

Get via attribute name.

__setattr__(name, value)[source]

Set via attribute name.