標籤:重構 cmd 命令列介面
不論戰術上如何變化,千萬不要忘記戰略。
在前些時候小白已經使用getopt獲得命令列工具。
但是,要完成一個個看似簡單,實際有 N 多情況的邏輯判定就有點煩人了。
熱心的行者,又出聲了:“使用 cmd 吧!”
cmd模組,是一個專門支援命令列介面的模組。讓我們來重構一下它:
# -*- coding: utf-8 -*-import sysimport cmdclass PyCDC(cmd.Cmd): def __init__(self): # 初始化基類,類的定量應該都在初始化時聲明 cmd.Cmd.__init__(self) # 定義命令列提示符 self.prompt = ">" # 定義walk命令所執行的操作 def do_walk(self, filename): if filename == "": filename = input("請輸入cdc檔案名稱:") print("掃描光碟片內容儲存到:'%s'" % filename) # 定義walk命令的協助輸出 def help_walk(self): print("掃描光碟片內容 walk cd and export init '.cdc'") # 定義dir命令所執行的操作 def do_dir(self, pathname): if pathname == "": pathname = input("請輸入指定儲存/搜尋目錄:") # 定義dir(命令的協助輸出 def help_dir(self): print("指定儲存/搜尋目錄") # 定義find命令所執行的操作 def do_find(self, keyword): if keyword == "": keyword = input("請輸入搜尋關鍵詞:") # 定義find命令的協助輸出 def help_find(self): print("搜尋關鍵詞") # 定義quit命令所執行的操作 def do_quit(self, arg): sys.exit(1) # 定義quit命令的協助輸出 def help_quit(self): print("Syntax:quit") print("--terminates the application") # 定義quit的捷徑 do_q = do_quit if __name__ == '__main__': cdc = PyCDC() cdc.cmdloop()
運行效果如下:
>helpDocumented commands (type help <topic>):========================================dir find help quit walkUndocumented commands:======================q>dir請輸入指定儲存/搜尋目錄:cdc>walk請輸入cdc檔案名稱:test.cdc掃描光碟片內容儲存到:'test.cdc'>?find搜尋關鍵詞>xx*** Unknown syntax: xx>q>>> ==========================>find請輸入搜尋關鍵詞:images>quit
可以看到,此代碼純粹是用來嘗試cmd模組功能的,只能列印輸出資訊,沒有任何實際作用。
從這個例子可以看出,首先PyCDC類繼承cmd.Cmd類,然後在類中定義了walk,dir,find和quit,而命令q被作為quit的短命令形式。(也就是說,若須另外定義一條命令,如command,只要在PyCDC類中增加一個 do_command 函式)而該命令對應的協助資訊由help_command 函式給出。
就像樣本中所寫的那樣,自訂的PyCDC類提供了的命令,是可以正常使用它們的,而xx命令是沒有定義的,所以命令列提示為未知文法。最後的q命令和quit是一樣的功能,即退出程式。
# -*- coding: utf-8 -*-import osimport sysfrom cdctools import * # 可以引入己有指令碼cdctools中的所有函數def cdWalker(cdrom, cdcfile): export = "" for root, dirs, files in os.walk(cdrom): export += "\n %s;%s;%s" % (root, dirs, files) open(cdcfile, 'w').write(export) if __name__ == "__main__": cdc = PyCDC() cdc.cmdloop()
哈哈,可以運行起來!可以看的出在代碼中,按代碼的複用尺度來分,從小到大應該是:程式碼→函式→類→模組
好像還有更大的一級包,具體現在還用不上,那就先不管它了。
《可愛的Python》讀書筆記(五)