我想使用Cython将C函数导入到IPython笔记本中。目前,我正在尝试复制Cython documentation中的示例,但是我收到了编译错误。
我的Python代码(来自iPython笔记本):
import cython
%load_ext Cython
---------------------------------- new cell
%%cython
cdef extern from "spam.c":
void order_spam(int tons)
我的C代码:
// spam.c
#include <stdio.h>
static void order_spam(int tons)
{
printf("Ordered %i tons of spam!\n", tons);
}
运行此代码,我收到以下回溯和错误消息:
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
我已尝试在Google上搜索此错误,但我似乎找不到任何相关内容。
答案 0 :(得分:6)
%cython
魔法命令probaby似乎无法解决问题。 %cython
magic命令在这里没有真正完成任务。为了编译它,您还需要提供*.c
源文件,%cython
不允许(据我所知)。 ( The source file for it indicates that it only uses the text entered in the cell as a source file. )
C
功能:在提出可能的解决方案之前,请允许我指出您创建的.pyx
文件实际上并未自动包裹C
函数order_spam
。如果您在cpdef
块中将其指定为cdef extern
,则可以将其自动换行(或者您可以将它自己包裹在cdef extern
块之外,这样可以提供更大的灵活性。/ p>
我将使用cyspam.pyx
的文件名作为Cython文件:
cdef extern from "spam.c":
cpdef void order_spam(int tons)
注意我如何用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]))
您可以通过简单的文本编辑器创建这样的文件,也可以使用%%writefile
magic命令通过IPython
创建。 setup.py
脚本当然应与cyspam.pyx
和spam.c
文件放在同一目录中。
您可以为此打开终端或使用IPython
中的 %%bash
命令,无论哪种方式都可以。发出以下命令:
python setup.py build_ext --inplace
--inplace
将生成的.so
文件放在当前目录中。
完成这些操作后,您可以轻松导入cyspam
中的文件Ipython
,然后只需调用已包装的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!
作为替代方案,您始终可以创建一个.pyxbld
文件,指定pyximport.install()
所需的参数。这提供了相同级别的控制,但对于已经具有使用setup.py
脚本经验的Python用户来说,这很可能是违反直觉的。
参见相关内容: