Cython导入外部模块

时间:2017-10-06 15:10:31

标签: python c cython

我在cython中很天真,刚开始探索这个。所以我有一个非常基本的问题。我有一个python代码,我试图cythonize。我设法从原始pyx文件创建c源文件和头文件,该文件包含我的python / cython代码。但代码有以下几行:

XML_File = "some xml file name" 
import xml.etree.ElementTree as ET
tree = ET.parse(XML_File)

现在,当我使用调用C程序编译cythong C源代码并执行最终二进制文件时,我得到的错误是NameError: name 'ET' is not defined

那么如何正确导入外部模块/包,如" xml"或任何其他包裹,如" numpy"在我的python / cython代码中,是否也可以从Cython生成的C代码中访问它?

我的设置文件如下: 请注意,我只处理一个调用其他外部python模块的Python代码文件,例如" xml" " numpy的"等。

from distutils.core import setup
from distutils.extension import Extension
import sys, os
import numpy

#def find_libxml2_include():
#    include_dirs = []
#    for d in ['/usr/include/libxml2', '/usr/local/include/libxml2']:
#        if os.path.exists(os.path.join(d, 'libxml/tree.h')):
#            include_dirs.append(d)
#    return include_dirs


#Determine whether to use Cython
if '--cythonize' in sys.argv:
    cythonize_switch = True
    del sys.argv[sys.argv.index('--cythonize')]
else:
    cythonize_switch = False

#Find all includes
numpy_include = numpy.get_include()
#lxml_include = []
#for l in find_libxml2_include() + lxml.get_include():
#   lxml_include.append(l)

#Set up the ext_modules for Cython or not, depending
if cythonize_switch:
    from Cython.Distutils import build_ext
    from Cython.Build import cythonize
    ext_modules = cythonize([Extension("s2a_angle", ["s2a_angle_c.pyx"],include_dirs = [numpy_include, lxml_include])])
else:
    ext_modules = [Extension("s2a_angle", ["s2a_angle_c.c"],include_dirs = [numpy_include, lxml_include])]

#Create a dictionary of arguments for setup
setup_args = {'name':'s2a_angles',
    'version':'0.1.0',
    'author':'Sam Hayden',
    'author_email':'abc@a.gov',
    'packages':[],
    'py_modules' : [],
    'ext_modules' : ext_modules} 

#Add the build_ext command only if cythonizing
if cythonize_switch:
    setup_args['cmdclass'] = {'build_ext': build_ext}

#Finally
setup(**setup_args)

我也尝试将普通的cython C源与我的C调用接口集成如下:

gcc -I/usr/local/include/python2.7 *.c -lpython2.7 -lm -ldl -lpthread -lutil

0 个答案:

没有答案