티스토리 뷰
This text is generated by ChatGPT.
`typer`는 파이썬 함수를 커맨드 라인 인터페이스(CLI) 명령으로 변환하는 데 사용하는 라이브러리입니다. 이를 통해 개발자는 복잡한 파싱 로직을 작성하지 않고도 간단한 함수 정의를 통해 강력하고 사용하기 쉬운 CLI 도구를 만들 수 있습니다.
### Typer의 기본 사용 예시
1. **기본 함수 정의**: 간단한 함수를 정의하고, `typer`를 사용하여 그 함수를 CLI 명령으로 만듭니다.
2. **명령 실행**: 사용자는 커맨드 라인에서 이 함수를 명령어 형태로 실행할 수 있습니다.
### 예시 코드
다음은 `typer`를 사용하여 간단한 커맨드 라인 툴을 만드는 예시입니다.
```python
# app.py 파일
import typer
app = typer.Typer()
@app.command()
def hello(name: str):
"""Simple program that greets NAME for a total of COUNT times."""
typer.echo(f"Hello {name}")
if __name__ == "__main__":
app()
```
이 스크립트를 실행하기 위해 커맨드 라인에서 다음과 같이 입력할 수 있습니다:
```bash
python app.py hello --name John
```
### 실행 결과
```
Hello John
```
이 예시에서는 `hello`라는 함수를 정의하고 `typer`를 사용해 `app` 객체에 커맨드로 추가했습니다. 이 커맨드는 사용자가 커맨드 라인에서 이 프로그램을 실행할 때 `--name` 옵션과 함께 이름을 제공하도록 요구합니다. `typer.echo`는 표준 출력으로 메시지를 출력합니다.
### `plot_query_results` 함수를 커맨드 라인 툴로 변환하기
위에서 설명한 `plot_query_results` 함수를 `typer`를 사용해 CLI 도구로 만들고 싶다면, 다음과 같이 작성할 수 있습니다:
```python
import typer
import json
from pathlib import Path
app = typer.Typer()
@app.command()
def plot_query_results(
file_path: Path = typer.Argument(
...,
exists=True,
file_okay=True,
dir_okay=False,
readable=True,
help="The path to the JSON file containing the query results."
)
):
"""Reads a JSON file and plots query results based on the content."""
with open(file_path, "r") as file:
data = json.load(file)
# 데이터 처리 및 그래프 생성 로직
print("Data processed and plot created.")
if __name__ == "__main__":
app()
```
이 스크립트를 사용하면 사용자는 커맨드 라인에서 JSON 파일 경로를 명령어와 함께 제공하여 함수를 실행할 수 있습니다. 이 방식으로 `typer`는 파이썬 함수를 간편하게 커맨드 라인 도구로 전환할 수 있게 해줍니다.