%%cython
命令对于创建 cython 函数非常方便,而无需构建和使用包。该命令有几个选项,但我找不到在那里指定编译时环境变量的方法。
我想要相当于:
from Cython.Distutils.extension import Extension
ext = Extension(...
cython_compile_time_env={'MYVAR': 10},
...)
为
%%cython
命令。我已经尝试过:
%%cython -cython_compile_time_env={'MYVAR':10}
IF MYVAR:
def func():
return 1
ELSE:
def func():
return 2
但这会引发异常:
Error compiling Cython file:
------------------------------------------------------------
...
IF MYVAR:
^
------------------------------------------------------------
...\.ipython\cython\_cython_magic_28df41ea67fec254f0be4fc74f7a6a54.pyx:2:8: Compile-time name 'MYVAR' not defined
和
%%cython --cython_compile_time_env={'MYVAR':10}
IF MYVAR:
def func():
return 1
ELSE:
def func():
return 2
throw
UsageError: unrecognized arguments: --cython_compile_time_env={'MYVAR':10}
最佳答案
这是一种解决方法而不是适当的解决方案,但它实现了所需的行为。总之,没有办法提供compile_time_env
通过 %%cython
魔术,但调用 cythonize
选择可以直接修改的默认编译器选项。对于上面的示例,请尝试以下操作。
from Cython.Compiler.Main import default_options
default_options['compile_time_env'] = {'MYVAR': 0}
# Running the magic and calling `func` yields 2
default_options['compile_time_env'] = {'MYVAR': 1}
# Running the magic and calling `func` yields 1
关于python - Cython ipython 魔术与编译时环境变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41526545/