목차

, , , ,

Python Fire

Python function, class, object, module을 reflection으로 탐색해 CLI를 자동 생성하는 library다.

Summary

Installation

공식 설치 문서는 PyPI와 conda-forge 방법을 제공한다. project virtual environment 사용을 권장한다.

# Linux / macOS
python3 -m venv .venv
source .venv/bin/activate
python3 -m pip install fire
python3 -c "import fire; print(fire.__version__)"
 
# conda
conda install fire -c conda-forge
# Windows PowerShell
py -m venv .venv
.venv\Scripts\Activate.ps1
py -m pip install fire
py -c "import fire; print(fire.__version__)"

Python Fire가 공식적으로 별도 안내하는 APT, DNF/YUM, Homebrew, winget package는 없다. Python environment에 설치한다.

Usage

함수 하나 노출

import fire
 
def hello(name: str, count: int = 1):
    """이름을 받아 인사합니다."""
    return "\n".join([f"Hello, {name}!"] * count)
 
if __name__ == "__main__":
    fire.Fire(hello)
python3 hello.py World
python3 hello.py --name World --count 2
python3 hello.py --help

여러 command를 명시적으로 노출

import fire
 
def create(name, admin=False):
    return {"name": name, "admin": admin}
 
def remove(name, force=False):
    if not force:
        raise ValueError("--force is required")
    return f"removed {name}"
 
if __name__ == "__main__":
    fire.Fire({"create": create, "remove": remove})

Module Execution

source를 수정하지 않고 module 또는 file을 Fire로 탐색할 수 있다.

python3 -m fire example hello --name=World
python3 -m fire example.py hello --name=World
module 전체나 신뢰 경계 밖의 object를 무심코 노출하면 의도하지 않은 public member와 동작까지 CLI에서 접근할 수 있다. production CLI에는 허용할 command를 dict, 함수 또는 전용 class로 명시해 노출 범위를 제한한다.

Arguments and Fire Flags

# interactive mode
python3 app.py command -- --interactive
 
# separator를 X로 변경
python3 app.py item1 item2 X upper -- --separator=X
 
# trace 표시
python3 app.py command -- --trace

Troubleshooting

Compatibility

Help

설치된 environment에서 application별 help와 Fire 자체 flag를 확인한다.

python3 app.py --help
python3 app.py command -- --help
python3 -m fire --help

See Also

History