75 lines
2.8 KiB
Python
75 lines
2.8 KiB
Python
"""argparse 中文错误说明。"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import argparse
|
||
import sys
|
||
from typing import List
|
||
|
||
from content_manager.constants import CLI_REQUIRED_ZH
|
||
|
||
|
||
def split_required_arg_names(raw: str) -> List[str]:
|
||
s = raw.replace(" and ", ", ").strip()
|
||
parts: List[str] = []
|
||
for chunk in s.split(","):
|
||
chunk = chunk.strip()
|
||
if not chunk:
|
||
continue
|
||
idx = chunk.find(" --")
|
||
if idx != -1:
|
||
left = chunk[:idx].strip()
|
||
flag_rest = chunk[idx + 1 :].strip().split()
|
||
if left:
|
||
parts.append(left)
|
||
if flag_rest:
|
||
parts.append(flag_rest[0])
|
||
else:
|
||
parts.append(chunk)
|
||
return [p for p in parts if p]
|
||
|
||
|
||
def explain_argparse_error(message: str) -> str:
|
||
m = (message or "").strip()
|
||
lines: List[str] = ["【命令参数不完整或写错了】请对照下面修改后再执行。"]
|
||
if "the following arguments are required:" in m:
|
||
raw = m.split("required:", 1)[-1].strip()
|
||
parts = split_required_arg_names(raw)
|
||
for p in parts:
|
||
hint = CLI_REQUIRED_ZH.get(p)
|
||
if not hint and p.startswith("--"):
|
||
hint = CLI_REQUIRED_ZH.get(p.split()[0], None)
|
||
lines.append(f" · {hint or f'还缺这一项:{p}'}")
|
||
lines.append(" · 查看全部:python main.py -h")
|
||
lines.append(" · 查看分组:python main.py article -h")
|
||
return "\n".join(lines)
|
||
if "one of the arguments" in m and "required" in m:
|
||
lines.append(" · 本命令要求下面几组参数里「必须选其中一组」,不能都不写。")
|
||
if "--body-file" in m and "--body" in m:
|
||
lines.append(" · 请任选其一:--body-file 某文件路径 或 --body \"正文文字\"")
|
||
else:
|
||
lines.append(f" · 说明:{m}")
|
||
lines.append(" · 查看该子命令:python main.py article add -h")
|
||
return "\n".join(lines)
|
||
if "unrecognized arguments:" in m:
|
||
tail = m.split("unrecognized arguments:", 1)[-1].strip()
|
||
lines.append(f" · 多写了不认识的参数:{tail},请删除或检查拼写。")
|
||
lines.append(" · 查看用法:python main.py -h")
|
||
return "\n".join(lines)
|
||
if "invalid choice:" in m:
|
||
lines.append(f" · {m}")
|
||
return "\n".join(lines)
|
||
if "expected one argument" in m:
|
||
lines.append(f" · {m}")
|
||
lines.append(" · 提示:--xxx 后面必须跟一个值,不要忘记。")
|
||
return "\n".join(lines)
|
||
lines.append(f" · {m}")
|
||
lines.append(" · 查看帮助:python main.py -h")
|
||
return "\n".join(lines)
|
||
|
||
|
||
class ZhArgumentParser(argparse.ArgumentParser):
|
||
def error(self, message: str) -> None:
|
||
print(explain_argparse_error(message), file=sys.stderr)
|
||
self.exit(2)
|