Python の fire を使ってみる(コマンドインタフェースの自動生成)
前準備
Python の準備(Windows,Ubuntu 上)
- Windows での Python 3.10,関連パッケージ,Python 開発環境のインストール(winget を使用しないインストール): 別ページ »で説明
- Ubuntu では,システム Pythonを使うことができる.Python3 開発用ファイル,pip, setuptools のインストール: 別ページ »で説明
【サイト内の関連ページ】
- Python のまとめ: 別ページ »にまとめ
- Google Colaboratory の使い方など: 別ページ »で説明
【関連する外部ページ】 Python の公式ページ: https://www.python.org/
Python の公式ページ: https://www.python.org/
fire のインストール手順
- Windows では,コマンドプロンプトを管理者として実行する.
- 次のコマンドを実行
Windows では「python」,Ubuntu では「sudo python3」.
python -m pip install -U fire
fire を使ってみる
fire の使用法については: https://github.com/google/python-fire/blob/master/docs/using-cli.md
関数
次のファイルを作り, hoge.pyのようなファイル名で保存
import fire
def foo(a):
return(a * 1.08)
if __name__ == '__main__': fire.Fire(foo)

端末 (Windows のコマンドプロンプトなど)を開き,次を実行
python hoge.py 100
python hoge.py 150
python hoge.py 400

クラスのコンストラクタとメソッド
次のファイルを作り, hoge.pyのようなファイル名で保存
import fire
class C(object):
def __init__(self, qty, weight, name):
self.qty = qty
self.weight = weight
self.name = name
def total(self):
return self.qty * self.weight
if __name__ == '__main__': fire.Fire(C)

端末 (Windows のコマンドプロンプトなど)を開き,次を実行
python hoge.py --qty 5 --weight 170.51 --name 'apple' qty
python hoge.py --qty 5 --weight 170.51 --name 'apple' weight
python hoge.py --qty 5 --weight 170.51 --name 'apple' name
python hoge.py --qty 5 --weight 170.51 --name 'apple' total
