Python 中的 Docopt 模組


Python 中的 Docopt 模組用於建立命令列介面。與其他命令列引數和選項類似,docopt 允許我們定義命令列引數和選項,併為程式生成幫助資訊和用法字串。在本文中,我們將瞭解 Docopt 模組是如何定義的以及如何使用它來建立命令列介面。

安裝

在使用 Docopt 模組之前,可以使用 Python 中的 pip 命令安裝它。要安裝 Docopt 模組,請在您的終端或命令提示符中輸入以下命令。

pip install docopt

使用 Docopt 模組的程式

安裝 Docopt 模組後,讓我們看一些示例,瞭解如何在 Python 中使用 Docopt 模組。

示例 1:簡單程式

在下面的程式碼中,我們將在執行程式時提供檔名引數。例如,如果程式檔案為 simple_program.py,並且我們在同一目錄下有一個 test.txt 檔案,則引數應為 python simple_program.py test.txt

""" Usage: simple_program.py <filename>

Print the contents of the file to the console.
"""

from docopt import docopt

def main():
   args = docopt(__doc__)
   filename = args['<filename>']
   with open(filename, 'r') as f:
      print(f.read())

if __name__ == '__main__':
   main()

輸出

This is testing the docopt module.

示例 2:帶選項的程式

在這個例子中,我們將建立一個程式,它接受檔名作為引數,以及一個可選的標誌,指定是否顯示行號。我們將使用 Docopt 定義命令列介面。在下面的示例中,我們將在執行程式時提供檔名引數和 –line-numbers 標誌。例如,如果程式檔案為 simple_program.py,並且我們在同一目錄下有一個 test.txt 檔案,則引數應為 python simple_program.py test.txt –line-numbers

"""Usage: program_with_options.py [--line-numbers] <filename>

Print the contents of the file to the console, with line numbers if specified.

Options:
  --line-numbers  Display line numbers.
"""

from docopt import docopt

def main():
   args = docopt(__doc__)
   filename = args['<filename>']
   with open(filename, 'r') as f:
      if args['--line-numbers']:
         for i, line in enumerate(f):
            print(f"{i+1}: {line}", end="")
      else:
         print(f.read())

if __name__ == '__main__':
    main()

輸出

1: This is testing the docopt module.
2: This is line 2
3: This is line 3
4: This is line 4

結論

在本文中,我們討論瞭如何使用 docopt 模組建立命令列介面,以及如何使用它建立命令列引數和選項。它使用宣告式方法定義命令列引數和選項,使其易於使用和理解。使用 Docopt,您可以快速為 Python 程式建立命令列介面,而無需擔心引數解析和幫助資訊生成的細節。

更新於: 2023-07-10

771 次瀏覽

開啟您的 職業生涯

透過完成課程獲得認證

立即開始
廣告

© . All rights reserved.