I have already developed class1.py, class2.py, etc. with functions implemented inside each class. e.g. Operator.py has add, minus, time, divide functions. How can I build a command line interface for these classes?
Also for this CLI, is it an infinite loop inside the main()
for interaction?
And how can the CLI give some feedback such as, suggesting the user for the next operation or to input right command or type --help
and check all the available commands, like the Bash shells?
Also it seems there is the optparse
module from Python. Are there some good, complete, or high quality samples showing how a CLI is built? I would like to take this chance to learn how to write a CLI program.
I have already developed several classes, and also a GUI to call the methods from these classes. Now I want to have a CLI, like the GUI, to use these classes. e.g. I have classes like CDContainer (with method like addCD, removeCD, etc), CD (with method like play, stop, pause), and I have a GUI that could be interacted. Now I want to have a CLI, which under the bash, I could run this CLI and call createCDContainer, addCD, removeCD commands.
If I use cmd
,
class CDContainerCLI(cmd.Cmd):
def do_CDContainer(self, line):
print "create CD container"
def do_addcd(self, line):
print "add cd into the container"
how do I add some options here? e.g., I want to addcd --track 3 --cdname thriller
.
I think --track 3 --cdname thriller
they are the 4 arguments for the addcd
function. How to implement that?
A command line interpreter allows the user to interact with a program using commands in the form of text lines. It was frequently used till the 1970's. However, in modern times many command line interpreters are replaced by graphical user interfaces and menu-driven interfaces.
Do one of the following: Click the Python Interpreter selector and choose Add New Interpreter. Press Ctrl+Alt+S to open the project Settings/Preferences and go to Project: <project name> | Python Interpreter. Click the Add Interpreter link next to the list of the available interpreters.
Create a file index. js in the root of the project. This will be the main entry of the CLI tool that will initialize the commands it will have. NOTE: If you are using Windows for development, make sure that the line end character is set to LF instead of CRLF or the tool will not work.
Derive from cmd.Cmd
, overriding the various methods as necessary.
Use the cmd module:
Other packages
You can also use various modules hosted at pypi that is built on top of cmd module
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With