pyins如何在可执行文件中包含json

2024-09-26 17:43:32 发布

您现在位置:Python中文网/ 问答频道 /正文

尝试使用以下内容构建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')

就像Clint在add json file with pysintaller中推荐的一样

但不起作用。

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

Tags: 文件thenamejsonfalsetrue可执行文件added
1条回答
网友
1楼 · 发布于 2024-09-26 17:43:32

当您添加带有^{}标志的文件时,在运行时,该文件将被解压到一个临时目录中,如C:/User/Appdata/local/temp/_MEI41482。因此,您需要从这个目录加载文件。在

您可以使用^{}获取当前临时目录并从中加载文件。在

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)

然后生成可执行文件:

^{pr2}$

相关问题 更多 >

    热门问题