Skip to content
Advertisement

Getting started with cython on mac os

I wrote a simple program in python:

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

Then I execute this:

cython main.py

It was generated a file: main.c And then I tried this:

gcc main.c

And I have an error:

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

How to compile python to c ? How to get started with cython with xcode on mac ?

Advertisement

Answer

You have to tell the gcc compiler where is the pyconfig.h file on your system using the -I flag. You can find it using the find program.

A simpler way to compile the module is using a setup.py module. Cython provides a cythonize function that starts this process for a .pyx module.

Another point you are missing is that Cython files usually define helper functions to be used from a main Python module.

Suppose you have the following setup as for dirs and files:

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

The contents of the setup.py are

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
      )

The contents of the split_urls.pyx file are

import re

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

And it is the main.py module which uses the defined Cython function:

import split_urls

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

Compile the Cython module by issuing:

$ 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 ...

And check that your main module is doing what it is supposed to do:

$ python main.py
['http://google.pl', 'http://youtube.com']
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement