使用cx_Freeze将Python脚本转为exe时的文件名读取异常问题
问题解决方法
一、修复cx_Freeze打包后文件名显示问题
你的脚本中os.path.basename(__file__)获取的是原始.py文件的名称,因为cx_Freeze打包后__file__仍指向源文件路径,而非生成的.exe。要获取实际运行的可执行文件名,需修改dork.py代码:
import os import sys import time # 判断是否为打包后的可执行环境 if getattr(sys, 'frozen', False): # 打包状态下,获取exe文件路径 current_file = sys.executable else: # 未打包状态下,获取py文件路径 current_file = __file__ print(os.path.basename(current_file)) time.sleep(3)
同时,你的setup.py中include_files: ['/']配置完全错误,会尝试包含系统根目录所有文件,需删除该配置:
from cx_Freeze import setup, Executable build_exe_options = { 'packages': ['os','time'], } setup( name='YourAppName', version='1.0', description='Your App Description', options={'build_exe': build_exe_options}, executables=[Executable('dork.py')] )
重新执行python setup.py build打包,生成的exe运行后会正确显示dork.exe。
二、PyInstaller打包错误处理
先尝试基础打包命令:
pyinstaller --onefile dork.py
若仍报错,按以下方向排查:
- 缺失依赖:提示找不到模块时,用
--hidden-import手动添加,例:pyinstaller --onefile --hidden-import os --hidden-import time dork.py - 路径问题:确保脚本所在目录无中文路径,且当前命令行处于该目录下
- 权限问题:用管理员权限打开命令提示符后再执行打包命令
内容的提问来源于stack exchange,提问作者Mergen Celasun
相关产品推荐
相关产品推荐

