You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Cython编译报错expected an identifier,exec方法引发问题求助

Cython编译含exec方法的Python文件报错原因解析

问题场景

我正在使用Cython将Python文件转换为pyd文件,测试代码funcA.py如下:

# funcA.py
class Window:

    def exec(self):
        pass
    pass

setup.py文件内容为:

#setup.py
from setuptools import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext

ext_modules = [
    Extension('funcA', ['funcA.py']),
]

setup(
    name='App',
    ext_modules=ext_modules,
    include_dirs=["App"],
    cmdclass={'build_ext': build_ext},
)

执行命令 python setup.py build_ext --inplace 后出现报错:

Error compiling Cython file:
------------------------------------------------------------
...

class Window:

    def exec(self):
       ^
------------------------------------------------------------

funcA.py:4:8: Expected an identifier
building 'funcA' extension
"C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.29.30133\bin\HostX86\x64\cl.exe" /c /nologo /O2 /W3 /GL /DNDEBUG /MD -IApp -ID:\Anaconda3\envs\work\include -ID:\Anaconda3\envs\work\Include "-IC:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.29.30133\ATLMFC\include" "-IC:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.29.30133\include" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.19041.0\ucrt" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.19041.0\shared" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.19041.0\um" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.19041.0\winrt" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.19041.0\cppwinrt" /TcfuncA.c /Fobuild\temp.win-amd64-cpython-39\Release\funcA.obj
funcA.c
funcA.c(1): fatal error C1189: #error:  Do not use this file, it is the result of a failed Cython compilation.
error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio\\2019\\Community\\VC\\Tools\\MSVC\\14.29.30133\\bin\\HostX86\\x64\\cl.exe' failed with exit code 2

但将funcA.py修改为以下内容时,编译正常:

#new funcA.py
class Window:

    pass

已通过在脚本顶部添加 #cython: language_level=3 解决问题,现说明报错原因。

报错原因

  • 在Python 2中,exec是关键字,不能用作标识符(比如方法名、变量名);而Python 3里exec被改为内置函数,不再是关键字,因此可以作为方法名使用。
  • Cython默认的语言级别如果未明确指定,可能会根据环境默认采用Python 2的语法规则,此时exec会被识别为关键字,用它定义方法就会触发"Expected an identifier"的语法错误。
  • 添加#cython: language_level=3后,Cython会切换到Python 3的语法模式,不再将exec视为关键字,因此对应的方法名能被正常编译。

内容的提问来源于stack exchange,提问作者Qiang Zhang

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 18:45:29