[英]Exiting to main level using nested interpreters and Cmd module in Python
我在具有多級嵌套解釋器的程序上使用Python Cmd模塊。 我希望能夠從幾個級別的解釋器一直退回到主循環。 這是我嘗試過的:
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()
當我運行程序時,導航到LEVEL3解釋器並輸入'exit_to_level_1'我只返回到level2。 救命?
所以它歸結為可變類型和不可變類型。 有一個非常完整的答案在這里 。 基本上,bool self.exit
是不可變的; 要將它傳遞給另一個對象並允許該對象更改它,它需要以可變類型包裝。
我們通過使用dict來恢復它:
self.context = {"exit": False}
...並將上下文傳遞給子控制台。 列表也可以正常工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.