cython
Bundling Cython
Ricerca…
Raggruppamento di un programma Cython usando pyinstaller
Inizia da un programma Cython con un punto di accesso:
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.")
Creare un file setup.py
nella stessa cartella:
from distutils.core import setup
from Cython.Build import cythonize
setup(
name = "Hello World",
ext_modules = cythonize('program.pyx'),
)
Eseguendolo con python setup.py build_ext --inplace
produrrà una libreria .pyd
in una sottocartella.
Successivamente, crea uno script Python vanilla usando la libreria (ad esempio, main.py
) e metti il file .pyd
accanto a esso:
import program
program.do_stuff()
Usa PyInstaller per raggrupparlo pyinstaller --onefile "main.py"
. Questo creerà una sottocartella contenente l'eseguibile di una dimensione di 4 MB + contenente la libreria più il runtime di python.
Configurazione automatica (Windows)
Per l'automazione della procedura di cui sopra in Windows utilizzare un .bat
dei contenuti simili:
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"
Aggiunta di Numpy al pacchetto
Per aggiungere Numpy al pacchetto, modificare il file setup.py
con include_dirs
e importare il numpy nello script Python wrapper per notificare 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()