【问题标题】:Python.h not found using swig and Anaconda Python使用 swig 和 Anaconda Python 找不到 Python.h
【发布时间】:2014-11-10 23:49:33
【问题描述】:

我正在尝试按照本教程编译一个简单的 python/C 示例:

http://www.swig.org/tutorial.html

我在 MacOS 上使用 Anaconda python。

但是,当我跑步时

gcc -c example.c example_wrap.c -I/Users/myuser/anaconda/include/

我明白了:

example_wrap.c:130:11: fatal error: 'Python.h' file not found
# include <Python.h>
          ^

这个问题好像很多问题都反映了:

Missing Python.h while trying to compile a C extension module

Missing Python.h and impossible to find

Python.h: No such file or directory

但似乎没有一个提供特定于 MacOS 上 Anaconda 的答案

有人解决了吗?

【问题讨论】:

    标签: python c macos swig anaconda


    【解决方案1】:

    gcc 命令中使用选项-I/Users/myuser/anaconda/include/python2.7。 (假设您使用的是 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
    

    但是,要构建扩展模块,我建议使用简单的设置脚本,例如以下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"])
    

    然后就可以运行了:

    $ swig -python example.i
    $ python setup.py build_ext --inplace
    

    (查看运行setup.py 时回显到终端的编译器命令。)

    distutils 了解 SWIG,因此您可以将example.i 包括在源文件列表中,而不是在源文件列表中包括example_wrap.c,并且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"])
    

    使用以上版本的setup.py,您可以使用单个命令构建扩展模块

    $ python setup.py build_ext --inplace
    

    一旦你构建了扩展模块,你应该就可以在 python 中使用它了:

    >>> import example
    >>> example.fact(5)
    120
    

    如果您不想使用脚本 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
    

    注意:我使用的是 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
    

    【讨论】:

    • 太棒了!有效。很清楚的解释!谢谢
    • 感谢分享 setup.py 的使用技巧~~它适用于我在 mac osx 10.11 上~~
    猜你喜欢
    • 2016-09-17
    • 1970-01-01
    • 2018-09-09
    • 2015-05-13
    • 1970-01-01
    • 1970-01-01
    • 2014-10-20
    • 2021-05-28
    • 1970-01-01
    相关资源
    最近更新 更多