安装pyinstaller库,
pip install pyinstaller
pip install pyinstaller -i https://pypi.tuna.tsinghua.edu.cn/simple
安装位置可以是虚拟环境也可以安装在base环境,运行是启用不同终端即可
main.py
主程序代码:
import subprocess
import platform
import os
import time
from ico import to_icon
def open_terminal_and_execute_command(command):
# 根据不同操作系统设置打开终端的命令
if platform.system() == 'Windows':
command = F'start cmd /k "{command}"'
elif platform.system() == 'Linux':
command = F'gnome-terminal -- bash -c "{command}; exec bash"'
elif platform.system() == 'Darwin': # macOS
command = F'terminal -e "{command}"'
else:
raise Exception("Unsupported operating system")
# 打开终端并执行命令
process = subprocess.Popen(command, shell=True)
process.wait()
def wait_for_conversion_complete(output_path):
while not os.path.exists(output_path):
pass
return 1
def status(status_num):
# 转换过程状态
if status_num == 0:
print('\n')
print("<<--------------转换中--------------->>")
print('\n')
elif status_num == 1:
print("***************转换完成****************")
else:
print("!!!!!!!!!!!!!!!转换失败!!!!!!!!!!!!!!!!")
def get_path(file_path):
# 得到上一级路径
path = os.path.dirname(file_path)
return path
def get_name(path):
# 得到转换文件名(无后缀)
name = os.path.basename(path)
return name
def run():
# 转换流程
input_path = input("将要转换的py文件绝对路径复制到此:")
output_path = os.getcwd() + "\dist\\" + get_name(input_path)[:-3] + ".exe"
try:
key = input("是否要配置图标 [yes/no] ")
if key == 'yes':
#print("<<<<<运行ico.py文件获取图标>>>>>")
path = input("输入要作为图标的图片路径:")
path = to_icon(path)
time.sleep(3)
command = F"Pyinstaller -F -i {path} {input_path}"
else:
command = F"Pyinstaller -F {input_path}"
open_terminal_and_execute_command(command)
status(0)
status(wait_for_conversion_complete(output_path))
print("转换后的exe文件位置:" + output_path)
except Exception as e:
status(2)
print(str(e))
if __name__ == "__main__":
run()
input()
如果想对生成后的exe文件配置icon图标
from PIL import Image
import time
def extension_replace(path,extension):
for i in range(1,len(path)):
if (path[-i] == '.'):
new_path = path.replace(path[-i+1:],extension)
break
return new_path
def to_icon(path):
#path = input("图片路径:")
img = Image.open(path)
size = (128,128)
icon = img.resize(size,Image.LANCZOS) #提取像素
name = extension_replace(path,'ico') #替换文件后缀名
icon.save(name)
#print("icon文件路径"+name)
return name