python - Cython ipython 魔术与编译时环境变量

标签 python ipython cython ipython-magic

%%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/

相关文章:

python - Winsound python 不适用于已附加到的数组

python - 更改线条颜色

python - 如何将多个输入行组合成一个字符串?

python - 什么是 kernmagic 扩展?

python - 将 cython 函数与 cython 方法传递给 scipy.integrate

python - Cython:如何将 C 函数分配给 Python/Cython 变量?

python - 编译成功后无法导入已编译的cython函数

python - 从外部操纵 Firefox 的 View

python - 如果 fig = plt.figure() 在 Ipython Notebook 的另一个单元格中,则 add_subplot() 不起作用

python - 如何在eclipse中暂停python执行并返回交互式提示