cmd2nest module¶
Command parser, extending cmd, cmd2 to nested sub-commands etc.
- usage:
Usage: import cmd2nest, subclass Cmd, TopCmd & SubCmd and use like cmd(2).
Module author: Michael S. Chapman <chapmanms@missouri.edu>
- Authors:
Michael S. Chapman <chapmanms@missouri.edu>
- Version:
1, Nov 26, 2024
Cmd should be subclassed and extended with methods to be available at all command nesting levels. Example: ProgCmd.
TopCmd should be subclassed and extended with methods to be available only at the top level. Example ProgTopCmd.
SubCmd should be subclassed and extended for each nesting of sub-commands. Example ProgSubCmd.
Changed in version v1.0.0a: 10/25/20 Fortran operators cmd2 v1.3 dependence on pyparsing introduces an incompatibility when command arguments are criteria for Atoms.Selection that contain ‘|’ or ‘>’. These can now be avoided with synonym Fortran-like operators that are interpreted in Atoms.Selection.select(). Old input scripts will need editing, replacing ‘|’ with .or. (or ‘^’ for XOR), ‘>’ with .gt. and ‘>=’ with .ge..
Warning
Redirection and piping. cmd2 v1.3 now interprets ‘>’ and ‘|’ as redirection and piping. Errors caused by use of these symbols in command-line selection expressions are not trapped by cmd2, so programs cannot give useful diagnostics. Atoms.Selection now supports Fortran synonyms of the operators as a as a workaround, but old input scripts will have to be updated. Further information is provided at https://cmd2.readthedocs.io/en/latest/features/redirection.html. Note that setting Cmd.allow_redirect=False merely ignores the redirection, but the rest of the command is already lost. This issue with cmd2 has been known since 2017, and has not been addressed due to challenges in refactoring pyparsing on which cmd2 now depends.
Changed in version v1.0.0: 09/25/20 upgrade to python v3.6
optparse deprecated, requiring use of @with_argparser decorators, and add_argument() calls on unique Argparser instances, and changed do_xxx() arguments.
see https://cmd2.readthedocs.io/en/latest/features/argument_processing.html
upgrade from cmd2 v0.8 to v1.3 - major changes to api, objects etc..
with the sub-classing etc. more changes may be needed.
deprecated commands load (do_load())
Changed in version v0.3.9: 06/05/13 relative to cmd2: * Supports nested command structure (subcommands). * Calling program objects can be added into the namespace for py commands. * Help options added for verbosity & scope (command to whole program). * Interpretation of commands entered on the program command line is now compatible with main programs use of argparse, optparse or no parser. (Internal workings of cmd2 still dependent on optparse.)
Changed in version 05/04/13: relative to cmd_extensions: upgrade to cmd2; nested commands.
Note
cmd2 may have an undocumented requirement that loaded files (including initial_commands) end with an EOF command. A work-around is implemented, adding an EOF if not in the last line.
Changed in version 8/13/10: start
Warning
Suspect that there is a maximum command line length of approaching 256 characters. Some failures that look like it might be dropping the 1st characters of longer strings.
Error
alias and macro have sub-commands, such as list, delete… . I have not yet managed to get this to work, even in simple example scripts. At the moment, this looks like a problem with cmd2, but I have not persisted as not central to PaStO.
Todo
09/30/20 - continue to check overridden Cmd methods as there were breaking changes between cmd2 v0.6.4 and v1.3 - likely a source of error.
Todo
09/30/20 - with cmd2 v1.3 comes support of dynamic commands (https://cmd2.readthedocs.io/en/latest/features/modular_commands.html). This could be an alternative to nesting where: (1) commands with daughters cause the current set to be saved and switched dynamically (during program execution) with the sub-commands (only) now visible until a “done” command, and (2) simplified structure in which all command control can be gathered together with call-out of the tasks. Challenges might include names spaces if: (a) want to inherit commands from modules used by several programs; (b) invoking tasks in other modules, and needing to worry about names spaces for py commands.
Todo
cmd2.Cmd.do_xxx(self, args) are now returning args as a modified argparse.Namespace object instead of a dict (cmd2 v0.6). Can no longer call other methods with **args named arguments. Have to convert using Q.Namespace.asdict(args). Needs to be propagated throughout the code base.
- class cmd2nest.Cmd(tasks=None, prompt=None, initial_commands=None, py_locals={'my': None}, register=True, parser=None)¶
Bases:
Cmd
Parser for terminal command input.
Processes commands from initial_commands, then command-line, then stdin.
Designed to be the base-class of other classes in the module, and the one direct sub-class of cmd2.Cmd, adding methods that should be available to all (nested) sub-classes.
This should be sub-classed, by copying & renaming the template class ProgCmd(), adding do_* and help_* methods. For multi-level command structures, subclasses of Cmd should contain only methods accessible at all levels, using sub-classes of TopCmd and SubCmd for methods that should be restricted to top level or subcommands respectively.
Shell that merely invokes task methods from a corresponding Control class. (Separation of the parser from the methods should facilitate alternative user-control interfaces.)
Extends the base class with parameters tasks, initial_commands, prompt, py_locals and register to: (a) associate command w/ a Task object, and provide py access to its namespace, (b) capture startup commands, (c) support nested sub-commnds with change in prompt.
Changed in version relative: to cmd_extensions, a number of commands are deprecated:
exec <command> & EXEC <command> are replaced by py <command>. There are currently no plans to support the global namespace of EXEC, but haven’t needed it.
cmd_file <FILE> is replaced by load <FILE>, @<FILE> etc.
echo <comment> is replaced by py print “comment” or # comment
Note
no attempt is made to import ‘option’ into namespace for py commands. Other objects will need py from module import object before using them.
Todo
(possibly) mechanism to automatically import other objects.
Todo
make sure that there is a way of modifing atom attributes.
Todo
refactored do_test when I have an example to play with.
Todo
add kwargs pass-through to provide full support of other cmd2.Cmd parameters.
Warning
cmd2 does not provide a means of escaping special symbols within arguments or options. Function unquote allows the rest of the command line (following options) to be enclosed in quotes - so partial support.
Changed in version ?: echo’s default is changed to True if not terminal-bound output i.e. redirected to log (but does not work within eclipse IDE).
- Parameters:
tasks (Control|NoneType) – class instance that defines methods to be called. (Reference will also be bound to ‘my’, so that ‘py’ commands can reference tasks.attribute as my.attribute rather than self.task.attribute.)
prompt (str or NoneType) – defaults to program basename.
initial_commands (str) – file(s) of commands to run before interactive loop at the top level, and before any command-line commands.
py_locals (dict) – objects added to the local namespace in the python interpreter invoked by ‘py’ commands.
register (bool) – keep object reference for setting of global parameters.
parser (ArgumentParser (argparse)) – to which -t / –test option will be added for cmd2 regression testing. Should only be used once / program.
- ancestory(include_self=True)¶
Iterator that climbs through parentage, returning Cmd objects.
- base_keywords = ['_relative_run_script', 'alias', 'edit', 'eof', 'help', 'history', 'macro', 'parrot', 'py', 'quit', 'run_pyscript', 'run_script', 'set', 'shell', 'shortcuts', 'test']¶
- children¶
- Var:
SubCommand instances called from this object.
- do_help(args)¶
Document commands.
Overrides cmd2.do_help(), adding –long, –recursive options.
Todo
deprecate option descend & clean up code.
- do_parrot(args)¶
toggle or set command echoing (for log file).
- do_set(args: Namespace) None ¶
Set a settable parameter or show current settings of parameters
- do_test(args)¶
Run a program developer’s test.
- help_parser = ArgumentParser(prog='sphinx-build', usage=None, description='List available commands or help for one or all commands', formatter_class=<class 'argparse.HelpFormatter'>, conflict_handler='error', add_help=True)¶
- instances = []¶
- Var:
list of instances (for setting global attributes).
- old_cmdloop()¶
Wrapper for _cmdloop() that extends cmd.cmdloop()
Deprecated since version 1.0.0: 09/30/20 This is a stripped-down version from cmd2 v0.6.4 (https://github.com/5monkeys/cmd2/blob/master/cmd2.py), but cmd2 v1.3 has more functionality. Think that need to return to the cmd2 version which will be inherited.
- old_do_load(arg=None)¶
Runs script of command(s) from a file or URL.
Overrides cmd2.do_load() by using cmd2.cmdqueue to support traversing between nested child / parent Cmd instances. This is different from the implementation in the base class.
Deprecated since version 1.0.0: 10/3/20, as cmd2 v0.9.13 deprecated support for cmdqueue(). Nearest equivalent is cmd2 run_script, which replaced load in cmd2 v0.9.15. This is not expected to support traversing nested Cmd instances. Support of this functionality would require a new approach without cmdqueue. Past use of the load command has been minimal, so not a priority.
- onfailure(cmd)¶
Attempt at learning how to trap exceptions, but not working.
- parent¶
- Var:
Command instance from which this instance created. None for top level.
- parrot_parser = ArgumentParser(prog='sphinx-build', usage=None, description='Echo commands (or not)', formatter_class=<class 'argparse.HelpFormatter'>, conflict_handler='error', add_help=True)¶
- postloop()¶
Hook method executed once when the cmdloop() method is about to return.
- preloop()¶
Run at start of cmdloop().
Warning
self.initial_commands set to None to avoid recursive call.
Changed in version ?: new implementation relative to cmd2 to be polymorphic for initial_commands open file(s) or file name(s).
Changed in version ?: relative to cmd2, adds EOF command at end if absent.
Changed in version v1.0.0: (10/3/20) cmdqueue has been deprecated in cmd2 v.0.9; try relying on startup_commands in super().Cmd.__init__ for execution of an initial script file, dropping support for multiple files. Changes made here without testing.
- set_description = "Set a settable parameter or show current settings of parameters\nCall without arguments for a list of all settable parameters with their values.\nCall with just param to view that parameter's value."¶
- set_parser = ArgumentParser(prog='sphinx-build', usage=None, description=None, formatter_class=<class 'argparse.HelpFormatter'>, conflict_handler='error', add_help=True)¶
- set_parser_parent = ArgumentParser(prog='sphinx-build', usage=None, description="Set a settable parameter or show current settings of parameters\nCall without arguments for a list of all settable parameters with their values.\nCall with just param to view that parameter's value.", formatter_class=<class 'argparse.HelpFormatter'>, conflict_handler='error', add_help=False)¶
- test_parser = ArgumentParser(prog='sphinx-build', usage=None, description='Run a test (program development only).', formatter_class=<class 'argparse.HelpFormatter'>, conflict_handler='error', add_help=True)¶
- undocumented = ('EOF', 'eof', 'exit', 'q', 'quit', 'test')¶
- class cmd2nest.Documentation¶
Bases:
object
User-level documentation for imports.
- property general¶
Generic documentation for import into other modules.
- class cmd2nest.ProgCmd(tasks=None, initial_commands=None, py_locals={}, parser=None)¶
Bases:
Cmd
Commands available at all levels for Program Prog.
Processes commands from initial_commands, then command-line, then stdin.
This is a template to be copied to developer’s program, “Prog”
- Parameters:
tasks (Control|NoneType) – class instance that defines methods to be called.
initial_commands (str or list of str) – file(s) of commands to run before interactive loop at the top level, and before any command-line commands.
py_locals (dict) – objects added to the local namespace in the python interpreter invoked by ‘py’ commands.
parser (ArgumentParser (argparse) or OptionParser (optparse)) – to which -t / –test option will be added for cmd2 regression testing. Should only be used once / program.
- class cmd2nest.ProgSubCmd(parent, prompt='sub-command')¶
-
Parser for sub-menu terminal command input.
This is a template to be copied to developer’s program, “Prog”
- Parameters:
parent (TopCmd) – Cmd object whence this call was made, usually self.
prompt (str) – concatonated with the parent’s prompt.
- do_callee(arg)¶
Call a sub-command.
- help_callee()¶
- class cmd2nest.ProgTopCmd(tasks=None, initial_commands=None, py_locals={}, parser=None)¶
-
Top-level commands for Program Prog.
This is a template to be copied to developer’s program, “Prog”
- Parameters:
tasks (Control|NoneType) – class instance that defines methods to be called.
initial_commands (str or list of str) – file(s) of commands to run before interactive loop at the top level, and before any command-line commands.
py_locals (dict) – objects added to the local namespace in the python interpreter invoked by ‘py’ commands.
parser (ArgumentParser (argparse) or OptionParser (optparse)) – to which -t / –test option will be added for cmd2 regression testing. Should only be used once / program.
- do_caller(arg)¶
Call a sub-command object.
- help_caller()¶
- class cmd2nest.Statekeeper(obj, attribs)¶
Bases:
object
Storage / recovery of an object’s attributes.
This was in cmd2 v0.6.4, but not in v1.3, so added for legacy support (https://github.com/5monkeys/cmd2/blob/master/cmd2.py)
- restore()¶
- save()¶
- class cmd2nest.SubCmd(parent, prompt='sub-command')¶
Bases:
Cmd
Parser for sub-menu terminal command input.
SubCmd should be sub-classed, by copying & renaming the template class ProgSubCmd(), adding do_* and help_* methods for each cascading level of commands.
Todo
Inheritance of “state”. How to get from parent? Should changes of state be mirrored back up to parent?
- Parameters:
parent (TopCmd) – Cmd object whence call is being made, usually self.
prompt (str) – concatonated with the parent’s prompt.
- do_done(args)¶
Safe sub-menu exit, returning to higher level command.
- class cmd2nest.TestControl(option=None)¶
Bases:
object
- class cmd2nest.TopCmd(tasks=None, initial_commands=None, py_locals={}, parser=None)¶
Bases:
Cmd
Parser for top-level terminal command input.
Processes commands from initial_commands, then command-line, then stdin.
This should be sub-classed, by copying & renaming the template class ProgTopCmd(), adding do_* and help_* methods.
For multi-level commands structure, programs should sub-class Cmd, TopCmd and SubCmd.
- Parameters:
tasks (Control|NoneType) – class instance that defines methods to be called.
initial_commands (str or list of str) – file(s) of commands to run before interactive loop at the top level, and before any command-line commands.
py_locals (dict) – objects added to the local namespace in the python interpreter invoked by ‘py’ commands.
parser (ArgumentParser (argparse) or OptionParser (optparse)) – to which -t / –test option will be added for cmd2 regression testing. Should only be used once / program.
- do_exit(args)¶
Safe program exit from top level not subcommands.
- cmd2nest.unquote(text)¶
Strip paired single or double quotes from ends of string.
Do nothing if not string or not quoted.