cython
Cython-Bündelung
Suche…
Cython-Programm mit pyinstaller bündeln
Beginnen Sie mit einem Cython-Programm mit einem Einstiegspunkt:
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.")
Erstellen Sie eine setup.py
Datei im selben Ordner:
from distutils.core import setup
from Cython.Build import cythonize
setup(
name = "Hello World",
ext_modules = cythonize('program.pyx'),
)
python setup.py build_ext --inplace
es mit python setup.py build_ext --inplace
, .pyd
python setup.py build_ext --inplace
eine .pyd
Bibliothek in einem Unterordner.
Anschließend erstellen Sie ein Vanilla-Python-Skript mit Hilfe der Bibliothek (z. B. main.py
) und platzieren die .pyd
Datei daneben:
import program
program.do_stuff()
Verwenden Sie PyInstaller, um es pyinstaller --onefile "main.py"
zu bündeln. Dadurch wird ein Unterordner erstellt, der die ausführbare Datei mit einer Größe von mindestens 4 MB enthält, die die Bibliothek sowie die Python-Laufzeit enthält.
Build automatisieren (Windows)
Zur Automatisierung des obigen Verfahrens in Windows verwenden Sie eine .bat
mit ähnlichen Inhalten:
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 zum Bundle hinzufügen
Um dem Paket Numpy hinzuzufügen, ändern Sie die setup.py
mit include_dirs
Schlüsselwort include_dirs
und importieren Sie den numpy-Code im Wrapper-Python-Skript, um Pyinstaller zu benachrichtigen.
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()