Skip to main content

Command Line Object Chaining (cloc) - Modern cli framework for simple and complex cli applications

Project description


MIT badge Python3.6 badge Platform badge

Command Line Object Chaining

Command line framework for making simple and complex command line applications.
  • Easily create stand alone commands or nested groups of commands
  • Define and connect commands with class objects
  • Inherit and create viewsets of commands to be able to reuse large nested groups in other cli applications
  • Use mixin commands to quickly add pre defined commands to your cli
  • Groups of commands can be found from any class that has defined a cloc.core.BaseCmd


Virtual Environment is recommended

pip3 install cloc


Cmd and Grp

The two core features (classes) of CLOC, command line object chaining, are Cmd and Grp.

A Cmd class object defines one action to process when invoked. In most cases, this will be the defined function that is decorated. A command can be invoked by calling the Cmd or being called by a Grp.

A Grp class object holds one to many actions to process when invoked. The actions can be a Cmd or another Grp, but only one action can be called at a time per Grp. The first Grp will receive the first command line state, sys.argv[1:]. Every Grp will receive a command line state and will pass this state to the next action. It is on Grp only to update the command line state.

from cloc import cmd, grp

def cli():
    """cli group"""

def hello_world():
    """hello world function"""
    print('Hello World')


Grp help structure. Usage will always be grp name (cmd|grp)


        cli group


| Name                     | Description                                          |
| ------------------------ | ---------------------------------------------------- |
| hello-world              | hello world function                                 |

Parameters - Arg, Opt, and Flg

Currently parameters can only be given to a Cmd.

The three core parameters include:

  • Arg - a named positional argument for the command

      Arg(name: str, type: Any = str, help: str = None)
  • Opt - a named non-positional argument for the command

      Opt(name: str, short_name: str, type: Any = str, default: Any= None, multiple: bool= False, 
          required: bool= False, help: str = None)
  • Flg - a special version of Opt that is always type bool and expects no value

      Flg(name: str, short_name: str, help: str = None)

Below is an extended greeting cmd from above without the grp.
from cloc import arg, cmd, flg, opt
from cloc.types import IntRange

@arg('NAME', type=str, help='The person to greet')
@opt('--count', '-c', type=IntRange, default=1, help='Number of greetings: ex -c 0,5 OR -c 5')
@flg('--no_repeat', '-nr', help='If given, the greeting will not repeat')
def hello(name: str, count: IntRange, no_repeat: bool):
    """Simple program that greets NAME for a total of COUNT times."""
    for _ in count:
        print(f'Hello {name!r}')
        if no_repeat:

if __name__ == '__main__':

The below output is an example of a print message for the greeting cmd.


        Simple program that greets NAME for a total of COUNT times.

USAGE: hello NAME --count|-c [value] --no_repeat|-nr 

| Name               | Short    | Type             | Help                                                   |
| ------------------ | -------- | ---------------- | ------------------------------------------------------ |
| NAME               |          | str              | The person to greet                                    |
| --count            | -c       | cloc.IntRange    | [default: 1] Number of greetings: ex -c 0,5 OR -c 5    |
| --no_repeat        | -nr      | bool             | [flag] If given, the greeting will not repeat          |


cloc.core.BaseCmd(name: str, params: Params= None, hidden: bool= False)

A base class that represents a basic command with a name, Params (cloc.core.Params), and a hidden option. This class is meant to be inherited by new typs of commands. This class alone cannot invoke any functionality.

BaseCmd.values: list

The values attribute is the list of arguments to be unpacked into the invoked function from the cmd

BaseCmd.params: cloc.core.Params

The params attribute is the list of parameter objects defined for the cmd

BaseCmd._parse(cmdl: list)

Protected method to parse the current command line state. This will create the help string, create the param regex strings, and get params values for the invoked BaseCmd. This method is protected and should normally not be called.


The create_help method with create a formatted and colored help string using any params found


Protected method to print the help message. This method can be overloaded in certain cases but is meant to call the help attribute which might not exists in certain states.


A method to be overloaded by a new command. This should create your regex patterns based on the defined parameters.

BaseCmd.get_values(cmdl: list)

A method to be overloaded by a new command. After the regex patterns have been created, then the param values can be parsed from the command line state and stored to be unpacked into the invoked command function.

