python獲取命令行參數實例方法講解
Python 在命令行解析方面給出了類似的幾個選擇:自己解析, 自給自足(batteries-included)的方式,以及大量的第三方方式。
自己解析
你可以從 sys 模塊中獲取程序的參數。
import sys if __name__ == ’__main__’: for value in sys.argv: print(value)
自給自足
在 Python 標準庫中已經有幾個參數解析模塊的實現: getopt 、 optparse ,以及最近的 argparse 。argparse 允許程序員為用戶提供一致的、有幫助的用戶體驗,但就像它的 GNU 前輩一樣,它需要程序員做大量的工作和“ 模板代碼 ”才能使它“奏效”。
from argparse import ArgumentParser if __name__ == '__main__': argparser = ArgumentParser(description=’My Cool Program’) argparser.add_argument('--foo', '-f', help='A user supplied foo') argparser.add_argument('--bar', '-b', help='A user supplied bar') results = argparser.parse_args() print(results.foo, results.bar)
CLI 的現代方法
Click 框架使用 裝飾器 的方式來構建命令行解析。
import click @click.command()@click.option('-f', '--foo', default='foo', help='User supplied foo.')@click.option('-b', '--bar', default='bar', help='User supplied bar.')def echo(foo, bar): '''My Cool Program It does stuff. Here is the documentation for it. ''' print(foo, bar) if __name__ == '__main__':echo()
在 Click 接口中添加參數就像在堆棧中添加另一個裝飾符并將新的參數添加到函數定義中一樣簡單。
知識拓展:
Typer 建立在 Click 之上,是一個更新的 CLI 框架,它結合了 Click 的功能和現代 Python 類型提示 。使用 Click 的缺點之一是必須在函數中添加一堆裝飾符。CLI 參數必須在兩個地方指定:裝飾符和函數參數列表。Typer 免去你造輪子 去寫 CLI 規范,讓代碼更容易閱讀和維護。
import typer cli = typer.Typer() @cli.command()def echo(foo: str = 'foo', bar: str = 'bar'): '''My Cool Program It does stuff. Here is the documentation for it. ''' print(foo, bar) if __name__ == '__main__':cli()
到此這篇關于python獲取命令行參數實例方法講解的文章就介紹到這了,更多相關python獲取命令行參數實現方法內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!
相關文章:
