[Level 3] Use cmd module to create python cli program.
How to use cmd module to create python cli program?
Please refer to the following sample:
$ cat ./cli.py
$ cat ./main.py
$ cat ./system.py
$ ./cli.py
Wish this helps.
regards,
Stanley Huang
Please refer to the following sample:
$ cat ./cli.py
#!/usr/bin/python
import os, sys
from menu.CLI_main import CLI_main
###################################### main
if __name__ == '__main__':
cli=main("user","host")
cli.cmdloop()
$$ cat ./main.py
import cmd
class main(cmd.Cmd):
def __init__(self, user, host):
cmd.Cmd.__init__(self)
self.user = user
self.host = host
self.prompt = "%s@%s:%s> " % (user, host, "main")
def do_system(self, args):
from system import system
sub_cmd = system(self.user, host)
sub_cmd.cmdloop()
class main(cmd.Cmd):
def __init__(self, user, host):
cmd.Cmd.__init__(self)
self.user = user
self.host = host
self.prompt = "%s@%s:%s> " % (user, host, "main")
def do_system(self, args):
from system import system
sub_cmd = system(self.user, host)
sub_cmd.cmdloop()
def help_system(self):
print "system sub menu of cli"
def do_show(self, args):
print "show"
def do_quit(self, args):
return True
$def do_quit(self, args):
return True
$ cat ./system.py
import cmd
class system(cmd.Cmd):
def __init__(self, user, host):
cmd.Cmd.__init__(self)
self.user = user
self.host = host
self.prompt = "%s@%s:%s> " % (user, host, "system")
def do_show(self, args):
print "show"
def do_quit(self, args):
return True
$def __init__(self, user, host):
cmd.Cmd.__init__(self)
self.user = user
self.host = host
self.prompt = "%s@%s:%s> " % (user, host, "system")
def do_show(self, args):
print "show"
def do_quit(self, args):
return True
$ ./cli.py
user@host:main> help
Documented commands (type help):
========================================
system
Undocumented commands:
======================
help show quit
user@host:main> system
user@host:system> quit
user@host:main> quit
$Documented commands (type help
========================================
system
Undocumented commands:
======================
help show
user@host:main> system
user@host:system> quit
user@host:main> quit
Wish this helps.
regards,
Stanley Huang
Comments
Post a Comment