Search code examples
pythonjsonpyinstallerspecifications

How to include json in executable file by pyinstaller


Tried to build specs.spec file with the following, to include a JSON file within the executable file.


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')

just like Clint recommended in add json file with pysintaller

BUT not working.

  1. Build spec file like so in the cmd - pyi-makespec specs.py
  2. Then build Executable - pyinstaller.exe --onefile --windowed --icon=logo1.ico script.py
  3. NOT WORKING without the JSON file placed in the same directory as the executable file
  4. Any suggestions?

Solution

  • After you add your files with add-data flag, on runtime those would be extracted into a temp directory like C:/User/Appdata/local/temp/_MEIXXX, so you need to load the files from this directory.

    You can use sys._MEIPASS to get the current temp directory and load your file from there.

    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)
    

    Then generate your executable adding the --add-data flag:

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

    Additional non-binary files or folders to be added to the executable. The path separator is platform specific, os.pathsep (which is ; on Windows and : on most unix systems) is used. This option can be used multiple times.

    # The path separator is ; on Windows and : on most unix systems
    pyinstaller -F --add-data "configREs.json;." script.py