4

我有一个在 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))
4

1 回答 1

4

你不应该做任何事情。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 代码,在 Cython 上运行它使用language_level=2(默认),然后使用 Python 3 头文件/库(默认情况下 setup.py 应该处理)编译它,它应该可以工作。不过,您可能需要解决一些小的具体问题。

于 2017-11-04T20:20:14.763 回答