サーチ…


pyinstallerを使ったCythonプログラムのバンドル

エントリポイントを持つCythonプログラムから開始する:

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.")

setup.pyファイルを同じフォルダに作成します:

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を実行すると、 .pydライブラリがサブフォルダに作成されます。

その後、ライブラリ(例えば、 main.py )を使ってバニラのPythonスクリプトを作成し、 .pydファイルをその横に.pydます:

import program
program.do_stuff()

pyinstallerを使用してpyinstallerをバンドルしpyinstaller --onefile "main.py" 。これにより、ライブラリとPythonランタイムを含む4 MB +サイズの実行可能ファイルを含むサブフォルダが作成されます。

ビルドの自動化(Windows)

Windowsで上記の手順を自動化するには、同様の内容の.batを使用します。

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を追加する

バンドルにNumpyを追加するには、 setup.pyinclude_dirsキーワードで変更し、必要に応じてnumpyをラッパーPythonスクリプトにインポートして、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
ライセンスを受けた CC BY-SA 3.0
所属していない Stack Overflow