如何編寫完美的Python命令行程序?

尋夢新聞LINE@每日推播熱門推薦文章,趣聞不漏接❤️

加入LINE好友

如何編寫完美的Python命令行程序? 科技 第1張

作者 |Yannick Wolff

譯者 |彎月

責編 | 屠敏

出品 |CSDN(ID:CSDNNews)

作為 Python 開發者,我們經常要編寫命令行程序。比如在我的數據科學項目中,我要從命令行運行腳本來訓練模型,以及計算算法的準確率等。

因此,更方便更易用的腳本能夠很好地提高生產力,特別是在有多個開發者從事同一個項目的場合下。

因此,我建議你遵循以下四條規則:

  1. 盡可能提供默認參數值

  2. 所有錯誤情況必須處理(例如,參數缺失,類型錯誤,找不到文件)

  3. 所有參數和選項必須有文檔

  4. 不是立即完成的任務應當顯示進度條

舉個簡單的例子

我們把這些規則應用到一個具體的例子上。這個腳本可以使用凱撒加密法加密和解密消息。

假設已經有個寫好的 encrypt 函數(做到如下),我們需要創建一個簡單的腳本,用來加密和解密消息。我們希望讓用戶通過命令行參數選擇加密模式(默認)和解密模式,並選擇一個秘鑰(默認為 1)。

defencrypt(plaintext,key):cyphertext=''forcharacterinplaintext:ifcharacter.isalpha():number=ord(character)number+=keyifcharacter.isupper():ifnumber>ord('Z'):number-=26elifnumber<ord('A'):number+=26elifcharacter.islower():ifnumber>ord('z'):number-=26elifnumber<ord('a'):number+=26character=chr(number)cyphertext+=characterreturncyphertext

我們的腳本需要做的第一件事就是獲取命令行參數的值。當我搜尋「python command line arguments」時,出現的第一個結果是關於sys.argv的,所以我們來試試這個方法……

「初學者」的方法

sys.argv 是個列表,包含用戶在運行腳本時輸入的所有參數(包括腳本名自身)。

例如,如果我輸入:

>pythoncaesar_script.py--key23--decryptmysecretmessagepbvhfuhwphvvdjh

該列表將包含:

['caesar_script.py','--key','23','--decrypt','my','secret','message']

因此只需遍歷該參數列表,找到’–key’(或’-k’)以得到秘鑰值,找到’–decrypt’以設置解密模式(實際上只需要使用秘鑰的反轉作為秘鑰即可)。

最後我們的腳本大致如下:

importsysfromcaesar_encryptionimportencryptdefcaesar():key=1is_error=Falseforindex,arginenumerate(sys.argv):ifargin['--key','-k']andlen(sys.argv)>index+1:key=int(sys.argv[index+1])delsys.argv[index]delsys.argv[index]breakforindex,arginenumerate(sys.argv):ifargin['--encrypt','-e']:delsys.argv[index]breakifargin['--decrypt','-d']:key=-keydelsys.argv[index]breakiflen(sys.argv)==1:is_error=Trueelse:forarginsys.argv:ifarg.startswith('-'):is_error=Trueifis_error:print(f'Usage:python{sys.argv[0]}[--key<key>][--encrypt|decrypt]<text>')else:print(encrypt(''.join(sys.argv[1:]),key))if__name__=='__main__':caesar()

這個腳本遵循了一些我們前面推薦的規則:

  1. 支持默認秘鑰和默認模式

  2. 基本的錯誤處理(沒有提供輸入文本的情況,以及提供了無法識別的參數的情況)

  3. 出錯時或者不帶任何參數調用腳本時會顯示文檔:

>pythoncaesar_script_using_sys_argv.pyUsage:pythoncaesar.py[--key<key>][--encrypt|decrypt]<text>

但是,這個凱撒加密法腳本太長了(39 行,其中甚至還沒包括加密代碼本身),而且很難讀懂。

解析命令行參數應該還有更好的辦法……

試試 argparse?

argparse 是 Python 用來解析命令行參數的標準庫。

我們來看看用 argparse 怎樣編寫凱撒加密的腳本:

importargparsefromcaesar_encryptionimportencryptdefcaesar():parser=argparse.ArgumentParser()group=parser.add_mutually_exclusive_group()group.add_argument('-e','--encrypt',action='store_true')group.add_argument('-d','--decrypt',action='store_true')parser.add_argument('text',nargs='*')parser.add_argument('-k','--key',type=int,default=1)args=parser.parse_args()text_string=''.join(args.text)key=args.keyifargs.decrypt:key=-keycyphertext=encrypt(text_string,key)print(cyphertext)if__name__=='__main__':caesar()

這段代碼也遵循了上述規則,而且與前面的手工編寫的腳本相比,可以提供更準確的文檔,以及更具有交互性的錯誤處理:

