使用pyinstaller把python脚本打包成二进制文件

简介

python 代码语法简单,但是有一个很大的问题就是打包,如果你想把python打包成一个二进制的话可能会有很多的问题,这就显示出go语言的好处了,启动快,在什么平台上都是一个二进制文件

操作

使用pyinstaller编译python首先要安装

pip install -i https://pypi.tuna.tsinghua.edu.cn/simple PyInstaller

安装完成之后就是编译了

如果你想编译成单个二进制文件

pyinstaller -F main.py

但是编译成单个二进制文件会有一个问题就是启动的时候会有一个解压的过程,会很慢

直接编译成多个文件的话就没有启动慢这个问题

pyinstaller main.py

但是带来的问题也很显然,文件太多,不方便管理

1
2
3
4
5
6
7
8
9
10
11
12
13
➜  main git:(master) ✗ ls
Python _heapq.cpython-37m-darwin.so _sha512.cpython-37m-darwin.so libyaml-0.2.dylib
_bisect.cpython-37m-darwin.so _lzma.cpython-37m-darwin.so _socket.cpython-37m-darwin.so main
_blake2.cpython-37m-darwin.so _md5.cpython-37m-darwin.so _ssl.cpython-37m-darwin.so math.cpython-37m-darwin.so
_bz2.cpython-37m-darwin.so _multibytecodec.cpython-37m-darwin.so _struct.cpython-37m-darwin.so pyexpat.cpython-37m-darwin.so
_codecs_cn.cpython-37m-darwin.so _opcode.cpython-37m-darwin.so _yaml.cpython-37m-darwin.so readline.cpython-37m-darwin.so
_codecs_hk.cpython-37m-darwin.so _pickle.cpython-37m-darwin.so base_library.zip resource.cpython-37m-darwin.so
_codecs_iso2022.cpython-37m-darwin.so _posixsubprocess.cpython-37m-darwin.so binascii.cpython-37m-darwin.so select.cpython-37m-darwin.so
_codecs_jp.cpython-37m-darwin.so _random.cpython-37m-darwin.so grp.cpython-37m-darwin.so termios.cpython-37m-darwin.so
_codecs_kr.cpython-37m-darwin.so _scproxy.cpython-37m-darwin.so libcrypto.1.1.dylib unicodedata.cpython-37m-darwin.so
_codecs_tw.cpython-37m-darwin.so _sha1.cpython-37m-darwin.so liblzma.5.dylib zlib.cpython-37m-darwin.so
_datetime.cpython-37m-darwin.so _sha256.cpython-37m-darwin.so libreadline.8.dylib
_hashlib.cpython-37m-darwin.so _sha3.cpython-37m-darwin.so libssl.1.1.dylib

打包好的文件在

dist/main

这个目录下

如果你是在mac下面使用pyenv安装的pyinstaller的话,可能会碰到下面这个问题

1
2
3
4
5
6
7
This would mean your Python installation doesn't come with proper library files.
This usually happens by missing development package, or unsuitable build parameters of Python installation.

* On Debian/Ubuntu, you would need to install Python development packages
* apt-get install python3-dev
* apt-get install python-dev
* If you're building Python by yourself, please rebuild your Python with `--enable-shared` (or, `--enable-framework` on Darwin)

这个时候你就需要重新安装下你的python了

PYTHON_CONFIGURE_OPTS="--enable-framework" pyenv install 3.7.4

如果你在运行二进制文件的时候碰到下面的问题

1
2
3
4
5
6
Traceback (most recent call last):
File "main.py", line 117, in <module>
File "main.py", line 108, in main
File "main.py", line 57, in get_opt
NameError: name 'exit' is not defined
[32501] Failed to execute script main

你需要在脚本中导入exit函数

from sys import exit

欢迎关注Bboysoul的博客www.bboy.app

Have Fun

欢迎关注我的其它发布渠道