cython
Cython-buntning
Sök…
Bundling ett Cython-program med pyinstaller
Börja från ett Cython-program med en startpunkt:
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.")
Skapa en setup.py
fil i samma mapp:
from distutils.core import setup
from Cython.Build import cythonize
setup(
name = "Hello World",
ext_modules = cythonize('program.pyx'),
)
Att köra den med python setup.py build_ext --inplace
kommer att skapa ett .pyd
bibliotek i en undermapp.
Skapa sedan ett vanilj-Python-skript med hjälp av biblioteket (t.ex. main.py
) och lägg .pyd
filen bredvid den:
import program
program.do_stuff()
Använd PyInstaller för att paketera den pyinstaller --onefile "main.py"
. Detta skapar en undermapp som innehåller den körbara filen med en storlek på 4 MB + som innehåller biblioteket plus Python-körtiden.
Automatisera build (Windows)
För automatisering av ovanstående procedur i Windows använder du en .bat
med liknande innehåll:
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"
Lägga till Numpy i bunten
För att lägga till Numpy i paketet, ändra setup.py
med nyckelordet include_dirs
och importera numpy i omslaget Python-skriptet för att meddela 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()