>pythoncaesar_script_using_argparse.py--encodeMymessageusage:caesar_script_using_argparse.py[-h][-e|-d][-kKEY][text[text...]]caesar_script_using_argparse.py:error:unrecognizedarguments:--encode>pythoncaesar_script_using_argparse.py--helpusage:caesar_script_using_argparse.py[-h][-e|-d][-kKEY][text[text...]]

positionalarguments:textoptionalarguments:-h,--helpshowthishelpmessageandexit-e,--encrypt-d,--decrypt-kKEY,--keyKEY

但是,仔細看了這段代碼後,我發現(雖然有點主觀)函數開頭的幾行(從7行到13行)定義了參數,但定義方式並不太優雅:它太臃腫了,而且完全是程式化的。應該有更描述性、更簡潔的方法。

click 能做得更好!

幸運的是,有個 Python 庫能提供與 argparse 同樣的功能(甚至還能提供更多),它的代碼風格更優雅。這個庫的名字叫 click。

這里是凱撒加密腳本的第三版,使用了 click:

[email protected]()@click.argument('text',nargs=-1)@click.option('--decrypt/--encrypt','-d/-e')@click.option('--key','-k',default=1)defcaesar(text,decrypt,key):text_string=''.join(text)ifdecrypt:key=-keycyphertext=encrypt(text_string,key)click.echo(cyphertext)if__name__=='__main__':caesar()

注意現在參數和選項都在修飾器里定義,定義好的參數直接作為函數參數提供。

我來解釋一下上面代碼中的一些地方:

  • 腳本參數定義中的nargs參數指定了該參數期待的單詞的數目(一個用引號括起來的字符串算一個單詞)。默認值是1。這里nargs=-1允許接收任意數目的單詞。

  • –encrypt/–decrypt這種寫法可以定義完全互斥的選項(類似於argparse中的add_mutually_exclusive_group函數),它將產生一個布爾型參數。

  • click.echo是該庫提供的一個工具函數,它的功能與print相同,但兼容Python 2和Python 3,還有一些其他功能(如處理顏色等)。

添加一些隱秘性

這個腳本的參數(被加密的消息)應當是最高機密。而我們卻要求用戶直接在終端里輸入文本,使得這些文本被記錄在命令歷史中,這不是很諷刺嗎?

解決方法之一就是使用隱藏的提示。或者可以從輸入文件中讀取文本,對於較長的文本來說更實際一些。或者可以乾脆讓用戶選擇。

輸出也一樣:用戶可以保存到文件中,也可以輸出到終端。這樣就得到了凱撒腳本的最後一個版本:

[email protected]()@click.option('--input_file',type=click.File('r'),help='Fileinwhichthereisthetextyouwanttoencrypt/decrypt.''Ifnotprovided,apromptwillallowyoutotypetheinputtext.',)@click.option('--output_file',type=click.File('w'),help='Fileinwhichtheencrypted/decryptedtextwillbewritten.''Ifnotprovided,theoutputtextwilljustbeprinted.',)@click.option('--decrypt/--encrypt','-d/-e',help='Whetheryouwanttoencrypttheinputtextordecryptit.')@click.option('--key','-k',default=1,help='Thenumerickeytouseforthecaesarencryption/decryption.')defcaesar(input_file,output_file,decrypt,key):ifinput_file:text=input_file.read()else:text=click.prompt('Enteratext',hide_input=notdecrypt)ifdecrypt:key=-keycyphertext=encrypt(text,key)ifoutput_file:output_file.write(cyphertext)else:click.echo(cyphertext)if__name__=='__main__':caesar()

這個版本有什麼新東西嗎?

  • 首先,注意到我給每個參數選項都加了個help參數。由於腳本變得複雜了,help參數可以給腳本的行為添加一些文檔。運行結果如下:

>pythoncaesar_script_v2.py--helpUsage:caesar_script_v2.py[OPTIONS]Options:--input_fileFILENAMEFileinwhichthereisthetextyouwanttoencrypt/decrypt.Ifnotprovided,apromptwillallowyoutotypetheinputtext.--output_fileFILENAMEFileinwhichtheencrypted/decryptedtextwillbewritten.Ifnotprovided,theoutputtextwilljustbeprinted.-d,--decrypt/-e,--encryptWhetheryouwanttoencrypttheinputtextordecryptit.-k,--keyINTEGERThenumerickeytouseforthecaesarencryption/decryption.--helpShowthismessageandexit.

  • 兩個新的參數:input_file 和 output_file,類型均為 click.File。該庫能夠用正確的模式打開文件,處理可能的錯誤,再執行函數。例如:

