金子邦彦研究室プログラミングPythonPython の fire を使ってみる(コマンドインタフェースの自動生成)

Python の fire を使ってみる(コマンドインタフェースの自動生成)

fire は,コマンドインタフェースを自動生成する機能を持ったライブラリ

目次

  1. 前準備
  2. fire のインストール手順
  3. fire を使ってみる

前準備

Python の準備(Windows,Ubuntu 上)

サイト内の関連ページ

関連する外部ページ

Python の公式ページ: https://www.python.org/

Python のまとめ: 別ページ »にまとめ

Python の公式ページ: https://www.python.org/

fire のインストール手順

  1. Windows では,コマンドプロンプト管理者として実行する.

    [image]
  2. 次のコマンドを実行

    Windows では「python」,Ubuntu では「sudo python3」.

    python -m pip install -U fire
    

    [image]

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)

[image]

端末 (Windows のコマンドプロンプトなど)を開き,次を実行

python hoge.py 100
python hoge.py 150
python hoge.py 400

[image]

クラスのコンストラクタとメソッド

次のファイルを作り, 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)

[image]

端末 (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

[image]