cmd.Cmd your customized Repl in Python

How can we interact with my written program? The user interface is a wide wide topic. There are a lot of ways:
The terminal ‘./my-program some-parameters’
The graphical user interface (GUI)
The web interface
There are a lot of variants between these. I prefer in a lot of cases the terminal. Maybe because I raised up in the time of dos. Yes the time before windows 3.1.
In python there is a really nice class to create interactive programs with the class cmd.Cmd
.
from cmd import Cmd
class HelloWorld(Cmd):
def __init__(self):
super().__init__()
self.name = "world"
def do_name(self, args):
"set your name"
self.name = args
print(f"Your name {self.name} is set.", file=self.stdout)
def do_hello(self, args):
"say hello"
print(f"Hello, {self.name}", file=self.stdout)
if __name__ == "__main__":
HelloWorld().cmdloop()
This is a really flexible and hacky interface for python.
Let’s give you an example:
(Cmd) hi
*** Unknown syntax: hi
(Cmd) help
Documented commands (type help <topic>):
========================================
hello help name
(Cmd) name Peter
Your name Peter is set.
(Cmd) hello
Hello, Peter
(Cmd) help name
set your name
(Cmd) help hello
say hello
This is just easy. If a function return True the loop ends. That’s easy and you can create some really nice interfaces. I am working on a system to load other repls as modules, so you can write a lot of cool stuff just to interact.
Try the python program yourself and change it like you want.
Subscribe to my newsletter
Read articles from Adrian directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
