如何使用Cython将外部C函数导入到IPython笔记本中?

Ali*_*bak 5 c python ipython cython

我想使用Cython将C函数导入到IPython笔记本中.目前,我正在尝试在Cython文档中复制该示例,但是我收到了编译错误.

我的Python代码(来自iPython笔记本):

import cython
%load_ext Cython
Run Code Online (Sandbox Code Playgroud)

----------------------------------新细胞

%%cython
cdef extern from "spam.c":
    void order_spam(int tons)
Run Code Online (Sandbox Code Playgroud)

我的C代码:

// spam.c
#include <stdio.h>

static void order_spam(int tons)
{
    printf("Ordered %i tons of spam!\n", tons);
}
Run Code Online (Sandbox Code Playgroud)

运行此代码,我得到以下回溯和错误消息:

CompileError                              Traceback (most recent call last)
<ipython-input-13-8bb733557977> in <module>()
----> 1 get_ipython().run_cell_magic(u'cython', u'', u'\ncdef extern from "spam.c":\n    void order_spam(int tons)')

/Users/danielacker/anaconda2/lib/python2.7/site-packages/IPython/core/interactiveshell.pyc in run_cell_magic(self, magic_name, line, cell)
   2118             magic_arg_s = self.var_expand(line, stack_depth)
   2119             with self.builtin_trap:
-> 2120                 result = fn(magic_arg_s, cell)
   2121             return result
   2122 

<decorator-gen-126> in cython(self, line, cell)

/Users/danielacker/anaconda2/lib/python2.7/site-packages/IPython/core/magic.pyc in <lambda>(f, *a, **k)
    191     # but it's overkill for just that one bit of state.
    192     def magic_deco(arg):
--> 193         call = lambda f, *a, **k: f(*a, **k)
    194 
    195         if callable(arg):

/Users/danielacker/anaconda2/lib/python2.7/site-packages/Cython/Build/IpythonMagic.py in cython(self, line, cell)
    276             build_extension.build_temp = os.path.dirname(pyx_file)
    277             build_extension.build_lib  = lib_dir
--> 278             build_extension.run()
    279             self._code_cache[key] = module_name
    280 

/Users/danielacker/anaconda2/lib/python2.7/distutils/command/build_ext.pyc in run(self)
    337 
    338         # Now actually compile and link everything.
--> 339         self.build_extensions()
    340 
    341     def check_extensions_list(self, extensions):

/Users/danielacker/anaconda2/lib/python2.7/distutils/command/build_ext.pyc in build_extensions(self)
    446 
    447         for ext in self.extensions:
--> 448             self.build_extension(ext)
    449 
    450     def build_extension(self, ext):

/Users/danielacker/anaconda2/lib/python2.7/distutils/command/build_ext.pyc in build_extension(self, ext)
    496                                          debug=self.debug,
    497                                          extra_postargs=extra_args,
--> 498                                          depends=ext.depends)
    499 
    500         # XXX -- this is a Vile HACK!

/Users/danielacker/anaconda2/lib/python2.7/distutils/ccompiler.pyc in compile(self, sources, output_dir, macros, include_dirs, debug, extra_preargs, extra_postargs, depends)
    572             except KeyError:
    573                 continue
--> 574             self._compile(obj, src, ext, cc_args, extra_postargs, pp_opts)
    575 
    576         # Return *all* object filenames, not just the ones we just built.

/Users/danielacker/anaconda2/lib/python2.7/distutils/unixccompiler.pyc in _compile(self, obj, src, ext, cc_args, extra_postargs, pp_opts)
    120                        extra_postargs)
    121         except DistutilsExecError, msg:
--> 122             raise CompileError, msg
    123 
    124     def create_static_lib(self, objects, output_libname,

CompileError: command 'gcc' failed with exit status 1
Run Code Online (Sandbox Code Playgroud)

我已经尝试在Google上搜索此错误,但我似乎找不到任何相关内容.

Jim*_*ard 8

%cython魔术命令probaby似乎并没有这样的伎俩.

%cython魔术的命令并没有真正做任务在这里.为了编译这个,您还需要提供*.c源文件,并且(据我所知)不允许%cython.(它的源文件表明它只使用在单元格中输入的文本作为源文件.)

包裹你的C功能:

在介绍可能的解决方案之前,我要指出.pyx您创建的文件实际上并没有自动包装该C函数order_spam.如果您将其指定为块cpdef内部,则可以将其自动cdef extern换行(或者您可以将其自身包裹在cdef extern块外部,这样可以提供更大的灵活性).

我将使用cyspam.pyxCython文件的文件名:

cdef extern from "spam.c":
    cpdef void order_spam(int tons)
Run Code Online (Sandbox Code Playgroud)

注意我是如何用函数声明作为前缀的cpdef,这指示Cython自动包装函数.

使用setup.py脚本:

为了完全控制编译过程,通常需要创建一个setup.py包含所有必需源的脚本,包括指定的目录等.

以下是setup.py脚本的外观:

from distutils.core import setup, Extension
from Cython.Build import cythonize

# you specify the c source file in the sources list
ext = Extension('cyspam', sources = ['cyspam.pyx', 'spam.c'])
setup(name="C spam", ext_modules = cythonize([ext]))
Run Code Online (Sandbox Code Playgroud)

您可以通过简单的文本编辑器或IPython使用%%writefilemagic命令创建这样的文件.该setup.py脚本当然应该放在cyspam.pyxspam.c文件相同的目录中.

编译文件:

您可以为此打开终端或使用%%bash命令IPython,无论哪种方式都可以.发出以下命令:

python setup.py build_ext --inplace 
Run Code Online (Sandbox Code Playgroud)

--inplace将生成的.so文件放在当前目录中.

做这些后,你可以很容易地导入该文件cyspamIpython并调用包裹C函数:

汇总所有命令IPython:

总而言之,如果您只想IPython从中发出以下命令,请执行以下命令:

In [1]: %%writefile setup.py
   ....: from distutils.core import setup, Extension
   ....: from Cython.Build import cythonize
   ....: ext = Extension('cyspam', sources = ['cyspam.pyx', 'spam.c'])
   ....: setup(name="C spam", ext_modules = cythonize([ext]))

In [2]: %%bash
   ...: python setup.py build_ext --inplace

In [3]: import cyspam

In [4]: cyspam.order_spam(1000)
You ordered 1000 ammount of spam!
Run Code Online (Sandbox Code Playgroud)

作为替代方案,您始终可以创建一个.pyxbld指定所需参数的文件pyximport.install().这提供了相同级别的控制,但对于已经具有使用setup.py脚本经验的Python用户来说,这很可能是违反直觉的.

见相关:

使用pyximport时如何设置Cython编译器标志?