如何通过pyinstaller在可执行文件中包含json

Omr*_*mri 3 python json specifications pyinstaller

尝试specs.spec使用以下内容构建文件,以在可执行文件中包含 JSON 文件。


block_cipher = None

added_files = [
         ( 'configREs.json', '.'),  # Loads the '' file from
                                    # your root folder and outputs it with
                                    # the same name on the same place.
         ]


a = Analysis(['gui.pyw'],
             pathex=['D:\\OneDrive\\Programming\\Python Projects\\Python'],
             binaries=[],
             datas=added_files,
             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='name here',
          debug=False,
          strip=False,
          upx=True,
          console=False, icon='iconname.ico', version='version.rc' )
coll = COLLECT(exe,
               a.binaries,
               a.zipfiles,
               a.datas,
               strip=False,
               upx=True,
               name='gui')
Run Code Online (Sandbox Code Playgroud)

就像 Clint 在使用 pysintaller 添加 json 文件中推荐的一样

但不工作。

  1. 在 cmd 中像这样构建规范文件 - pyi-makespec specs.py
  2. 然后构建可执行文件 - pyinstaller.exe --onefile --windowed --icon=logo1.ico script.py
  3. 如果 JSON 文件与可执行文件位于同一目录中,则无法工作
  4. 有什么建议?

M. *_* R. 8

添加带有add-data标志的文件后,在运行时这些文件将被提取到临时目录中,例如C:/User/Appdata/local/temp/_MEIXXX,因此您需要从此目录加载文件。

您可以使用sys._MEIPASS获取当前临时目录并从那里加载您的文件。

import os
import sys


def resource_path(relative_path):
    if hasattr(sys, '_MEIPASS'):
        return os.path.join(sys._MEIPASS, relative_path)
    return os.path.join(os.path.abspath("."), relative_path)


if __name__ == "__main__":
    scope = ['https://spreadsheets.google.com/feeds',
             'https://www.googleapis.com/auth/drive']
    credentials = ServiceAccountCredentials.from_json_keyfile_name(
        resource_path('configREs-.json'), scope)
    client = gspread.authorize(credentials)
Run Code Online (Sandbox Code Playgroud)

然后生成您的可执行文件添加--add-data标志:

--add-data <SRC;DEST 或 SRC:DEST>

要添加到可执行文件的其他非二进制文件或文件夹。路径分隔符是特定于平台的,使用 os.pathsep (在 Windows 上为 ; ,在大多数 unix 系统上为 : )。此选项可以多次使用。

# The path separator is ; on Windows and : on most unix systems
pyinstaller -F --add-data "configREs.json;." script.py
Run Code Online (Sandbox Code Playgroud)