Recherche…


Regrouper un programme Cython en utilisant pyinstaller

Démarrer à partir d'un programme Cython avec un point d'entrée:

def do_stuff():
    cdef int a,b,c
    a = 1
    b = 2
    c = 3
    print("Hello World!")
    print([a,b,c])
    input("Press Enter to continue.")

Créez un fichier setup.py dans le même dossier:

from distutils.core import setup
from Cython.Build import cythonize
setup(
    name = "Hello World",
    ext_modules = cythonize('program.pyx'), 
)

Le python setup.py build_ext --inplace avec python setup.py build_ext --inplace produira une bibliothèque .pyd dans un sous-dossier.

Après cela, créez un script Python en utilisant la bibliothèque (par exemple, main.py ) et placez le fichier .pyd à côté:

import program
program.do_stuff()

Utilisez PyInstaller pour regrouper pyinstaller --onefile "main.py" . Cela créera un sous-dossier contenant l'exécutable d'une taille de 4 Mo + contenant la bibliothèque plus le runtime python.

Automatisation de la construction (Windows)

Pour l'automatisation de la procédure ci-dessus sous Windows, utilisez un .bat du contenu similaire:

del "main.exe"
python setup.py build_ext --inplace
del "*.c"
rmdir /s /q ".\build"
pyinstaller --onefile "main.py"
copy /y ".\dist\main.exe" ".\main.exe"
rmdir /s /q ".\dist"
rmdir /s /q ".\build"
del "*.spec"
del "*.pyd"

Ajout de Numpy au bundle

Pour ajouter Numpy à l'ensemble, modifiez le mot-clé setup.py avec include_dirs et importez-le dans le script Python de l'encapsuleur pour notifier Pyinstaller.

program.pyx :

import numpy as np
cimport numpy as np


def do_stuff():
    print("Hello World!")
    cdef int n
    n = 2
    r = np.random.randint(1,5)
    print("A random number: "+str(r))
    print("A random number multiplied by 2 (made by cdef):"+str(r*n))
    input("Press Enter to continue.")

setup.py :

from distutils.core import setup, Extension
from Cython.Build import cythonize
import numpy

setup(
    ext_modules=cythonize("hello.pyx"),
    include_dirs=[numpy.get_include()]
)

main.py :

import program
import numpy
program.do_stuff()


Modified text is an extract of the original Stack Overflow Documentation
Sous licence CC BY-SA 3.0
Non affilié à Stack Overflow