Creating a command line interface with Python is pretty easy 🙂 Python has a built in module — “cmd” to assist you in building a command line interface of your application.
In this example, I have created a dummy shell that uses the os.system() call to execute a command in terminal. Here is the code explanations:
First, we import the modules required for the demo. Then, we create a subclass of the cmd.Cmd class. Then we define the commands by defining and naming methods in “do_
For a complete reference, please consult the python manual.
Here’s the source code of the program I wrote:
Type “shell date” or any other commands to try it out.
Type “help” to get help 🙂
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
import cmd import os class shell_cmd(cmd.Cmd): def do_shell(self, s): os.system(s) def emptyline(self): pass def help_shell(self): print "Type -> <shell> <command>" print "to execute the <command> in terminal" def help_help(self): print "Type -> <help> to see available commands" print "Type -> <help> <command> to get detailed doc" def help_exit(self): print "Type -> <exit> or press <ctrl+D> to terminate the shell" def help_EOF(self): print "Press <ctrl+D> to terminate the shell" def do_exit(self,s): return True def do_EOF(self,s): print "" return True shell = shell_cmd() shell.cmdloop("\n \n maSnun's python shell \n ---------- \n Type: <help> to get help \n ---------- \n Created by: maSnun :) \n https://masnun.com \n masnun@gmail.com\n ---------- \n") |