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

时间:2019-07-20 07:19:08

标签: python json pyinstaller specifications

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

就像add json file with pysintaller中推荐的克林特

但无法正常工作。

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

1 个答案:

答案 0 :(得分:1)

使用add-data标志添加文件时,在运行时文件将被提取到 this.control.valueChanges .pipe( debounceTime(1000), // Waiting for 1 sec while you are typing distinctUntilChanged() // Prevents the emitting if the 'start' value and the 'end' value are the same ) .subscribe(value => { console.log(value); // TODO: call BE here with this.httpClient... }); 之类的临时目录中。因此,您需要从该目录加载文件。

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

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)