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_” in scheme. When the user types something like “ “, the do_ is called and the parameters are passed as a single string. If a method returns True, the shell exits. We can define help docs by naming methods in “help_” scheme. do_EOF handles the “end of file” character. That’s this function is called when we press Ctrl+D on Linux shell. By default, pressing the enter key without any command executes the last command. We override this behaviour by re-defining the emptyline() method.
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") |
One reply on “Building Command Line Interface using Python”
Hello from Russia!
Can I quote a post in your blog with the link to you?