【教程】Ubuntu下将python脚本编译为可执行文件

一、准备环境

1.1 安装

安装pyinstaller,这里建议python版本在3.0以上并且不要使用3.6(亲测其他版本用pyinstaller后仍旧会出现各种缺库的问题)。

安装pyinstaller

pip3 install pyinstaller

正常情况下,此时就能够使用pyinstaller,但是如果当前用户不是root或没有sudo权限,则会出现如下问题:

pyinstaller
pyinstaller: command not found

需要按照以下步骤进行配置。

1.2 配置

检查pyinstaller是否安装成功,输出如下信息表明安装成功。

pip3 show pyinstaller

Name: pyinstaller
Version: 6.9.0
Summary: PyInstaller bundles a Python application and all its dependencies into a single package.
Home-page: https://www.pyinstaller.org/
Author: Hartmut Goebel, Giovanni Bajo, David Vierra, David Cortesi, Martin Zibricky
Author-email: None
License: GPLv2-or-later with a special exception which allows to use PyInstaller to build and distribute non-free programs (including commercial ones)
Location: xxxxxxxxxxxxxxxxxxx
Requires: setuptools, altgraph, pyinstaller-hooks-contrib, importlib-metadata, packaging
Required-by:

检查 local/bin 下是否存在pyinstaller

ll /home/用户名/.local/bin

-rwxrwxr-x 1 xxx xxx  249 7月  11 17:37 pyinstaller

加入环境变量使其能够在任意目录执行(或在第二部时直接用绝对路径执行pyinstaller)

export PATH=$PATH:~/.local/bin

二、使用

2.1 打包

第一步完成后,通过以下命令查看其是否能够使用

pyinstaller --version
6.9.0

打包

pyinstaller --onefile python_file.py

如果需要将相关静态文件导入:

pyinstaller --onefile --add-data "config.json:." python_file.py

如果这两条命令仍旧无法满足,可以使用spec 文件进行高级配置,笔者这里没有用过就不举例了。

2.2 输出

打包完成后默认位置在 /home/zhaoshuai/.local/bin/dist

posted @ 2024-07-11 18:36  小拳头呀  阅读(20)  评论(0编辑  收藏  举报