Search code examples
python-3.xresourcespyinstallerpython-importlib

Python and Pyinstaller - How to import resource files?


I have a quite simple project in python3.6 (I can't change python version):

resources/
  __init__.py
  file.txt
start.py

with start.py containing :

import importlib_resources
import resources

with importlib_resources.path(resources, 'file.txt') as p:
  with open(p) as file:
    print(file.read())

file.txt contains "Hello Word" and this sentence is correctly printed when running python start.py

But after packaging with pyinstaller with the following spec file :

# -*- mode: python ; coding: utf-8 -*-
block_cipher = None
a = Analysis(['start.py'],
         pathex=['D:\\dev\\ec'],
         binaries=[],
         datas=[('resources','resources')],
         hiddenimports=[],
         hookspath=[],
         runtime_hooks=[],
         excludes=[],
         win_no_prefer_redirects=False,
         win_private_assemblies=False,
         cipher=block_cipher,
         noarchive=False)
pyz = PYZ(a.pure, a.zipped_data,
         cipher=block_cipher)
exe = EXE(pyz,
      a.scripts,
      [],
      exclude_binaries=True,
      name='start',
      debug=False,
      bootloader_ignore_signals=False,
      strip=False,
      upx=True,
      console=True )
coll = COLLECT(exe,
           a.binaries,
           a.zipfiles,
           a.datas,
           strip=False,
           upx=True,
           upx_exclude=[],
           name='start')

the resource file is copied in pyinstaller dist folder (as explained here Pyinstaller: How to include resources from package used by importlib_resources) but I when executing the produced exe file I have this error :

PS D:\dev\ec> .\dist\start\start.exe
Traceback (most recent call last):
 File "start.py", line 4, in <module>
 with importlib_resources.path(resources, 'file.txt') as p:
 File "contextlib.py", line 81, in __enter__
 File "importlib_resources\_common.py", line 87, in _tempfile
 File "tempfile.py", line 342, in mkstemp
 File "tempfile.py", line 258, in _mkstemp_inner
TypeError: must be str, not method
[8148] Failed to execute script start

Can anyone help ? tks


Solution

  • finally I get rid of importlib_resources and used pkg_resources instead and it worked like a charm :

    import pkg_resources
    with open(pkg_resources.resource_filename('resources', 'file.txt')) as file:
        print(file.read())