Name

cmdloop

Synopsis

c.cmdloop(intro=None)

Performs an entire interactive session of line-oriented commands. cmdloop starts by calling c .preloop( ), then outputs string intro (c .intro, if intro is None). Then c .cmdloop enters a loop. In each iteration of the loop, cmdloop reads line s with s =raw_input( c .prompt). When standard input reaches end-of-file, cmdloop sets s ='EOF‘. If s is not 'EOF', cmdloop preprocesses string s with s = c .precmd( s ), then calls flag = c .onecmd( s ). When onecmd returns a true value, this is a tentative request to terminate the command loop. Now cmdloop calls flag = c .postcmd( flag,s ) to check if the loop should terminate. If flag is now true, the loop terminates; otherwise another iteration of the loop executes. If the loop is to terminate, cmdloop calls c .postloop( ), then terminates. This structure of cmdloop is probably easiest to understand by showing Python code equivalent to the method just described:

def cmdloop(self, intro=None):
    self.preloop( )
    if intro is None: intro = self.intro
    print intro
    while True:
        try: s = raw_input(self.prompt)
        except EOFError: s = `EOF'
        else: s = self.precmd(s)
        flag = self.onecmd(s)
        flag = self.postcmd(flag, s)
        if flag: break
    self.postloop( )

cmdloop is a good example of the design pattern known as Template Method. Such a method performs little substantial work itself; rather, it structures and organizes calls to other methods. Subclasses may override the other methods, to define the details of class behavior ...

Get Python in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.