Switching between cmd.CMD instances

Josh English Joshua.R.English at gmail.com
Thu Apr 3 23:40:44 EDT 2014


On Wednesday, April 2, 2014 4:33:07 PM UTC-7, Jason Swails wrote:

> From there, you can implement a method interface in which the child Cmd subclasses can call to indicate to BossCmd that do_exit has been called and it should quit after the child's cmdloop returns.  So something like this:
>
> 

Hey, yeah. My previous responses didn't show up, or are delayed, or something.

Thank you, yes. This advice helped and rooting around the source code I realized that the Cmd.cmdqueue attribute is the easy way out:

import cmd

class BossCmd(cmd.Cmd):
    def __init__(self):
        cmd.Cmd.__init__(self)
        self.prompt = 'Boss>'
        self.exit_called_from_minion = False
        self.minions = {}

    def add_minion(self, name, cmder):
        self.minions[name] = cmder

    def do_exit(self, line):
        return True

    def postloop(self):
        print "I mean it. I'm done"

    def postcmd(self, stop, line):
        # check if minion called for exit
        if self.exit_called_from_minion:
            stop = True
        return stop

    def do_submission(self, line):
        if line:
            self.minions['submission'].onecmd(line)
        else:
            self.minions['submission'].cmdloop()

    def do_story(self, line):
        if line:
            self.minions['story'].onecmd(line)
        else:
            self.minions['story'].cmdloop()

class SubmissionCmd(cmd.Cmd):
    def __init__(self, master = None):
        cmd.Cmd.__init__(self)
        self.prompt = 'Submission>'
        self.master = master
        if self.master:
            self.master.add_minion('submission', self)

    def do_done(self, line):
        return True

    def do_exit(self, line):
        self.master.exit_called_from_minion = True
        return True

    def do_story(self, line):
        if line:
            self.master.minions['story'].onecmd(line)
        else:
            self.master.cmdqueue.append('story {}'.format(line))
            return True


class StoryCmd(cmd.Cmd):
    def __init__(self, master=None):
        cmd.Cmd.__init__(self)
        self.prompt = 'Story>'
        self.master=master
        if self.master:
            self.master.add_minion('story', self)

    def do_done(self, line):
        return True

    def do_exit(self, line):
        elf.master.exit_called_from_minion = True
        return True

    def do_submission(self, line):
        if line:
            self.master.minions['submission'].onecmd(line)
        else:
            self.master.cmdqueue.append('submission {}'.format(line))
            return True

Boss = BossCmd()
Sub = SubmissionCmd(Boss)
Story = StoryCmd(Boss)

Boss.cmdloop()
----

This gives me a flexible framework to bounce between Cmd instances at will, and quit the program from anywhere.

Josh



More information about the Python-list mailing list