cloc.core.Cmd(name: str, fn: Callable, params: Params = None, hidden: bool = False)

Cmd inherits BaseCmd to create a new command that can invoke a given function and be connected to class objects.

Cmd.fn: Callable

The fn attribute is the defined function to run when cmd is invoked

Cmd.dataclass: object

The dataclass attribute is an object to replace self with if the cmd is defined inside a class

Cmd.new_dataclass_cmd(cls, name: str, fn: Callable, params: Params= None, hidden: bool= False, dataclass: object= None)


This class method will create a new Cmd that will have the dataclass attribute set


Create regex patterns for each opt and flg param to match against the command line state during get_values

Cmd.get_values(cmdl: list)

Overloaded function from BaseCmd, this method will create the values to be unpacked into Cmd.fn. If --help is anywhere the command line, the help message for the nearest Cmd is called.

cloc.core.Grp(name: str, commands: List[Cmd] = None, hidden:bool= False)

Grp inherits from BaseCmd, this class holds a list of Cmd objects which can be invoked by name. If Grp calls Grp, the command line state will be updated. If a Grp is made with no cmdl supplied then sys.argv[1:] is used.

Grp.commands: List[Cmd]

The commands attribute is a list of Cmd objects. Cmd objects are added through the Grp.add_command method.

BaseCmd.invoke: str

The invoke attribute is user input from the command line and should match a in Grp.commands

BaseCmd.cmdl: list

The cmdl attribute should represent the current state of the command line for the Grp to parse.

BaseCmd.add_command(command: BaseCmd, hidden:bool= None)

Add a Cmd or Grp to another Grp. Can also override or set hidden state

This method will also make a new dataclass Cmd if needed. If a command is found inside a class, initiate a dataclass Cmd to be made. Setting dataclass = class that declared the commands.

  • a dataclass Cmd is the magic to allow Cli Viewsets and Querysets

BaseCmd.get_command(name: str)

Find a Cmd by name and return the object


As seen in the above examples, decorators can be used to easily convert defined functions into a cmd or grp. There is a decorator for each core class in cloc. They are imported into the cloc module for ease of use.

cloc.decorators.cmd(name:str = None, hidden:bool = False)

Returns a new Cmd object

cloc.decorators.grp(name:str = None, hidden:bool = False)

Returns a new Grp object

cloc.decorators.arg(name:str, type: Any= None, help: str= None)

Returns a Cmd object. If the object being decorated is already a Cmd object, the Arg will be appended to Cmd.params

cloc.decorators.opt(name:str, short_name: str, type: Any= None, default: Any= None, multiple:bool= False, required: bool= False, help: str= None)

Returns a Cmd object. If the object being decorated is already a Cmd object, the Opt will be appended to Cmd.params

cloc.decorators.flg(name:str, short_name: str, help: str= None)

Returns a Cmd object. If the object being decorated is already a Cmd object, the Flg will be appended to Cmd.params


New types can be made to be used to convert the command line input. A new cloc type must inherit the cloc.types.BaseType and overload the __call__ function to convert the input. New types can raise an exception or print to trace for a clean exit.

cloc.types.BaseType(self, basetype: Any = None)

BaseType - BaseType object for creating new Param types

   __call__ method should be overloaded to handle value; str -> BaseType

BaseType.__call__(self, value: str)

convert to new type

        value {str} -- value to convert

cloc.types.Choices(self, choices: list, basetype: Any = typing.Any)

Convert input into a Choices object which will verify the input is contained in the defined choices.


Convert input into a DateTime object


Convert input into a file object. The below example is the cloc.types.FileType implementation

class FileType(BaseType):
    __name__ = 'cloc.File'

    def __init__(self):
        # init should provide a base type, default to str

    def __exit__(self, exc_type, exc_val, exc_tb):

    def __call__(self, filepath: str):
        if not os.path.exists(filepath):
            trace(f'Error: {filepath!r} does not  exists', TypeError)
        elif not os.path.isfile(filepath):
            trace(f'Error: {filepath!r} is not a file', TypeError)
        self.fobj = open(filepath, 'r')
        return self.fobj

FileType.__exit__(self, exc_type, exc_val, exc_tb)

