argparse는 커맨드라인 인자를 파싱하는 파이썬 표준 라이브러리입니다. 이 치트시트는 위치/옵션 인자, 타입 변환, 서브커맨드, 도움말 생성의 핵심 패턴을 정리합니다.
언제 이 치트시트를 보나?
- CLI 도구나 스크립트에 옵션/인자를 받고 싶을 때
--help자동 생성이 필요할 때
핵심 패턴
ArgumentParser(): 파서 생성add_argument(): 인자 정의 (위치/옵션)parse_args(): 파싱 후Namespace객체 반환- 옵션:
-v,--verbose(앞에-붙임) - 위치 인자:
-없이 정의
최소 예제
| |
| |
| |
주요 add_argument 옵션
| |
nargs 옵션
| nargs | 의미 | 결과 타입 |
|---|---|---|
N (정수) | 정확히 N개 | list |
? | 0개 또는 1개 | 값 또는 None |
* | 0개 이상 | list |
+ | 1개 이상 | list |
| |
action 옵션
| |
서브커맨드
| |
| |
실무 패턴
| |
| |
| |
자주 하는 실수/주의점
- 위치 인자 순서: 정의 순서대로 파싱됨
- 옵션 이름 충돌:
-h는 기본적으로 help에 예약됨 - type=bool 함정:
type=bool은 의도대로 동작 안 함 →action="store_true"사용 - required 옵션: 위치 인자는 기본적으로 필수,
nargs="?"로 선택적으로 변경 가능 - dest 네이밍:
--my-option은args.my_option으로 접근 (하이픈 → 언더스코어)
대안: click, typer
더 복잡한 CLI가 필요하면 서드파티 라이브러리 고려:
| |
![Featured image of post [Python Cheatsheet] 17. argparse & CLI - 커맨드라인 인자 처리](/post/python-cheatsheet/argparse-command-line-interface-guide-core-cli-arguments/wordcloud_hu_7fbe4bcec1e09958.png)
![[Python Cheatsheet] 12. Context Managers - with문/리소스 관리](/post/python-cheatsheet/context-manager-with-resource-management-best-practices-guide/wordcloud_hu_c4127dc6ae73e7db.png)
![[Python Cheatsheet] 16. Environment Variables - os.environ/dotenv 패턴](/post/python-cheatsheet/manage-env-variables-os-environ-dotenv-envfile-configuration-guide/wordcloud_hu_a9f5d5bb7c00d9ed.png)
![[Python Cheatsheet] 17. argparse & CLI - 커맨드라인 인자 처리](/post/python-cheatsheet/argparse-command-line-interface-guide-core-cli-arguments/wordcloud_hu_9a192cb68b9a0baf.png)
![[Python Cheatsheet] 18. subprocess - 외부 프로세스 실행](/post/python-cheatsheet/external-process-run-execute-command-subprocess-guide-security/wordcloud_hu_3efabb2c4e988dbc.png)
![[Python Cheatsheet] 19. Typing - 실전 타입힌트 패턴](/post/python-cheatsheet/practical-type-hint-patterns-static-analysis-guide-2024/wordcloud_hu_7189a50467c1b0ca.png)
![[Python Cheatsheet] 07. Functions - 인자/리턴/*args/**kwargs](/post/python-cheatsheet/fast-guide-functions-args-kwargs-defaults-annotations-tips/wordcloud_hu_34ea397edb139663.png)
![[Python Cheatsheet] 61. Profiling - cProfile/py-spy 성능 분석](/post/python-cheatsheet/profiling-cprofile-pyspy-performance-analysis-guide/wordcloud_hu_e5d0dcaf802b0e2d.png)
![[Python Cheatsheet] 09. Decorators - 함수/클래스 데코레이터](/post/python-cheatsheet/guide-decorators-functions-classes-wrapper-examples-reference/wordcloud_hu_5116df45caa4e900.png)