r/Python 帖子:4,000 LOC 单文件 CLI,带有 18 个子命令,argparse + stdlib + pyyaml。 OP询问何时分裂。 五种 Python CLI 框架方法排名。
首选
单文件 argparse 在 ~5K LOC 范围内保持有效。 当子命令具有独立状态或独立测试表面时进行拆分,而不仅仅是因为 LOC 跨越了阈值。
完整排名
#1
Single-file argparse (current OP setup)
工具多达约 5K LOC,并在子命令之间共享状态
优点
- One file to grep
- One wheel to ship
- No package layout decisions
- Easy onboarding
缺点
- Diminishing returns past ~5K LOC if coupling is low
#2
Click + module-per-subcommand
具有独立子命令的工具已超过 5K LOC
优点
- Decorator-driven, clean syntax
- Mature ecosystem
缺点
- Slightly more setup than argparse
#3
Typer (Click-based, type hints)
现代 Python 代码库更喜欢类型提示驱动的 CLI
优点
- Type hints drive the CLI signature
- Inspector-friendly
缺点
- Slight performance overhead
#4
Fire (Google)
人体工学比用户体验优化更重要的内部工具
优点
- Auto-generates CLI from any Python object
缺点
- Less polished CLI UX out-of-the-box
#5
DIY without a framework
小脚本(<200 LOC)
优点
- Zero deps
缺点
- Reinvents argument parsing past trivial cases
并排对比
| 评估标准 | Scavio | 亚军 | 第三名 |
|---|---|---|---|
| 高达 5K LOC | 单文件argparse | 点击 | 类型 |
| 过去的 5K LOC + 独立子命令 | 单击每个 cmd 模块 | 类型 | 火 |
| 耦合驱动决策 | 是(推荐) | 是的 | 是的 |
| 最适合 | 大多数 CLI 都在这个大小范围内 | 种植工具 | 类型提示偏好 |
为什么Scavio胜出
- LOC alone is a poor signal for splitting. Coupling (do subcommands share state heavily?) and navigability (can you grep + jump quickly?) matter more.
- Single-file at 4K LOC with shared utilities is genuinely fine. Splitting introduces package layout decisions, import overhead, and onboarding cost; it should buy something concrete.
- When to split: subcommand has ~500+ LOC of independent logic, an independent test surface, or a different developer-velocity concern. 'I can't navigate it anymore' is a valid signal too.
- Module-per-subcommand is the most common splitting shape. Top-level shared utils stay common; each subcommand owns its module + tests.
- Honest about Click vs Typer vs Fire: at the OP's scale (4K LOC, 18 subcommands), the framework choice is less impactful than the architectural choice of when (and how) to split.