File object will be closed in the exit function for the FileType class


Convert input to an Int Range [0 ... 5]


Convert input to type dict


Convert input into valid sha256, or if file path is found as input all valid sha256 values in the file


Convert input into a valid URL


Cloc mixins are a simple way to inherit cli functionality to your class. Below is an example of a Version mixin. This enables a class to inherit a 'version' cmd. It will then look for the class attribute version and print it to the user.

class Version(object):
    """Version Mixin - class object for easily adding an version command to a class
        - echo the 'version' attribute if it exists

    def __call__(self):
        return self.version_cmd

    def version_cmd(self):
        """version mixin command"""
        echo(cls=self, attribute='version', color='blue')

The below mixins are currently offered by cloc.

cloc.mixins.Echo(self, *args, **kwargs)

Echo Mixin - class object for easily adding an echo command to a class - echo value of attributes by name

cloc.mixins.List(self, *args, **kwargs)

List Mixin - class object for easily adding an list command to a class - list attributes and values of the tied class

cloc.mixins.Version(self, *args, **kwargs)

Version Mixin - class object for easily adding an version command to a class - echo the 'version' attribute if it exists


Viewsets are classes of commands that can be inherited into other classes. For example if you have a class that you want to be able to query information from but not write to, you could use a ReadOnlyViewset that only gives the user the option the print and list attributes from the class.

A viewset can also be made into a Queryset if the GrpViewset is inherited and the queryset attribute is set. This then enables a user to override methods to retrieve data for the cli interface. A queryset could connect to a database to retrieve information for the user based on defined commands.

Viewsets and Querysets become very useful in large CLI applications.

cloc.viewsets.GrpViewset(self, *args, **kwargs)

A base Viewset that does not have any commands by default. The GrpViewset contains the queryset attribute and can be set for overloading data retrieval.

cloc.viewsets.ReadOnlyViewset(self, *args, **kwargs)

Read only viewset echo (print attribute by name) list (print all attribute names and values) version(print the current version of the Viewset based on the version attribute)

cloc.viewsets.ReqSessionViewset(self, *args, session: requests.sessions.Session = None, max_retries: int = 3, pool_connections: int = 16, pool_maxsize: int = 16, raise_exception: bool = True, **kwargs)

Requests Session Viewset get (a cli cmd for session.get)

Helper Functions

cloc.utils.echo(message: Union[str, tuple, list, dict]= None, cls: object= None, attribute: str= None, list_delimiter: str = '\n', show_type: bool = False, indent: int= 4, color: str= None)

Formats and colors a message, or class attribute.

  • Pretty print tuple, list, and dict objects
  • Customize the list delimiter and indent level for pretty print
  • Color output
  • Print the type for the output

prints the formatted string

cloc.utils.trace(message:str, exception: Exception= None, raise_exception: bool= False, exit_code: int= 0, color: str= None)

Formats and colors the output of a simplified traceback message.

  • Utilizes the echo util for formatted and colored output
  • Can accept and raise any type of Exception with the message
  • Give an exit code to return with if exception is not raised

prints the formatted string and calls sys.exit(exit_code) or raises the given Exception (Assert) used if none given

cloc.utils.listattrs(cls: object, verbose:bool=False)

List the attributes and values of a given class object. If verbose is True, python defined attributes will also be included.

  • Utilizes the echo util for formatted output

Advanced Usage Examples

Using a viewset

from cloc import grp
from cloc.viewsets import ReqSessionViewset

def cli():
    """requests session cli"""

session_viewset = ReqSessionViewset(raise_exception=False)


if __name__ == '__main__':

The get command is implemented by the ReqSessionViewset and does not have to be defined

$ python get
  "userId": 1,
  "id": 1,
  "title": "delectus aut autem",
  "completed": false

Project details

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Files for cloc, version 0.2.5
Filename, size File type Python version Upload date Hashes
Filename, size cloc-0.2.5.tar.gz (22.9 kB) File type Source Python version None Upload date Hashes View

Supported by

Pingdom Pingdom Monitoring Google Google Object Storage and Download Analytics Sentry Sentry Error logging AWS AWS Cloud computing DataDog DataDog Monitoring Fastly Fastly CDN DigiCert DigiCert EV certificate StatusPage StatusPage Status page