簡單記錄一下,竟然這么簡單的方法就能在 python 里面實現一個簡單的交互式命令行以前從來沒有嘗試過。
上一個完整的例子:
import cmd import os
import readline
readline.parse_and_bind('tab: complete') class CLI(cmd.Cmd): def __init__(self): cmd.Cmd.__init__(self) self.prompt = "Miller2 > " # define command prompt def do_dir(self, arg): if not arg: self.help_dir() elif os.path.exists(arg): print"\n".join(os.listdir(arg)) else: print "No such pathexists." def help_dir(self): print "syntax: dir path -- displaya list of files and directories" def do_quit(self, arg): return True def help_quit(self): print "syntax: quit -- terminatesthe application" # define the shortcuts do_q = do_quit if __name__ == "__main__": cli = CLI() cli.cmdloop(intro="welcome to axiba")
使用 readline 來實現了命令交互 tab 提示補全的功能。 然后是 CLI 類繼承了 cmd.Cmd。
self.prompt 用於指定提示符樣式。
交互命令行的規則定義就是 do_cmd 就可以在運行的使用 cmd 命令。如果出錯可以調用自己定義的數據。
backup 一份常用函數,可以根據這些鈎子函數來達到自己想要的交互效果:
(1)cmdloop():類似與Tkinter的mainloop,運行Cmd解析器; (2)onecmd(str):讀取輸入,並進行處理,通常不需要重載該函數,而是使用更加具體的do_command來執行特定的命令; (3)emptyline():當輸入空行時調用該方法; (4)default(line):當無法識別輸入的command時調用該方法; (5)completedefault(text,line,begidx,endidx):如果不存在針對的complete_*()方法,那么會調用該函數,該函數主要是用於tab補充,且只能在linux下使用。 (6)precmd(line):命令line解析之前被調用該方法; (7)postcmd(stop,line):命令line解析之后被調用該方法; (8)preloop():cmdloop()運行之前調用該方法; (9)postloop():cmdloop()退出之后調用該方法; (10)help_command():對command命令的說明,其中command為可變字符
reference:
https://www.cnblogs.com/r00tuser/p/7515136.html 簡單認識python cmd模塊