【问题标题】:Getting started with cython on mac os在 mac os 上开始使用 cython
【发布时间】:2014-03-12 06:05:41
【问题描述】:

我用python写了一个简单的程序:

// main.py
import re
links = re.findall('(https?://\S+)', 'http://google.pl http://youtube.com')
print(links)

然后我执行这个:

cython main.py

生成了一个文件:main.c 然后我尝试了这个:

gcc main.c

我有一个错误:

main.c:8:10: fatal error: 'pyconfig.h' file not found
#include "pyconfig.h"
         ^
1 error generated.

如何将python编译成c?如何在 mac 上使用 xcode 开始使用 cython?

【问题讨论】:

    标签: python c++ xcode macos cython


    【解决方案1】:

    您必须使用-I 标志告诉gcc 编译器您系统上的pyconfig.h 文件在哪里。您可以使用find 程序找到它。

    更简单的编译方式是使用setup.py 模块。 Cython 提供了一个 cythonize 函数,该函数为 .pyx 模块启动此过程。

    您缺少的另一点是 Cython 文件通常定义要从主要 Python 模块使用的辅助函数

    假设您对目录和文件进行了以下设置:

    cython-start/
    ├── main.py
    ├── setup.py
    └── split_urls.pyx
    

    setup.py的内容是

    from distutils.core import setup
    from Cython.Build import cythonize
    
    setup(name="My first Cython app",
          ext_modules=cythonize('split_urls.pyx'),  # accepts a glob pattern
          )
    

    split_urls.pyx文件的内容是

    import re
    
    def do_split(links):
        return re.findall('(https?://\S+)', links)
    

    它是main.py 模块,使用了定义的 Cython 函数

    import split_urls
    
    URLS = 'http://google.pl http://youtube.com'
    print split_urls.do_split(URLS)
    

    通过发出以下命令编译 Cython 模块:

    $ python setup.py build_ext --inplace
    Cythonizing split_urls.pyx
    running build_ext
    building 'split_urls' extension
    creating build
    creating build/temp.macosx-10.9-x86_64-2.7
    ... compiler output ...
    

    并检查您的主模块是否正在做它应该做的事情:

    $ python main.py
    ['http://google.pl', 'http://youtube.com']
    

    【讨论】:

    • 或者,您可以将main.py 重命名为main.pyx,然后按照logc 的说明创建并运行setup.py。然后,您可以在控制台中执行 import main 或在 shell 中执行 python -c "import main"
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多