Package: cloc
clocCommand Line Object ChainingCommand line framework for making simple and complex command line applications.Easily create stand alone commands or nested groups of commandsDefine and connect commands with class objectsInherit and create viewsets of commands to be able to reuse large nested groups in other cli applicationsUse mixin commands to quickly add pre defined commands to your cliGroups of commands can be found from any class that has defined acloc.core.BaseCmdInstallationDocumentationCmd and GrpParameters - Arg, Opt, and FlgClassescloc.core.BaseCmdBaseCmd.valuesBaseCmd.paramsBaseCmd._parseBaseCmd.create_helpBaseCmd._print_helpBaseCmd.create_regex_patternsBaseCmd.get_valuescloc.core.CmdCmd.fnCmd.dataclassCmd.new_dataclass_cmdCmd.create_regex_patternsCmd.get_valuescloc.core.GrpGrp.commandsGrp.invokeGrp.cmdlGrp.add_commandGrp.get_commandDecoratorscloc.decorators.cmdcloc.decorators.grpcloc.decorators.argcloc.decorators.optcloc.decorators.flgTypescloc.types.BaseTypeBaseType.callcloc.types.Choicescloc.types.DateTypecloc.types.FileTypeFileType.exitcloc.types.IntRangeTypecloc.types.JsonTypecloc.types.Sha256Typecloc.types.UrlTypeMixinscloc.mixins.Echocloc.mixins.Listcloc.mixins.VersionViewsetscloc.viewsets.GrpViewsetcloc.viewsets.ReadOnlyViewsetcloc.viewsets.ReqSessionViewsetHelper Functioncloc.utils.echocloc.utils.tracecloc.utils.listattrsAdvanced Usage ExamplesViewset ExampleInstallationVirtual Environment is recommendedpip3installclocDocumentationCmd and GrpThe two core features (classes) of CLOC, command line object chaining, areCmdandGrp.ACmdclass 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 theCmdor being called by aGrp.AGrpclass object holds one to many actions to process when invoked. The actions can be aCmdor anotherGrp, but
only one action can be called at a time perGrp. The firstGrpwill receive the first command
line state,sys.argv[1:]. EveryGrpwill receive a command line state and will pass this state to the
next action. It is onGrponly to update the command line state.fromclocimportcmd,grp@grp('cli')defcli():"""cli group"""pass@cmd('hello-world')defhello_world():"""hello world function"""print('Hello World')cli.add_command(hello_world)cli()Grphelp structure. Usage will always begrpname (cmd|grp)Clicligroup

USAGE:CLINAME

Commands:|Name|Description||------------------------|----------------------------------------------------||hello-world|helloworldfunction|Parameters - Arg, Opt, and FlgCurrently parameters can only be given to aCmd.The three core parameters include:Arg- a named positional argument for the commandArg(name: str, type: Any = str, help: str = None)Opt- a named non-positional argument for the commandOpt(name: str, short_name: str, type: Any = str, default: Any= None, multiple: bool= False, 
      required: bool= False, help: str = None)Flg- a special version ofOptthat is always type bool and expects no valueFlg(name: str, short_name: str, help: str = None)Below is an extended greeting cmd from above without the grp.fromclocimportarg,cmd,flg,optfromcloc.typesimportIntRange@cmd('hello')@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')defhello(name:str,count:IntRange,no_repeat:bool):"""Simple program that greets NAME for a total of COUNT times."""for_incount:print(f'Hello{name!r}')ifno_repeat:breakif__name__=='__main__':hello()The below output is an example of a print message for the greeting cmd.HelloSimpleprogramthatgreetsNAMEforatotalofCOUNTtimes.

