【问题标题】:Porting cython files from python2 to python3 with 2to3使用 2to3 将 cython 文件从 python2 移植到 python3
【发布时间】:2017-11-04 20:01:56
【问题描述】:

我有一个在 python2.7 下开发的 python 包,但我需要将它移植到 python3.6 。我在代码的某些部分使用了 cython,因此该软件包同时具有 .py.pyx 文件。

我尝试了2to3 命令,但出现了一个我既无法理解也无法解决的错误。

示例:我有以下test.pyx 文件

# cython: profile=False
cimport cython

@cython.boundscheck(False)
@cython.wraparound(False)
@cython.profile(False)
cpdef sillyfunction():
    print 'Thank you for your kind help'
    return

然后我运行2to3 test.pyx。我得到的是:

user@machine:~$ 2to3 test.pyx
RefactoringTool: Skipping optional fixer: buffer
RefactoringTool: Skipping optional fixer: idioms
RefactoringTool: Skipping optional fixer: set_literal
RefactoringTool: Skipping optional fixer: ws_comma
RefactoringTool: Can't parse test.pyx: ParseError: bad input: type=1, value=u'cython', context=(u' ', (2, 8))
RefactoringTool: No files need to be modified.
RefactoringTool: There was 1 error:
RefactoringTool: Can't parse test.pyx: ParseError: bad input: type=1, value=u'cython', context=(u' ', (2, 8))

【问题讨论】:

    标签: python cython python-2to3


    【解决方案1】:

    您不需要做任何事情。 Cython 接受一个参数 language_level(请参阅 http://cython.readthedocs.io/en/latest/src/reference/compilation.html#compiler-directives),该参数控制它将代码解释为 Python 2 或 Python 3 的位置(例如,print 作为函数或语句)。

    无论您执行哪个代码,它生成的代码都应该可以编译以与 Python 2 或 Python 3 一起使用(这取决于您包含的标头,这主要由构建过程安排)。生成的 C 代码中有很多预处理器#if PY_MAJOR_VERSION >= 3 部分来确保这一点。

    我怀疑这种兼容性存在一些限制,我当然不希望所有 Python 3 功能在针对 Python 2 编译时都能完美运行,但作为一般规则,您应该能够使用现有的 Cython 代码,使用language_level=2(默认)在其上运行 Cython,然后使用 Python 3 头文件/库(默认情况下 setup.py 应负责)对其进行编译,它应该可以工作。不过,您可能需要解决一些小的具体问题。

    【讨论】:

      猜你喜欢
      • 2021-10-30
      • 2018-05-30
      • 2021-01-11
      • 1970-01-01
      • 2020-12-28
      • 2015-06-17
      • 1970-01-01
      • 2020-01-17
      相关资源
      最近更新 更多