Nuitka-好用的 Python 打包工具

· · 科技·工程

0x01 前言

有时候我们写了一个 Python 项目,想要在任何地方都能运行它,但不想重复配置环境和依赖,于是就想到了打包的方法。

网上最多的打包教程是使用 Pyinstaller,但它打包后的文件实在太大了,而且运行比较慢,对于一些项目不太友好。

所以,我来介绍一下另外一款实用的打包工具 Nuitka。

0x02 Nuitka 基本介绍

::::info[官网的介绍]

Nuitka is the optimizing Python compiler written in Python that creates executables that run without a separate installer. Data files can both be included or put alongside.

Nuitka is fully compatible with Python 3 (3.4 — 3.13) and Python 2 (2.6, 2.7), and works on Windows, macOS, Linux, and more — essentially, wherever Python is already compatible with your system.
Nuitka 是一个用来将 Python 代码打包为可执行文件,方便其在没有相关环境的系统上运行的工具(不然为什么用这个当文章标题)。

其原理为:将 Python 代码转换成 C 代码,以提高运行速度。

该工具支持 Python 3(3.4-3.13) 和 Python 2(2.6-2.7)。

该工具需要以下依赖:

C 编译器(OIer 应该都装过吧)推荐使用 mingw-w64,可以去 SourceForge 下载安装,安装完成后输入 gcc --version 检查安装。

然后 pip install nuitka 安装 Nuitka。

0x04 基本使用

Nuitka 基本命令长这样:

python -m nuitka --lto=no --onefile --standalone 1.py

在 Windows 下,这个命令可以把 1.py 打包成一个 exe 文件。

::::info[官网的参数介绍] ::::

不想看这一堆参数可以让 AI 生成命令。

我用 AI 写了一个 Python 的游戏,想把它变成 exe 文件,于是再让 AI 写了一个打包脚本。

::::info[脚本代码]

import os
import subprocess
import sys

def build_with_nuitka():
    """使用Nuitka进行更优化的打包,生成更小的exe文件"""

    # 获取当前目录
    current_dir = os.path.dirname(os.path.abspath(__file__))

    # Nuitka命令参数 - 简化版本
    cmd = [
        sys.executable,
        '-m', 'nuitka',
        # '--standalone',           # 独立可执行文件
        '--onefile',              # 打包成单个文件
        '--windows-disable-console',  # 禁用控制台窗口
        '--enable-plugin=anti-bloat',  # 启用反膨胀插件
        '--include-module=pygame',     # 包含pygame模块
        '--nofollow-import-to=tkinter',   # 排除tkinter
        '--nofollow-import-to=matplotlib', # 排除matplotlib
        '--nofollow-import-to=numpy',    # 排除numpy
        '--nofollow-import-to=pandas',   # 排除pandas
        '--output-dir=./dist_nuitka',  # 输出目录
        '--assume-yes-for-downloads',  # 自动下载依赖
        # '--quiet',                # 静默模式,减少输出
        'main.py'
    ]

    print("正在使用Nuitka进行优化打包...")
    print(f"命令: {' '.join(cmd)}")

    try:
        # 执行打包命令
        result = subprocess.run(cmd, cwd=current_dir, capture_output=True, text=True)

        if result.returncode == 0:
            print("✅ Nuitka打包成功!")
            print(f"生成的exe文件位置: {os.path.join(current_dir, 'dist_nuitka', 'main.exe')}")
            print("文件大小应该比PyInstaller打包的小30-50%")
        else:
            print("❌ Nuitka打包失败!")
            print("错误信息:")
            print(result.stderr)

    except FileNotFoundError:
        print("❌ 未找到Nuitka,请先安装:")
        print("pip install nuitka")
    except Exception as e:
        print(f"❌ 打包过程中出现错误: {e}")

def build_with_cx_freeze():
    """使用cx_Freeze进行打包"""

    # cx_Freeze setup脚本内容
    setup_content = '''
import sys
import os
from cx_Freeze import setup, Executable

# 基础配置
build_exe_options = {
    "packages": ["pygame", "random", "math", "json", "socket", "threading"],
    "excludes": ["tkinter", "matplotlib", "numpy", "pandas", "test"],
    "include_files": [],
    "optimize": 2,
    "compressed": True,
    "copy_dependent_files": True,
    "create_shared_zip": False,
    "include_in_shared_zip": False,
    "zip_includes": [],
    "zip_exclude_packages": ["pygame"],
    "build_exe": "./dist_cxfreeze"
}

# 设置可执行文件
base = None
if sys.platform == "win32":
    base = "Win32GUI"

setup(
    name="ZD-2D-Gunfight",
    version="1.0",
    description="2D射击游戏",
    options={"build_exe": build_exe_options},
    executables=[Executable("main.py", base=base)]
)
'''

    # 写入setup脚本
    with open('setup_cxfreeze.py', 'w', encoding='utf-8') as f:
        f.write(setup_content)

    cmd = [sys.executable, 'setup_cxfreeze.py', 'build']

    print("正在使用cx_Freeze进行打包...")
    try:
        result = subprocess.run(cmd, cwd=current_dir, capture_output=True, text=True)

        if result.returncode == 0:
            print("✅ cx_Freeze打包成功!")
            print(f"生成的exe文件位置: {os.path.join(current_dir, 'dist_cxfreeze')}")
        else:
            print("❌ cx_Freeze打包失败!")
            print(result.stderr)

    except FileNotFoundError:
        print("❌ 未找到cx_Freeze,请先安装:")
        print("pip install cx_Freeze")

if __name__ == "__main__":
    print("请选择打包方式:")
    print("1. Nuitka (推荐,文件更小)")
    print("2. cx_Freeze")

    choice = input("请输入选择 (1或2): ").strip()

    if choice == "1":
        build_with_nuitka()
    elif choice == "2":
        build_with_cx_freeze()
    else:
        print("无效选择,退出")

::::

运行后效果如下:

请选择打包方式:
1. Nuitka (推荐,文件更小)
2. cx_Freeze
请输入选择 (1或2): 1
正在使用Nuitka进行优化打包...
命令: C:\Users\ruijie\anaconda3\python.exe -m nuitka --onefile --windows-disable-console --enable-plugin=anti-bloat --include-module=pygame --nofollow-import-to=tkinter --nofollow-import-
-plugin=anti-bloat --include-module=pygame --nofollow-import-to=tkinter --nofollow-import-to=matp-assume-yes-for-downloads main.py
lotlib --nofollow-import-to=numpy --nofollow-import-to=pandas --output-dir=./dist_nuitka --assume
-yes-for-downloads main.py
✅ Nuitka打包成功!
生成的exe文件位置: E:\python-game\zd-2d-gunfight\dist_nuitka\main.exe
文件大小应该比PyInstaller打包的小30-50%

整个生成过程大概几分钟,之后就可以在设定的路径看到生成好的文件了。

运行很流畅。