USAGE:helloNAME--count|-c[value]--no_repeat|-nrParameters:|Name|Short|Type|Help||------------------|--------|----------------|------------------------------------------------------||NAME||str|Thepersontogreet||--count|-c|cloc.IntRange|[default:1]Numberofgreetings:ex-c0,5OR-c5||--no_repeat|-nr|bool|[flag]Ifgiven,thegreetingwillnotrepeat|Classescloc.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:listThe values attribute is the list of arguments to be unpacked into the invoked function from the cmdBaseCmd.params:cloc.core.ParamsThe params attribute is the list of parameter objects defined for the cmdBaseCmd._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 invokedBaseCmd. This method is protected and should normally not be called.BaseCmd.create_help()The create_help method with create a formatted and colored help string using any params foundBaseCmd._print_help()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.BaseCmd.create_regex_patterns()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:CallableThe fn attribute is the defined function to run when cmd is invokedCmd.dataclass:objectThe dataclass attribute is an object to replaceselfwith if the cmd is defined inside a classCmd.new_dataclass_cmd(cls, name: str, fn: Callable, params: Params= None, hidden: bool= False, dataclass: object= None)ClassmethodThis class method will create a new Cmd that will have the dataclass attribute setCmd.create_regex_patterns()Create regex patterns for each opt and flg param to match against the command line state during get_valuesCmd.get_values(cmdl: list)Overloaded function from BaseCmd, this method will create the values to be unpacked intoCmd.fn.
If--helpis 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 theGrp.add_commandmethod.BaseCmd.invoke:strThe invoke attribute is user input from the command line and should match aCmd.nameinGrp.commandsBaseCmd.cmdl:listThe 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 stateThis 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. Settingdataclass = class that declared the commands.a dataclass Cmd is the magic to allow Cli Viewsets and QuerysetsBaseCmd.get_command(name: str)Find a Cmd by name and return the objectDecoratorsAs 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 objectcloc.decorators.grp(name:str = None, hidden:bool = False)Returns a new Grp objectcloc.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.paramscloc.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.paramscloc.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.paramsTypesNew types can be made to be used to convert the command line input. A new cloc type must inherit thecloc.types.BaseTypeand 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 -> BaseTypeBaseType.__call__(self, value: str)convert to new typeArgs:
        value {str} -- value to convertcloc.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.cloc.types.DateType(self)Convert input into a DateTime objectcloc.types.FileType(self)Convert input into a file object. The below example is thecloc.types.FileTypeimplementationclassFileType(BaseType):__name__='cloc.File'def__init__(self):# init should provide a base type, default to strsuper().__init__(io.TextIOWrapper)def__exit__(self,exc_type,exc_val,exc_tb):self.fobj.close()def__call__(self,filepath:str):ifnotos.path.exists(filepath):trace(f'Error:{filepath!r}does not  exists',TypeError)elifnotos.path.isfile(filepath):trace(f'Error:{filepath!r}is not a file',TypeError)self.fobj=open(filepath,'r')returnself.fobjFileType.__exit__(self, exc_type, exc_val, exc_tb)File object will be closed in the exit function for the FileType classcloc.types.IntRangeType(self)Convert input to an Int Range [0 ... 5]cloc.types.JsonType(self)Convert input to type dictcloc.types.Sha256Type(self)Convert input into valid sha256, or if file path is found as input all valid sha256 values in the filecloc.types.UrlType(self)Convert input into a valid URLMixinsCloc 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.classVersion(object):"""Version Mixin - class object for easily adding an version command to a class- echo the 'version' attribute if it exists"""def__call__(self):returnself.version_cmd@cmd('version')defversion_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 namecloc.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 classcloc.mixins.Version(self, *args, **kwargs)Version Mixin - class object for easily adding an version command to a class
- echo the 'version' attribute if it existsViewsetsViewsets 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 theGrpViewsetis 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 Functionscloc.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 objectsCustomize the list delimiter and indent level for pretty printColor outputPrint the type for the outputprints the formatted stringcloc.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 outputCan accept and raise any type of Exception with the messageGive an exit code to return with if exception is not raisedprints the formatted string and callssys.exit(exit_code)or raises the given Exception (Assert) used if none givencloc.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 outputAdvanced Usage ExamplesUsing a viewsetfromclocimportgrpfromcloc.viewsetsimportReqSessionViewset@grp('cli')defcli():"""requests session cli"""passsession_viewset=ReqSessionViewset(raise_exception=False)cli.add_command(session_viewset)if__name__=='__main__':cli()The get command is implemented by the ReqSessionViewset and does not have to be defined$pythonexample3.pygethttps://jsonplaceholder.typicode.com/todos/1{"userId":1,"id":1,"title":"delectus aut autem","completed":false}