PyInstaller,如何包含pip安装的外部包中的数据文件?

时间:2017-09-28 16:58:57

标签: python python-3.5 pyinstaller

问题

我正在尝试使用PyInstaller创建一个供公司内部使用的应用程序。该脚本在工作的python环境中运行良好,但在转换为包时会丢失一些东西。

我知道如何在我的软件包中包含和引用我自己需要的数据文件,但是我在导入时应该包含或引用文件时遇到问题。

我正在使用一个名为tk-tools的可安装pip的软件包,其中包含一些用于面板式显示的漂亮图像(看起来像LED)。问题是,当我创建一个pyinstaller脚本时,任何时候引用其中一个图像,我都会收到错误:

DEBUG:aspen_comm.display:COM23 19200
INFO:aspen_comm.display:adding pump 1 to the pump list: [1]
DEBUG:aspen_comm.display:updating interrogation list: [1]
Exception in Tkinter callback
Traceback (most recent call last):
  File "tkinter\__init__.py", line 1550, in __call__
  File "aspen_comm\display.py", line 206, in add
  File "aspen_comm\display.py", line 121, in add
  File "aspen_comm\display.py", line 271, in __init__
  File "aspen_comm\display.py", line 311, in __init__
  File "lib\site-packages\tk_tools\visual.py", line 277, in __init__
  File "lib\site-packages\tk_tools\visual.py", line 289, in to_grey
  File "lib\site-packages\tk_tools\visual.py", line 284, in _load_new
  File "tkinter\__init__.py", line 3394, in __init__
  File "tkinter\__init__.py", line 3350, in __init__
_tkinter.TclError: couldn't open "C:\_code\tools\python\aspen_comm\dist\aspen_comm\tk_tools\img/led-grey.png": no such file or directory

我查看了最后一行中的那个目录 - 这是我的发行版所在的位置 - 并且发现没有tk_tools目录。

问题

如何让pyinstaller收集导入包的数据文件?

规范文件

目前,我的datas是空白的。使用pyinstaller -n aspen_comm aspen_comm/__main__.py

创建的规范文件
# -*- mode: python -*-

block_cipher = None


a = Analysis(['aspen_comm\\__main__.py'],
             pathex=['C:\\_code\\tools\\python\\aspen_comm'],
             binaries=[],
             datas=[],
             hiddenimports=[],
             hookspath=[],
             runtime_hooks=[],
             excludes=[],
             win_no_prefer_redirects=False,
             win_private_assemblies=False,
             cipher=block_cipher)

pyz = PYZ(a.pure, a.zipped_data,
             cipher=block_cipher)

exe = EXE(pyz,
          a.scripts,
          exclude_binaries=True,
          name='aspen_comm',
          debug=False,
          strip=False,
          upx=True,
          console=True )

coll = COLLECT(exe,
               a.binaries,
               a.zipfiles,
               a.datas,
               strip=False,
               upx=True,
               name='aspen_comm')

当我在/build/aspen_comm/out00-Analysis.toc/build/aspen_comm/out00-PYZ.toc内查看时,我发现一个看起来像tk_tools包的条目。此外,tk_tools包的功能在找到数据文件之前完美运行,因此我知道它正在某处导入,我只是不知道在哪里。当我搜索tk_tools时,我在文件结构中找不到对它的引用。

我也尝试了--hidden-imports选项,结果相同。

部分解决方案

如果我使用datas = [('C:\\_virtualenv\\aspen\\Lib\\site-packages\\tk_tools\\img\\', 'tk_tools\\img\\')]中的datas=datasAnalysis“手动”添加指定文件的路径,则所有内容均按预期工作。这将工作,但我宁愿PyInstaller找到包数据,因为它已明确安装。我会继续寻找解决方案,但是 - 目前 - 我可能会使用这种非理想的解决方法。

如果您控制了包裹......

然后你可以在子包上使用stringify,但这只适用于你自己的包。

6 个答案:

答案 0 :(得分:2)

我通过利用spec文件是被执行的Python代码的事实解决了这个问题。您可以在PyInstaller构建阶段动态获取包的根,并在datas列表中使用该值。就我而言,我在.spec文件中有类似的内容:

import os
import importlib

package_imports = [['package_name', ['file0', 'file1']]

datas = []
for package, files in package_imports:
    proot = os.path.dirname(importlib.import_module(package).__file__)
    datas.extend((os.path.join(proot, f), package) for f in files)

并使用生成的datas列表作为Analysis的参数。

答案 1 :(得分:2)

这里使用的是与Turn相同的想法。就我而言,我需要一个在kivy_garden内的软件包(zbarcam)。但是我试图在这里概括该过程。

from os.path import join, dirname, abspath, split
from os import sep
import glob
import <package>

pkg_dir = split(<package>.__file__)[0]
pkg_data = []
pkg_data.extend((file, dirname(file).split("site-packages")[1]) for file in glob.iglob(join(pkg_dir,"**{}*".format(sep)), recursive=True))

答案 2 :(得分:1)

以下代码会将您目录中的所有PNG文件放入名为imgs的捆绑应用顶层的文件夹中:

datas=[("C:\\_code\\tools\\python\\aspen_comm\\dist\\aspen_comm\\tk_tools\\img\\*.png", "imgs")],

然后,您可以在代码中使用os.path.join("imgs", "your_image.png")引用它们。

答案 3 :(得分:1)

已编辑添加

为了更永久地解决这个问题,我创建了一个名为stringify的pip可安装包,它将获取一个文件或目录并将其转换为python字符串,以便pyinstaller等软件包将它们识别为本机python文件

查看project page,欢迎提供反馈!

原始答案

答案有点迂回,处理tk_tools打包而不是pyinstaller的方式。

最近有人告诉我一种技术,其中二进制数据(如图像数据)可以存储为base64字符串:

with open(img_path, 'rb') as f:
    encoded_string = base64.encode(f.read())

编码字符串实际存储数据。如果原始包只是将包文件存储为字符串而不是图像文件,并创建一个python文件,该数据可以作为字符串变量访问,那么可以简单地以{{1}的形式在包中包含二进制数据无需干预即可查找和检测。

考虑以下功能:

pyinstaller

如果def create_image_string(img_path): """ creates the base64 encoded string from the image path and returns the (filename, data) as a tuple """ with open(img_path, 'rb') as f: encoded_string = base64.b64encode(f.read()) file_name = os.path.basename(img_path).split('.')[0] file_name = file_name.replace('-', '_') return file_name, encoded_string def archive_image_files(): """ Reads all files in 'images' directory and saves them as encoded strings accessible as python variables. The image at images/my_image.png can now be found in tk_tools/images.py with a variable name of my_image """ destination_path = "tk_tools" py_file = '' for root, dirs, files in os.walk("images"): for name in files: img_path = os.path.join(root, name) file_name, file_string = create_image_string(img_path) py_file += '{} = {}\n'.format(file_name, file_string) py_file += '\n' with open(os.path.join(destination_path, 'images.py'), 'w') as f: f.write(py_file) 放置在安装文件中,那么只要运行安装脚本(在创建和安装轮子期间),就会自动创建archive_image_files()

我可能会在不久的将来改进这项技术。谢谢大家的帮助,

Ĵ

答案 4 :(得分:0)

Mac OS X 10.7.5 Pyinstaller;为app.spec文件中的每个图像使用1行代码(而不是单独的行)添加图像。这就是我用来使图像与脚本一起编译的所有代码。 将此功能添加到以下位置:yourappname.py:

# Path to the resources, (pictures and files) needed within this program def resource_path(relative_path): """ Get absolute path to resource, works for dev and for PyInstaller """ try:

# PyInstaller creates a temp folder and stores path in _MEIPASS base_path = sys._MEIPASS

   except Exception:
        base_path = os.path.abspath(".")
        return os.path.join(base_path, relative_path)`  

此外,在appname.py脚本中,添加此“ resource_path”以从资源中获取图像,如下所示:

yourimage = PhotoImage(file=resource_path("yourimage.png"))

在您的appname.spec文件中,将'datas = []替换为您要使用的图像路径。我只使用了“ * .png”图像文件,这对我有用:

datas=[("/Users/rodman/PycharmProjects/tkinter/*.png", ".")],

请确保将/ Users / rodman / PycharmProjects / tkinter /替换为图像所在文件夹的路径。请原谅草率的代码格式,我不习惯这些代码标签,感谢Steampunkery指导我朝正确的方向努力,以找出Mac OS X答案。

答案 5 :(得分:0)

参加聚会有点晚,但是写了一篇关于我如何做到的帮助文章:

https://www.linkedin.com/pulse/loading-external-module-data-during-pyinstaller-bundling-deguzis/?published=t

摘要:

import os
import pkgutil
import PyInstaller.__main__
import platform
import shutil
import sys


# Get mypkg data not imported automagically
# Pre-create location where data is expected
if not os.path.exists('ext_module'):
    os.mkdir('ext_module')

with open ('ext_module' + os.sep + 'some-env.ini', 'w+') as f:
    data = pkgutil.get_data( 'ext_module', 'some-env.ini' ).decode('utf-8', 'ascii')
    f.write(data)

# Set terminator (PyInstaller does not provide an easy method for this)
# ':' for OS X / Linux
# ';' for Windows
if platform.system() == 'Windows':
    term = ';'
else:
    term = ':'


PyInstaller.__main__.run([
        '--name=%s' % 'mypkg',
        '--onefile',
        '--add-data=%s%smypkg' % (os.path.join('mypkg' + os.sep + 'some-env.ini'),term),
        os.path.join('cli.py'),
    ])


# Cleanup
shutil.rmtree('mypkg')