From 7911b4de54e0742cd2241a9c2d575c002b14ab2e Mon Sep 17 00:00:00 2001 From: TermiNexus Date: Sun, 18 Oct 2026 18:07:19 +0800 Subject: [PATCH] =?UTF-8?q?feat(cli):=20=E7=BC=96=E8=AF=91=E6=9C=9F?= =?UTF-8?q?=E9=94=99=E8=AF=AF=E6=8C=89=20Viper=20=E6=A8=A1=E6=8B=9F?= =?UTF-8?q?=E5=A0=86=E6=A0=88=E8=BE=93=E5=87=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit TypeError/SyntaxError 输出 Traceback (compile-time) + File/line + 源码行 + Err,不再打印 Python 内部调用链。 --- Projectrans.py | 19 ++++++++++++++++++- lib/Projectrans/Utils.py | 4 ++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/Projectrans.py b/Projectrans.py index d5a2551..9b8b811 100644 --- a/Projectrans.py +++ b/Projectrans.py @@ -41,7 +41,24 @@ if __name__ == '__main__': _timing_status: str = '成功' except (TypeError, SyntaxError) as _e: _timing_status = '失败' - _sys.stderr.write(f'{_e}\n') + import re as _re + _lines: list[str] = ['Traceback (most recent call last, compile-time):'] + _file: str = getattr(_e, 'Filename', '') or '' + _lineno: int = 0 + _m = _re.search(r'(?:第\s*|line\s*)(\d+)', str(_e)) + if _m: + _lineno = int(_m.group(1)) + if _file: + _lines.append(f' File "{_file}", line {_lineno}, in ') + try: + with open(_file, 'r', encoding='utf-8') as _f: + _src: list[str] = _f.read().splitlines() + if 0 < _lineno <= len(_src): + _lines.append(f' {_src[_lineno - 1].strip()}') + except Exception: + pass + _lines.append(f'Err: {_e}') + _sys.stderr.write('\n'.join(_lines) + '\n') raise SystemExit(1) except BaseException: _timing_status = '失败' diff --git a/lib/Projectrans/Utils.py b/lib/Projectrans/Utils.py index 2700ea9..701ddbf 100644 --- a/lib/Projectrans/Utils.py +++ b/lib/Projectrans/Utils.py @@ -92,6 +92,10 @@ def parse_python_file(filepath: str) -> tuple[str, ast.Module] | tuple[str, None tree: ast.Module = ast.parse(ExpandSoftKeywords(content), filepath) except SyntaxError: return (content, None) + except TypeError as _e: + if not getattr(_e, 'Filename', ''): + _e.Filename = filepath + raise _FILE_AST_CACHE[norm_path] = (mtime, content, tree) return (content, tree)