Building a Hello World program

As is the tradition with programming languages, we will start with a Hello World example. Unlike with Python, we need to compile Cython code. We start with a .pyx file, from which we will generate C code. This .c file can be compiled and then imported into a Python program.

How to do it...

This section describes how to build a Cython Hello World program.

  1. Write the hello.pyx code.

    First, we will write some pretty trivial code that prints "Hello World". This is just normal Python code, but the file has the pyx extension.

    def say_hello():
    print "Hello World!"
  2. Write a distutils setup.py script.

    We need to create a file named setup.py to help us build the Cython code.

    from distutils.core import setup
    from distutils.extension import Extension
    from Cython.Distutils import build_ext
    
    ext_modules = [Extension("hello", ["hello.pyx"])]
    
    setup(
            name = 'Hello world app',
            cmdclass = {'build_ext': build_ext},
            ext_modules = ext_modules
         )

    As you can see, we specified the file from the previous step and gave our application a name.

  3. Build using the following command:
    python setup.py build_ext --inplace

    This will generate C code, compile it for your platform, and will produce the following output

    running build_ext
    cythoning hello.pyx to hello.c
    building 'hello' extension
    creating build

    Now, we can import our module with the following statement:

    from hello import say_hello

How it works...

In this recipe we did a traditional Hello World example. Cython is a compiled language, so we needed to compile our code. We wrote a .pyx file containing the Hello World code and a setup.py file that was used to generate and build the C code.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
52.14.17.40