![](/img/trans.png)
[英]Exiting to main level using nested interpreters and Cmd module in Python
[英]python Cmd module autocompletion error in nested interpreters
我正在嘗試為使用Cmd模塊編寫的主控制台創建調試控制台。
調試控制台應具有所有主控制台屬性,並且應具有更多用於調試和高級用戶的擴展。
滿足我需求的最佳答案是以下文章的第二個答案: 對象繼承和嵌套cmd
我的實現當前看起來像這樣:
class MainConsole(cmd.Cmd):
def __init__(self):
cmd.Cmd.__init__(self)
def do_something(self, line):
print "do something!"
return
def do_something2(self, line):
print "do something2!"
return
class SubConsole1(cmd.Cmd):
def __init__(self, maincon):
cmd.Cmd.__init__(self)
self.maincon = maincon
self.register_main_console_methods()
def register_main_console_methods(self):
main_names = self.maincon.get_names()
for name in main_names:
if (name[:3] == 'do_') or (name[:5] == 'help_') or (name[:9] == 'complete_'):
self.__dict__[name] = getattr(self.maincon, name)
觀察:
當我點擊“幫助”時,的確可以看到所有上層控制台方法,並且能夠調用它們。
問題:
實際命令的自動完成功能不可用。
敲“ some”和“ tab”時,shell的預期行為是將其自動完成為“ something”。 這不會發生。
當我試圖調試問題,我發現self.get_names()
方法,其使用由所述self.completenames()
函數返回的登記之前方法的列表。
因此,實際上發生的是,盡管我可以調用它們,但是從嵌套控制台中“刪除”了新添加的方法。
我希望對此有一些見解。
謝謝!
您可以通過擴展get_names
方法來解決您的問題
import cmd
class MainConsole(cmd.Cmd):
def __init__(self,console_id):
cmd.Cmd.__init__(self)
self.console_id = console_id
def do_something(self, line):
print "do something!",self.console_id
return
def do_something2(self, line):
print "do something2!",self.console_id
return
class SubConsole1(cmd.Cmd):
def __init__(self, maincon):
cmd.Cmd.__init__(self)
self.maincon = maincon
self.register_main_console_methods()
def do_super_commands(self,line):
print "do supercommand",self.maincon
def register_main_console_methods(self):
main_names = dir(self.maincon)
for name in main_names:
for prefix in 'do_','help_','complete_', :
if name.startswith(prefix) and name not in dir(self):
self.__dict__[name] = getattr(self.maincon, name)
def get_names(self):
result = cmd.Cmd.get_names(self)
result+=self.maincon.get_names()
return result
SubConsole1(MainConsole("mainconsole")).cmdloop()
它不能保證在python的子序列版本上工作,因為它是python 2.7的未記錄行為
編輯 :按注釋要求將mainconsole的子類方法替換為成員
編輯2 :不要替換SubConsole中的現有方法,以使方法保持為do_help
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.