Cython compiler directive的language_level未生效,编译报错求助
language_level=3 Directive Not Being Recognized Let's work through resolving this compilation error step by step:
1. Fix the Obvious Command Typo
First, I notice you're running cythonize -i world_dep.pyx but your code lives in temp.pyx—that's likely a copy-paste mistake. Make sure you target the correct file:
cythonize -i temp.pyx
2. Force Python 3 Syntax via Command Line
If the file-level directive isn't being picked up, bypass it by specifying the language level directly in the cythonize command:
cythonize -i -3 temp.pyx
The -3 flag tells Cython to enforce Python 3 syntax rules, which will properly recognize the sep parameter in your print() call.
3. Update Your Cython Version
Older versions of Cython had inconsistent support for the language_level=3 directive. Check your current version first:
cython --version
If you're on a version older than 0.29, upgrade to the latest stable release:
pip install --upgrade cython
Newer versions handle the language_level directive much more reliably.
4. Use a setup.py for Explicit Configuration
For more control, define the compiler directive in a setup.py file instead of relying on the file-level comment. Create this file in the same directory as temp.pyx:
from setuptools import setup from Cython.Build import cythonize setup( ext_modules=cythonize( "temp.pyx", compiler_directives={"language_level": "3"} ) )
Then compile with:
python setup.py build_ext --inplace
This method ensures the language level is explicitly set during the build process, eliminating ambiguity.
Why This Happens
The error (Expected '...' at the sep parameter) is a classic Python 2 syntax issue—Python 2's print statement doesn't support keyword arguments like sep. This means Cython was still parsing your code as Python 2, despite your language_level=3 directive. Common causes include outdated Cython versions, conflicting global configurations, or typos in your command/file path.
内容的提问来源于stack exchange,提问作者Saim Raza

