在 Mac OS 上开始使用 cython

Getting started with cython on mac os

本文关键字:cython 开始 Mac OS      更新时间:2023-10-16

我用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?

您必须

使用 -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)

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

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']