Protect Your Python Code with Cython (1)

Ship with Confidence: Protect Your Python Code with Cython

Distributing Your Python Code as an Executable with Cython

Ever wondered how to keep your Python code private when distributing software?

While obfuscation tools like Pyarmor add some protection, they can’t fully prevent someone from deciphering your code. Here’s where Cython comes in.

Cython is a compiler that lets you convert Python code into a compiled extension, like a .so file. This compiled extension can be included with your software and protects your original Python source code.

Here’s how to use Cython to create a distributable executable:

1. Install Cython:

Bash

pip install cython

2. Convert your Python script:

This file tells Cython which Python files to convert. Create a new file named setup.py with the following content, replacing cube.pyx with your file name:

Python
from setuptools import setup
from Cython.Build import cythonize

setup(
    ext_modules = cythonize("cube.pyx")
)

4. Build the Cython extension:

Run the following command in your terminal:

Bash
python setup.py build_ext --inplace

This command will generate two new files:

  • A .c file containing the compiled C code.
  • A .so file (or .pyd on Windows) containing the compiled extension.

Compiling the .c file (optional):

If you want a standalone executable, you can compile the generated .c file using a C compiler like GCC. This will create an executable file containing your Python code.

Using the compiled extension:

To use the compiled extension in another Python script, simply import it like a regular module. For example:

Python
from cube import cube
print("9 cubed =", cube(9))

Remember:

  • Place the .so file in the same directory as your Python script that uses it.

By following these steps, you can distribute your Python code as a compiled extension, protecting your source code while still providing a functional program to your clients.

Leave a Reply

Your email address will not be published. Required fields are marked *