You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python转可执行文件体积优化:将6MB压缩至4MB以下方案咨询

Python打包体积优化方法(从6MB压缩到4MB以下)

针对你的代码,以下是具体的体积优化方案,按实施优先级排序:

1. 清理代码冗余导入

你的代码中存在未使用的导入,直接删除可减少打包时的模块包含:

# 原冗余导入:from requests import get, post(post未使用)、import time(未使用)
# 修改后代码
from requests import get
from sseclient import SSEClient
import subprocess

server_uri = 'http://127.0.0.1/server.php'
try:
    my_id = get('https://api.ipify.org').text

    try:
        server = get(server_uri)
        print(server.headers)

        messages = SSEClient(server_uri)
        subprocess.call('ipconfig', shell=True) 

    except Exception as e:
        print("you can't connect to server\n")

except Exception as e:
    print("Please check your internet connection\n")

2. 替换重型依赖为标准库

requests库体积较大,而你仅用到GET请求,可改用Python标准库urllib.request替代,完全消除第三方依赖:

from urllib.request import urlopen
from sseclient import SSEClient
import subprocess

server_uri = 'http://127.0.0.1/server.php'
try:
    with urlopen('https://api.ipify.org') as response:
        my_id = response.read().decode('utf-8')

    try:
        with urlopen(server_uri) as response:
            print(dict(response.headers))
            messages = SSEClient(server_uri)
            subprocess.call('ipconfig', shell=True) 

    except Exception as e:
        print("you can't connect to server\n")

except Exception as e:
    print("Please check your internet connection\n")

3. PyInstaller优化打包命令

使用PyInstaller时,添加以下参数最小化体积:

pyinstaller --onefile --noconsole --exclude-module tkinter --exclude-module numpy --upx-dir ./upx your_script.py
  • --onefile:生成单个可执行文件
  • --noconsole:无需控制台窗口时启用(可选)
  • --exclude-module:排除默认可能被打包的冗余模块(如tkinter、numpy)
  • --upx-dir:指定UPX工具路径,用UPX压缩可执行文件

4. 独立UPX压缩

若PyInstaller集成的UPX压缩效果不足,单独使用UPX最高压缩率参数:

upx --best --lzma your_executable.exe

5. 改用轻量打包工具Nuitka

Nuitka将Python代码编译为C代码后打包,体积远小于PyInstaller,命令示例:

nuitka --standalone --onefile --windows-disable-console your_script.py

内容的提问来源于stack exchange,提问作者daniel doval

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 09:07:32