Switching between cmd.CMD instances

Jason Swails jason.swails at gmail.com
Wed Apr 2 19:33:07 EDT 2014


On Wed, Apr 2, 2014 at 1:03 AM, Josh English <Joshua.R.English at gmail.com>wrote:

> I have a program with several cmd.Cmd instances. I am trying to figure out
> what the best way to organize them should be.
>
> I've got my BossCmd, SubmissionCmd, and StoryCmd objects.
>
> The BossCmd object can start either of the other two, and this module
> allows the user switch back and forth between them. Exiting either of the
> sub-command objects returns back to the BossCmd.
>
> I have defined both a do_done and do_exit method on the sub-commands.
>
> Is it possible to flag BossCmd so when either of the other two process
> do_exit, the BossCmd will also exit?
>

I have an app that also has a number of cmd.Cmd subclasses to implement
different interpreter layers.  I haven't needed to implement what you're
talking about here (exiting one interpreter just drops you down to a
lower-level interpreter).  However, it's definitely possible.  You can have
your SubmissionCmd and StoryCmd take a "master" (BossCmd) object in its
__init__ method and store the BossCmd as an instance attribute.

>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:

class SubmissionCmd(cmd.Cmd):
    # your stuff
    def __init__(self, master):
        cmd.Cmd.__init__(self, *your_args)
        self.master = master

    def do_exit(self, line):
        self.master.child_has_exited()

class BossCmd(cmd.Cmd):
    # your stuff
    def child_has_exited(self):
        self.exit_on_return = True # this should be set False in __init__

    def do_submit(self, line):
        subcmd = SubmissionCmd(self)
        subcmd.cmdloop()
        if self.exit_on_return: return True

Untested and incomplete, but you get the idea.

HTH,
Jason

-- 
Jason M. Swails
BioMaPS,
Rutgers University
Postdoctoral Researcher
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20140402/7ce31fca/attachment.html>


More information about the Python-list mailing list