《可愛的Python》讀書筆記(五)
阿新 • • 發佈:2018-03-23
重構 cmd 命令行界面 不論戰術上如何變化,千萬不要忘記戰略。
在前些時候小白已經使用getopt獲得命令行工具。
但是,要完成一個個看似簡單,實際有 N 多情況的邏輯判定就有點煩人了。
熱心的行者,又出聲了:“使用 cmd 吧!”
cmd模塊,是一個專門支持命令行界面的模塊。讓我們來重構一下它:
# -*- coding: utf-8 -*- import sys import cmd class 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()
運行效果如下:
>help Documented commands (type help <topic>): ======================================== dir find help quit walk Undocumented 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 os import sys from 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》讀書筆記(五)