Fra*_*Fra 10 c python macos swig anaconda
我正在尝试按照本教程编译一个简单的python/C示例:
http://www.swig.org/tutorial.html
我在MacOS上使用Anaconda python.
但是,当我跑
gcc -c example.c example_wrap.c -I/Users/myuser/anaconda/include/
Run Code Online (Sandbox Code Playgroud)
我明白了:
example_wrap.c:130:11: fatal error: 'Python.h' file not found
# include <Python.h>
^
Run Code Online (Sandbox Code Playgroud)
似乎在一些问题中报告了这个问题:
但似乎没有一个在MacOS上提供Anaconda特有的答案
有人解决了吗?
War*_*ser 21
使用该选项-I/Users/myuser/anaconda/include/python2.7的gcc命令.(假设您使用的是python 2.7.更改名称以匹配您正在使用的python版本.)您可以使用该命令python-config --cflags获取完整的推荐编译标记集:
$ python-config --cflags
-I/Users/myuser/anaconda/include/python2.7 -I/Users/myuser/anaconda/include/python2.7 -fno-strict-aliasing -I/Users/myuser/anaconda/include -arch x86_64 -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes
Run Code Online (Sandbox Code Playgroud)
但是,要构建扩展模块,我建议使用一个简单的安装脚本,如下所示setup.py,并distutils为您找出所有编译和链接选项.
# setup.py
from distutils.core import setup, Extension
example_module = Extension('_example', sources=['example_wrap.c', 'example.c'])
setup(name='example', ext_modules=[example_module], py_modules=["example"])
Run Code Online (Sandbox Code Playgroud)
然后你可以运行:
$ swig -python example.i
$ python setup.py build_ext --inplace
Run Code Online (Sandbox Code Playgroud)
(看一下setup.py运行时回显到终端的编译器命令.)
distutils了解SWIG,因此example_wrap.c您可以包含example.i并将swig由安装脚本自动运行,而不是包含在源文件列表中:
# setup.py
from distutils.core import setup, Extension
example_module = Extension('_example', sources=['example.c', 'example.i'])
setup(name='example', ext_modules=[example_module], py_modules=["example"])
Run Code Online (Sandbox Code Playgroud)
使用上面的版本setup.py,您可以使用single命令构建扩展模块
$ python setup.py build_ext --inplace
Run Code Online (Sandbox Code Playgroud)
一旦你构建了扩展模块,你应该能够在python中使用它:
>>> import example
>>> example.fact(5)
120
Run Code Online (Sandbox Code Playgroud)
如果您不想使用该脚本setup.py,这里有一组对我有用的命令:
$ swig -python example.i
$ gcc -c -I/Users/myuser/anaconda/include/python2.7 example.c example_wrap.c
$ gcc -bundle -undefined dynamic_lookup -L/Users/myuser/anaconda/lib example.o example_wrap.o -o _example.so
Run Code Online (Sandbox Code Playgroud)
注意:我使用的是Mac OS X 10.9.4:
$ gcc --version
Configured with: --prefix=/Library/Developer/CommandLineTools/usr --with-gxx-include-dir=/usr/include/c++/4.2.1
Apple LLVM version 5.1 (clang-503.0.40) (based on LLVM 3.4svn)
Target: x86_64-apple-darwin13.3.0
Thread model: posix
Run Code Online (Sandbox Code Playgroud)