Welcome, guest | Sign In | My Account | Store | Cart

Class to make easy, cration of command line interfaces.

Also can be used to try classes manually.

Python, 208 lines
  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
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
    #Covered by GPL V2.0


    import sys
    try:
        import readline 
    except:
        pass

    class Console:
        def __init__(self,prompt):
            self.prompt=prompt
            self.banner=""
    
            self.commands={}
            self.commandSort=[]
    
    
            for i in dir(self):
                if "CMD_"==i[:4]:
                    cmd=i.split("CMD_")[1].lower()
                    self.commands[cmd]=getattr(self,i)
                    try:
                        self.commandSort.append((int(self.commands[cmd].__doc__.split("|")[0]),cmd))
                    except:
                        print ("Docstring for command must have the following format: '(number)|(string)[|(string)]+' # Two or more strings")
            
            self.commandSort.sort()
            self.commandSort=[i[1] for i in self.commandSort]
    
            #######   DEFAULT VARS (begins with CFG_)  ###########################
            self.CFG_DEBUG=False
    
            self.configvars={}
            for i in dir(self):
                if "CFG_"==i[:4]:
                    var=i.split("CFG_")[1]
                    self.configvars[var]=i
    
        def setBanner(self,banner):
            self.banner=banner
    
        def run(self):
            print self.banner
            while True:
                try:
                    command=raw_input(self.prompt)
                    self.execCommand(command)
                except KeyboardInterrupt:
                    break
                except EOFError:
                    break
                except Exception,a:
                    self.printError (a)
    
            print ("\r\n\r\nBye!...")
            sys.exit(0)
    
    
        def printError(self,err):
            sys.stderr.write("-- Error: %s\r\n" % (str(err),))
            if self.CFG_DEBUG:
                pass
    
        def execCommand(self,cmd):
            words=cmd.split(" ")
            words=[i for i in words if i]
            if not words:
                return
            cmd,parameters=words[0].lower(),words[1:]
    
            if not cmd in self.commands:
                raise Exception("Command '"+cmd+"' not found. Try 'help'\r\n")
    
            self.commands[cmd](*parameters)
    
        ######## DEFAULT COMMANDS (begins with CMD_) ################
    
        def CMD_help(self,*args):
            '''-3|help|Show's help'''
            print (self.banner)
    
    
            alldata=[]
            lengths=[]
    
            for i in self.commandSort:
                alldata.append(self.commands[i].__doc__.split("|")[1:])
    
            for i in alldata:
                if len(i) > len(lengths):
                    for j in range(len(i)-len(lengths)):
                        lengths.append(0)
    
                j=0
                while j<len(i):
                    if len(i[j])>lengths[j]:
                        lengths[j]=len(i[j])
                    j+=1
    
            print ("Help")
            print ("-"* (lengths[0]+lengths[1]+4))
            print 
    
            for i in alldata:
                print (("%-"+str(lengths[0])+"s  - %-"+str(lengths[1])+"s") % (i[0],i[1]))#lengths))
                if len(i)>2:
                    for j in i[2:]:
                        print (("%"+str(lengths[0]+9)+"s* %s") % (" ",j))
                    print 
            print
    
    
        def CMD_config(self,*args):
            '''-2|config|Show config variables'''
            print ("Configuration variables\r\n"+"-"*79)
            for i,j in self.configvars.items():
                value=self.parfmt(repr(getattr(self,j)),52)
                print ("| %20s | %52s |" % (i,value[0]))
                for k in value[1:]:
                    print ("| %20s | %52s |" % ("",k))
                if len(value)>1:
                    print("| %20s | %52s |" % ("",""))
    
            print ("-"*79)
    
            print 
    
        def parfmt(self,txt,width):
            res=[]
            pos=0
            while True:
                a=txt[pos:pos+width]
                if not a:
                    break
                res.append(a)
                pos+=width
    
            return res
            
    
        def CMD_set(self,*args):
            '''-1|set [variable_name] [value]|Set configuration variable value|Values are python expressions: 1, True, "How are you".lower()'''
            value=" ".join(args[1:])
    
            if args[0] not in self.configvars:
                raise Exception("Variable %s doesn't exist" % (args[0]))
    
            setattr(self,"CFG_"+args[0],eval(value))


    ################# CALCULATOR EXAMPLE ######################


    class calculator(Console):
        def __init__(self):
            self.CFG_var1=28                     # Config variable before call superclass constructor
            Console.__init__(self,prompt="Calculator Cli: ") # Specify the prompt

        def CMD_sum(self,*args):
            '''5|sum val1 val2|Makes the sum of val1 and val2'''  # Docstring format: Preference order in help | command syntax | help string
            print int(args[0])+int(args[1])
 
        def CMD_sub(self,*args):
            '''6|sub val1 val2|Makes the substraction of val1 and val2'''
            print int(args[0])-int(args[1])

 
    a=calculator()
    a.run()

    ############################# DEMO ##############################################

    $ python example.py

    Calculator Cli: help

    Help
    ----------------------------------------------------------------------

    help                         - Show's help                        
    config                       - Show config variables              
    set [variable_name] [value]  - Set configuration variable value   
                                        * Values are python expressions: 1, True, "How are you".lower()

    sum val1 val2                - Makes the sum of val1 and val2     
    sub val1 val2                - Makes the substraction of val1 and val2

    Calculator Cli: sum 4 9
    13
    Calculator Cli: sub 5 8
    -3
    Calculator Cli: config
    Configuration variables
    -------------------------------------------------------------------------------
    |                DEBUG |                                                False |
    |                 var1 |                                                   28 |
    -------------------------------------------------------------------------------

    Calculator Cli: set var1 59
    Calculator Cli: config
    Configuration variables
    -------------------------------------------------------------------------------
    |                DEBUG |                                                False |
    |                 var1 |                                                   59 |
    -------------------------------------------------------------------------------

    Calculator Cli:

1 comment

Larry Hastings 13 years, 11 months ago  # | flag

How is this better than the "cmd" library that ships with Python?

Created by Carlos del Ojo on Wed, 26 May 2010 (GPL)
Python recipes (4591)
Carlos del Ojo's recipes (2)

Required Modules

  • (none specified)

Other Information and Tasks