最近用python写了一个小工具,想打包成exe发给其他小伙伴使用,
目标是他直接运行exe可以正常使用,不用再安装开发环境。
我的开发环境是,pycharm 虚拟环境,
- 使用 pyinstaller
进入Terminal执行如下命令
pip install pyinstaller
pyinstaller -F main.py
运行完成后会在dist目录下生成main.exe,
使用cmd命令,运行main.exe 时提示如下:
PS D:\USERDATA\PycharmProjects\apple\dist> .\main.exe
Traceback (most recent call last):
File "main.py", line 6, in <module>
ModuleNotFoundError: No module named 'toml'
[19776] Failed to execute script main
因为我的main.py使用了toml模块,
from tkinter import *
from tkinter import messagebox
from tkinter import ttk
import requests
import toml
尝试了很多方法无法解决,最后使用方法2解决了。
- 使用 py2exe
工程根目录下,创建setup.py,内容如下:
# -*- encoding:utf-8 -*-
from distutils.core import setup
import py2exe
py2exe_options = {
#"includes": ["sip"],#If Qt Aplication,you need to add this line
"dll_excludes": ["MSVCP90.dll",], #miss these dll files
"compressed": 1,
#optimize:
#0 - don’t optimize (generate .pyc)
#1 - normal optimization (like python -O)
#2 - extra optimization (like python -OO)
"optimize": 2,
"ascii": 0,
#bundle_files:
#3 - create script.exe, python.dll, extensions.pyd, others.dll.
#2 - create script.exe, python.dll, others.dll.
#1 - create script.exe, others.dll.
#0 - create script.exe.
"bundle_files": 1,
}
setup(
name = 'Python_gui',
version = '1.0',
#If GUI ,use windows;else use console
windows = ['main.py',],
#console = ['main.py',],
zipfile = None,
#None : Not generate Zip file,and generate in exe file
options = {'py2exe': py2exe_options}
)
进入Terminal执行如下命令
pip install py2exe
python setup.py py2exe
打包过程如果提示找不到toml、requests 等第三方模块,则先执行命令安装一下后,在执行打包;
pip install toml
pip install requests
运行完成后会在dist目录下生成main.exe, 发给小伙伴,在他电脑上也能运行正常了。