简体   繁体   中英

Exiting to main level using nested interpreters and Cmd module in Python

I'm using the Python Cmd module on a program with multiple levels of nested interpreters. I'd like to be able to exit from an interpreter several levels down all the way back to the main loop. Here is what I've tried:

import cmd

class MainCmd(cmd.Cmd):
    def __init__(self):
        cmd.Cmd.__init__(self)
        self.prompt = "MAIN> "

    def do_level2(self, args):
        level2cmd = Level2Cmd()
        level2cmd.cmdloop()

class Level2Cmd(cmd.Cmd):
    def __init__(self):
        cmd.Cmd.__init__(self)
        self.prompt = "LEVEL2> "
        self.exit = False

    def do_level3(self, line):
        level3cmd = Level3Cmd(self.exit)
        level3cmd.cmdloop()
        return self.exit

class Level3Cmd(cmd.Cmd):
    def __init__(self, exit_to_level_1):
        cmd.Cmd.__init__(self)
        self.prompt = "LEVEL3> "
        self.exit_to_level_1 = exit_to_level_1

    def do_back_to_level_1(self, args):
        self.exit_to_level_1 = True
        return True

################################################

if __name__ == '__main__':
    MainCmd().cmdloop()

When I run the program, navigate to the LEVEL3 interpreter and type 'exit_to_level_1' I am returned only to level2. Help?

So it comes down to mutable vs. immutable types. There's a pretty thorough answer here . Basically, the bool self.exit is immutable; to pass it to another object and allow that object to change it, it needs to be wrapped in a mutable type.

We resoved this by using a dict:

self.context = {"exit": False}

... and passing the context to the subconsole. A list would have worked just as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM