py2app打包Mac应用运行时出现Wand库PNG文件写入CoderError错误
问题根因
你遇到的报错核心原因是运行时工作目录权限不匹配:
- 你在代码中使用相对路径
PatDrawFig1.png保存文件,PyCharm运行时默认工作目录是你的本地工程文件夹,你对该路径有写入权限,所以运行正常。 - py2app打包后的
.app程序双击运行时,系统默认工作目录为系统根目录/,普通用户没有根目录的写入权限,因此Wand调用ImageMagick写文件时抛出WriteBlob Failed错误。
修复步骤
1. 替换相对路径为用户可写的绝对路径
将保存路径修改为用户目录下的可读写路径(如下载文件夹、桌面),修改后的代码参考:
import os def fig_one(full_text, ct): target_width = 375 y_offset = 0 y_padding = 5 x_padding = 7 # 新增:获取用户下载文件夹的绝对路径 save_path = os.path.join(os.path.expanduser("~/Downloads"), "PatDrawFig1.png") with Image(width=2000, height=5000, pseudo='xc:white') as fig1: for match in find_matches(text=full_text): with Drawing() as ctx: ctx.font_size = 20 ctx.text_alignment = 'center' words = match.split(" ") word_count = len(words) while True: temp_text = rebuild_text(words, word_count, str(ct)) metrics = ctx.get_font_metrics(fig1, temp_text, multiline=True) if metrics.text_width > target_width: word_count -= 1 else: text = temp_text target_height = int(metrics.text_height + 1) break ctx.push() ctx.fill_color = 'white' ctx.stroke_width = 3 ctx.stroke_color = 'black' ctx.rectangle(2, y_offset + y_padding, width=2*x_padding+target_width, height=2*y_padding+target_height) ctx.pop() ctx.text(x_padding+3 + (target_width // 2), 10 + 4*y_padding+y_offset, text) ctx(fig1) y_offset += target_height + 4*y_padding - 2 ct += 2 fig1.trim() # 替换为绝对路径保存 fig1.save(filename=save_path) # 打开图片也使用绝对路径 open_image(save_path) exit()
2. py2app打包补充配置(适配无依赖环境)
Wand依赖系统的ImageMagick动态库,如果你需要打包的应用可以在未安装ImageMagick的设备上运行,需要在py2app的setup.py配置中添加ImageMagick相关动态库到打包列表:
from setuptools import setup APP = ['PatDrawDemo.py'] DATA_FILES = [] OPTIONS = { 'argv_emulation': True, # 新增:将本地ImageMagick的动态库和编码文件打包进.app,brew安装的ImageMagick默认路径如下 'frameworks': ['/usr/local/opt/imagemagick/lib/libMagickCore-7.Q16HDRI.dylib', '/usr/local/opt/imagemagick/lib/libMagickWand-7.Q16HDRI.dylib'], 'packages': ['wand'], } setup( app=APP, data_files=DATA_FILES, options={'py2app': OPTIONS}, setup_requires=['py2app'], )
3. 分发前额外操作
如果需要将应用分发给其他Mac用户,需要对应用进行签名和公证,否则其他用户打开时会收到「文件已损坏」的系统提示。
内容的提问来源于stack exchange,提问作者Jimmy Wede
相关产品推荐
相关产品推荐

