简体   繁体   English

使用Python中的嵌套解释器和Cmd模块退出到主级别

[英]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. 我在具有多级嵌套解释器的程序上使用Python Cmd模块。 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. 当我运行程序时,导航到LEVEL3解释器并输入'exit_to_level_1'我只返回到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; 基本上,bool self.exit是不可变的; 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: 我们通过使用dict来恢复它:

self.context = {"exit": False}

... and passing the context to the subconsole. ...并将上下文传递给子控制台。 A list would have worked just as well. 列表也可以正常工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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