在PyInstaller中将数据与.spec文件捆绑在一起

时间:2015-07-03 22:48:05

标签: python python-2.7 pyinstaller

所以我已经阅读了这里的所有问题而不能为我的生活看到为什么这不起作用。我有一个.spec文件,如下所示:

# -*- mode: python -*-

block_cipher = None


a = Analysis(['newtestsphinx.py'],
         pathex=['C:\\Program Files (x86)\\speechfolder'],
         hiddenimports=[],
         hookspath=None,
         runtime_hooks=None,
         excludes=None,
         cipher=block_cipher)
pyz = PYZ(a.pure,
         cipher=block_cipher)
exe = EXE(pyz,
      a.scripts,
      a.binaries,
      a.zipfiles,
      a.datas + [('grammar2.jsgf', 'C:\\Program Files (x86)\\speechfolder\\grammar2.jsgf', 'DATA')],
      name='newtestsphinx.exe',
      debug=False,
      strip=None,
      upx=True,
      console=True )

所以如果我了解它们就像所有的例子一样,我添加了' grammar2.jsgf'对于根目录中的捆绑包,我认为其格式为[' path_to_put_in',' path_its_in_now',' label']

然后我运行命令来创建我的新文件:

pyinstaller --onefile newtestsphinx.spec

我现在在代码中做的第一件事是:

print os.path.isfile('grammar2.jsgf')

它返回false 100%,我的程序也找不到要使用它的文件。任何帮助都会很棒,谢谢!

1 个答案:

答案 0 :(得分:1)

目前的问题是pyinstaller在运行时应该将一堆必要的支持文件提取到临时目录中。尝试访问这些支持文件时,您需要使用正确的目录名称预先访问文件。来自docs

import sys
import os

if getattr(sys, 'frozen', False):
    # we are running in a |PyInstaller| bundle
    basedir = sys._MEIPASS
else:
    # we are running in a normal Python environment
    basedir = os.path.dirname(__file__)

然后在尝试访问您的文件时:

print os.path.isfile(os.path.join(basedir, 'grammar2.jsgf'))

你应该看到它返回True。另一个有用的事情是打印出basedir,并确保执行不会结束,使用简单的东西:

raw_input('Press enter to end execution.')

这将允许您查看临时目录的位置 - 然后您可以进行一些探索,并了解它是如何工作的。