前言:最近需要使用 Python 写一个脚本,但是我不想在所在机器安装 Python 环境,因此就在想有没有可以把 Python 脚本打包为可执行的二进制程序,找到了 Nuitka,一个强大的 Python 编译器,可以将 Python 代码编译为 C 代码,并生成高效的可执行文件。除了之外还有其他的,选择 Nuitka 是因为它的性能比较好。
环境
OS:Ubuntu 24.04 LTS
需要装安装包:
| |
实践
Hello World
先来一个比较简单的程序,文件名为 hello_world.py,主要内容如下:
| |
写完后,然后进行打包为二进制程序,使用如下命令:
| |
参数说明:
--standalone:生成包含所有依赖的独立目录。--onefile:将结果打包为单个可执行文件。--follow-imports:自动包含所有导入的模块。--show-progress:显示编译进度。--output-dir=dist:指定输出目录。
一个更加复杂的示例:FastAPI 提供简单的 WebServer
| |
生成二进制文件和上面那个类似,不过有一点需要注意的是,在打包之前需要把需要的包装好了,然后才能打包。
FAQ
apt/dnf/yum install patchelf' first.
详细错误如下: python -m nuitka –standalone –onefile –follow-imports –show-progress –output-dir=dist hello_world.py Nuitka-Options:Used command line options: Nuitka-Options: –standalone –onefile –follow-imports –show-progress –output-dir=dist hello_world.py FATAL:Error,standalone mode on Linux requires ‘patchelf’ to be installed。Use ‘apt/dnf/yum install patchelf’ first。
解决方法如下:
| |