>pythoncaesar_script_v2.py--decrypt--input_filewrong_file.txtUsage:caesar_script_v2.py[OPTIONS]Error:Invalidvaluefor"--input_file":Couldnotopenfile:wrong_file.txt:Nosuchfileordirectory

  • 正像help文本中解釋的那樣,如果沒有提供input_file,就使用click.promp讓用戶直接在提示符下輸入文本,在加密模式下這些文本是隱藏的。如下所示:

>pythoncaesar_script_v2.py--encrypt--key2Enteratext:**************yyy.ukectc.eqo

破解密文!

現在設想你是個黑客:你要解密一個用凱撒加密過的密文,但你不知道秘鑰是什麼。

最簡單的策略就是用所有可能的秘鑰調用解密函數 25 次,閱讀解密結果,看看哪個是合理的。

但你很聰明,而且也很懶,所以你想讓整個過程自動化。確定解密後的 25 個文本哪個最可能是原始文本的方法之一,就是統計所有這些文本中的英文單詞的個數。這可以使用 PyEnchant 模塊做到:

importclickimportenchantfromcaesar_encryptionimportencrypt@click.command()@click.option('--input_file',type=click.File('r'),required=True,)@click.option('--output_file',type=click.File('w'),required=True,)defcaesar_breaker(input_file,output_file):cyphertext=input_file.read()english_dictionnary=enchant.Dict("en_US")max_number_of_english_words=0forkeyinrange(26):plaintext=encrypt(cyphertext,-key)number_of_english_words=0forwordinplaintext.split(''):ifwordandenglish_dictionnary.check(word):number_of_english_words+=1ifnumber_of_english_words>max_number_of_english_words:max_number_of_english_words=number_of_english_wordsbest_plaintext=plaintextbest_key=keyclick.echo(f'Themostlikelyencryptionkeyis{best_key}.Itgivesthefollowingplaintext:\n\n{best_plaintext[:1000]}...')output_file.write(best_plaintext)if__name__=='__main__':caesar_breaker()

如何編寫完美的Python命令行程序? 科技 第2張

好像運行得很不錯,但別忘了,好的命令行程序還有個規則需要遵守:

4.A 不是立即完成的任務應當顯示進度條。

示例中的文本包含10^4個單詞,因此該腳本需要大約5秒才能解密。這很正常,因為它需要檢查所有25個秘鑰,每個秘鑰都要檢查10^4個單詞是否出現在英文字典中。

假設你要解密的文本包括10^5個但IC,那麼就要花費50秒才能輸出結果,用戶可能會非常著急。

因此我建議這種任務一定要顯示進度條。特別是,顯示進度條還非常容易做到。

下面是個顯示進度條的例子:

importclickimportenchantfromtqdmimporttqdmfromcaesar_encryptionimportencrypt@click.command()@click.option('--input_file',type=click.File('r'),required=True,)@click.option('--output_file',type=click.File('w'),required=True,)defcaesar_breaker(input_file,output_file):cyphertext=input_file.read()english_dictionnary=enchant.Dict("en_US")best_number_of_english_words=0forkeyintqdm(range(26)):plaintext=encrypt(cyphertext,-key)number_of_english_words=0forwordinplaintext.split(''):ifwordandenglish_dictionnary.check(word):number_of_english_words+=1ifnumber_of_english_words>best_number_of_english_words:best_number_of_english_words=number_of_english_wordsbest_plaintext=plaintextbest_key=keyclick.echo(f'Themostlikelyencryptionkeyis{best_key}.Itgivesthefollowingplaintext:\n\n{best_plaintext[:1000]}...')output_file.write(best_plaintext)if__name__=='__main__':caesar_breaker()

你發現區別了嗎?可能不太好找,因為區別真的很小,只有四個字母:tqdm。

tqdm 是 Python 庫的名字,也是它包含的類的名字。只需用它包裹一個可迭代的東西,就能顯示出進度條:

forkeyintqdm(range(26)):

這樣就能顯示出非常漂亮的進度條。我都不敢相信這是真的。

如何編寫完美的Python命令行程序? 科技 第3張

另外,click也提供類似的顯示進度條的工具(click.progress_bar),但我覺得它的外觀不太容易懂,而且要寫的代碼也多一些。

我希望這篇文章能讓你在改進開發者的體驗上多花點時間。

原文:

https://blog.sicara.com/perfect-python-command-line-interfaces-7d5d4efad6a2

作者:Yannick Wolff,Sicara 的數據科學家。

本文為CSDN 翻譯,如需轉載,請註明來源出處。

福利

公眾號後台回復:2018Python,獲取2018Python開源項目Top100整理資料!或掃碼添加小助手微信,回復:1,入群獲取。

如何編寫完美的Python命令行程序? 科技 第4張

推薦閱讀:

About 尋夢園
尋夢園是台灣最大的聊天室及交友社群網站。 致力於發展能夠讓會員們彼此互動、盡情分享自我的平台。 擁有數百間不同的聊天室 ,讓您隨時隨地都能找到志同道合的好友!