Examples
The examples can be found on github in the examples folder. You can go directly to the source file by clicking on the title of the example.
simple_cli.py
This is a very simple cli that takes input from stdin. It has a few sample commands that show a few basic features of the argparseDecorator.
simple_asyncio_demo.py
A very small sample to test using argparseDecorator in an asyncio context.
ssh_cli.py
is a more involved demo that shows how argparseDecorator can be used to create a CLI that can be accessed remotly via ssh.
Full Documentation
Example of running a argparseDecorator CLI in an asyncssh server.
It uses asyncssh to provide an ssh server and the Python prompt toolit to provide a rich terminal interface with code completion, colours and more.
Note
The ssh server is very basic and will accept any client connection. Use either in a closed environment (behind firewall) or add authentification as required.
This module has three main classes:
BaseCLI
contains all the low level code linking an argparseDecorator based CLI with the prompt toolkit. It also implements two commands that are probably useful for all ssh based cli’s:exit
to close the ssh connection from the remote end, andshutdown
to shut down the server from the remote end
This class can be subclassed to implement more commands without worrying about the details.
DemoCLI
is a small example CLI built on top ofBaseCLI
showcasing a few of the possibilities.SshCLIServer
contains all required code to start the SSH Server.
In addition to those three classes a few helpful functions are implemented to handle formatted output:
print_html()
to use some basic html formatting.print_error()
,print_warn()
andprint_info()
for color coded status messages. The colors used can be changes by modifying the suppliedstyle
dictionary.
- class BaseCLI
Bases:
object
Basic Command Line Interface for use with the PromptToolkitSSHServer
It contains all the low-level stuff to integrate it with a PromptToolkit SSH session (in the
cmdloop()
method)To add more commands subclass this base CLI, as shown in the
DemoCLI
class.Note
Subclasses must use the ArgParseDecorator from BaseCLI. Do not create a seperate instance. The BaseCLI instance is in the
BaseCLI.cli
class variable and can be accessed like this:class MyCLI(BaseCLI): cli = BaseCLI.cli ...
The other class variables
BaseCLI.intro
andBaseCLI.prompt
can be overwritten by subclasses.- cli = <argparsedecorator.argparse_decorator.ArgParseDecorator object>
The
ArgParseDecorator
used to decorate command methods.
- async cmdloop(ssh_session: PromptToolkitSSHSession) None
Handle an incoming SSH connection.
This is the entry point to start the CLI in the given SSH session. It will display a prompt and execute the user input in a loop until the session is closed, either by the remote end or by the ‘exit’ command.
This will be called from the ssh server for each incoming connection. There is no need to call it directly.
- Parameters
ssh_session – Session object
- property command_dict: Dict[str, Optional[Dict]]
A dictionary with all supported commands suitable for the PromptToolkit Autocompleter
- error_handler(exc: Exception) None
Prints any parser error messages in the <error> style (default: red)
Override this for more elaborate error handling.
- Parameters
exc – Exception containg the error message.
- async execute(cmdline: str) Any
Excecute the given command.
- Returns
‘exit’ to close the current ssh session, ‘shutdown’ to end the ssh server. All other values are ignored.
- async get_prompt_session() PromptSession
Start a new prompt session.
Called from
cmdloop()
for each new session.By default, it will return a simple PromptSession without any argument. Override to customize the prompt session.
- Returns
a new PromptSession object
- intro = '\nThis is a basic SSH CLI.\nType Ctrl-C to exit.\n'
Intro text displayed at the start of a new session. Override as required.
- prompt = '\n<green># </green>'
Prompt text to display. Override as required.
- async run_prompt(prompt_session: PromptSession) Any
Display a prompt to the remote user and wait for his command.
The default implementation uses only a comand name completer. Override to implement other, more advanced features.
- Returns
The command entered by the user
- property sshserver: SSHAcceptor
The SSH Server (actually asyncssh.SSHAcceptor) running this session. Must be set externally and is used for the
shutdown
command.
- class DemoCLI
Bases:
BaseCLI
Demo some features of the Python prompt toolkit
- cli = <argparsedecorator.argparse_decorator.ArgParseDecorator object>
The
ArgParseDecorator
used to decorate command methods.
- intro = "\nThis is a sample CLI to demonstrate the use of the <i>argparseDecorator</i> Library with a SSH Server.\n\nUse 'help' for all available commands.\nPress <b>Ctrl-C</b> to close connection.\n"
Intro text displayed at the start of a new session. Override as required.
- async progress(ticks: int | argparsedecorator.annotations.ZeroOrOne = 50) None
Show a progress bar. :param ticks: Number of ticks in the progressbar. Default is 50
- prompt = '\n<green># </green>'
Prompt text to display. Override as required.
- class SshCLIServer(cli: BaseCLI, port: int = 8222, keyfile: Optional[str] = None)
Bases:
object
Implementation of the asyncssh SSHServer
- Parameters
cli – The CLI to use for incoming ssh connections
port – The port number to use for the server. Defaults to 8222
keyfile – Location of the private key file for the server. Defaults to ‘.ssh_cli_key’ in the user home directory. A new key will be generated if the keyfile does not exist.
- async close()
- async run_server() None
Start the SSH server and run until the server is shut down.
- Returns
Reference to the running server.
- property ssh_server: SSHAcceptor
- print_error(text: str) None
Print an error message.
By default, this message is printed in red. As the text is printed via
print_html()
it can include HTML tags for further formatting.- Parameters
text – The message to be printed.
- print_html(text: str) None
Format and print text containing HTML tags.
Note
The prompt toolkit HTML to ANSI converter supports only a few basic HTML tags. See here for more info.
- Parameters
text – A string that may have html tags.
- print_info(text: str) None
Print an info message.
By default, this message is printed in grey. As the text is printed via
print_html()
it can include HTML tags for further formatting.- Parameters
text – The message to be printed.
- print_warn(text: str) None
Print a warning message.
By default, this message is printed in orange. As the text is printed via
print_html()
it can include HTML tags for further formatting.- Parameters
text – The message to be printed.
- style = <prompt_toolkit.styles.style.Style object>
Some basic styles. Styles can be used as html tags, e.g.:
<error>An error message</error>
Useful for the
print_html()
function.