首页 > 解决方案 > 编译 Cython 扩展后 Python traceback.format_tb 不能完全工作

问题描述

源代码:example/example.py

import traceback


def run():
    try:
        assert 1 == 0
    except Exception as e:
        log_info = f'Erase failed, exception={type(e).__name__},\n{e},\n{"".join(traceback.format_tb(e.__traceback__))}'
        print('*********************')
        print(log_info)
        print('*********************')

setup.py

from setuptools import setup
from setuptools.extension import Extension
from Cython.Build import cythonize

setup(name='example',
      version="0.0",
      ext_modules=cythonize(
          [
              Extension("example.*", ["example/**/*.py"]),
          ],
          build_dir="build",
          compiler_directives=dict(always_allow_keywords=True,
                                   language_level='3')))

构建命令:python setup.py build

编译前的输出

*********************
Erase failed, exception=AssertionError,
,
  File "example/example.py", line 6, in run
    assert 1 == 0
*********************

编译后的输出

*********************
Erase failed, exception=AssertionError,
,
  File "example/example.py", line 6, in example.example.run

*********************

标签: pythoncythoncythonize

解决方案


这是意料之中的,因为在 Cython 将您的代码转换为 C 并编译本机模块之后,不再需要引用 Python 代码。

问题https://github.com/cython/cython/issues/1755是相关的,但它也已经开放了 3 年以上。


推荐阅读