Fire (0) Hello world

1. Why Fire:

Python Fire 的特點:

  1. 用於簡單地建立 CLI (command line interfaces)
  2. 讓開發和除錯更簡單
  3. 調整程式碼
  4. bash 和 python 的轉換橋梁
  5. Python Fire makes using a Python REPL easier by setting up the REPL with the modules and variables you'll need already imported and created

2. Installing Fire:

$ pip3 install fire

3. Hello world:

基本用法有兩種,第一種是在執行時指定函數另一種是在程式碼裡綁定函數:

import fire

def greet(name):
    return "Hello " + name

if __name__ == "__main__":
    fire.Fire()  # 不指定 greet

使用的格式為 python3 <file_name> <function_name> <args>。

$ python3 f.py greet cooper  # 執行時指定 greet, arg 為 cooper
$ python3 f.py greet --name=cooper  # 參數自動對應
$ python3 f.py greet --name cooper

Hello cooper

另一種是在程式碼裡綁定函數:

import fire

def greet(name):
    return "Hello " + name

if __name__ == "__main__":
    fire.Fire(greet)  # 指定使用 greet
$ python3 f.py cooper  # 不用 greet

Reference:

[1] https://github.com/google/python-fire

[2] https://github.com/google/python-fire/blob/master/docs/guide.md


留言

熱門文章