cython
Cython-bundeling
Zoeken…
Een Cython-programma bundelen met pyinstaller
Start vanuit een Cython-programma met een startpunt:
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.")
Maak een setup.py bestand in dezelfde map:
from distutils.core import setup
from Cython.Build import cythonize
setup(
name = "Hello World",
ext_modules = cythonize('program.pyx'),
)
Als het wordt uitgevoerd met python setup.py build_ext --inplace wordt een .pyd bibliotheek in een submap geproduceerd.
Maak daarna een vanille Python-script met behulp van de bibliotheek (bijv. main.py ) en plaats het .pyd bestand ernaast:
import program
program.do_stuff()
Gebruik PyInstaller om het te bundelen pyinstaller --onefile "main.py" . Hiermee maakt u een submap met het uitvoerbare bestand van 4 MB + en de bibliotheek plus de python-runtime.
Build automatiseren (Windows)
Gebruik voor de automatisering van de bovenstaande procedure in Windows een .bat van dezelfde inhoud:
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"
Numpy toevoegen aan de bundel
Om Numpy aan de bundel toe te voegen, wijzigt u het setup.py met include_dirs sleutelwoord en importeert u de numpy in het wrapper Python-script om Pyinstaller op de hoogte te stellen.
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()