我正在构建一个Python应用程序,不想强迫我的客户端安装Python和模块。

那么,是否有一种方法可以将Python脚本编译为独立的可执行文件?


当前回答

使用py2exe……使用下面的设置文件:

from distutils.core import setup
import py2exe

from distutils.filelist import findall
import matplotlib

setup(
    console = ['PlotMemInfo.py'],

    options = {
        'py2exe': {
            'packages': ['matplotlib'],
            'dll_excludes': ['libgdk-win32-2.0-0.dll',
                             'libgobject-2.0-0.dll',
            'libgdk_pixbuf-2.0-0.dll']
        }
    },
    data_files = matplotlib.get_py2exe_datafiles()
)

其他回答

我也推荐使用PyInstaller以获得更好的向后兼容性,例如Python 2.3 - 2.7。

对于py2exe,你必须有Python 2.6。

您可以使用PyInstaller将Python程序打包为独立的可执行文件。它可以在Windows、Linux和Mac上运行。

PyInstaller Quickstart Install PyInstaller from PyPI: pip install pyinstaller Go to your program’s directory and run: pyinstaller yourprogram.py This will generate the bundle in a subdirectory called dist. pyinstaller -F yourprogram.py Adding -F (or --onefile) parameter will pack everything into single "exe". pyinstaller -F --paths=<your_path>\Lib\site-packages yourprogram.py running into "ImportError" you might consider side-packages. pip install pynput==1.6.8 still runing in Import-Erorr - try to downgrade pyinstaller - see Getting error when using pynput with pyinstaller For a more detailed walkthrough, see the manual.

pyinstaller yourfile.py -F --onefile

这将在Windows上创建一个独立的EXE文件。

重要提示1:EXE文件将生成在名为“dist”的文件夹中。

重要提示2:不要忘记—onefile标志

您可以使用pip install PyInstaller安装PyInstaller

注意:在极少数情况下,存在隐藏的依赖关系…所以如果你运行EXE文件并得到丢失库错误(下面的例子中是win32timezone),然后使用这样的方法:

pyinstaller --hiddenimport win32timezone -F "Backup Program.py"

由于它似乎没有出现在当前的答案列表中,我认为值得一提的是,标准库包含一个zipapp模块,可用于此目的。它的基本用途是将一堆Python文件压缩成一个扩展名为.pyz的zip文件,可以直接作为Python myapp执行。Pyz,但是你也可以从requirements.txt文件中创建一个自包含的包:

$ python -m pip install -r requirements.txt --target myapp
$ python -m zipapp -p "interpreter" myapp

其中解释器可以是/usr/bin/env python(请参阅指定解释器)。

通常,生成的.pyz / .pyzw文件应该是可执行的,在Unix中,因为它被这样标记,在Windows中,因为Python安装通常会注册这些扩展名。然而,只要用户在路径中有python3.dll,就可以相对容易地创建一个Windows可执行文件。

如果您不想要求最终用户安装Python,您可以将应用程序与可嵌入的Python包一起分发。

您可以在“分布实用程序”中找到列出的分布实用程序列表。

我使用bbfreeze,它一直工作得很好(虽然还没有Python 3支持)。