Pyinstaller: How to include resources from package used by importlib_resources

2.6k views Asked by At

I have following project structure:

package1/
  __init__.py
  some.py
  package2
    __init__.py
    some.py
    static_data/
      __init__.py
      file1.txt
      file2.txt
      ...
my_script.py

my_script.py contains imports from all over the structure. And python code wotks fine except of importlib_resources usage.

I access files with importlib_resources (Python 3.6) like so: importlib_resources.open_text(static_data, 'file1.txt').readlines()

Building executable with: pyinstaller my_script.py -F --noconsole --noupx

In result executable I get following error:

File "lib\site-packages\importlib_resources\_py3.py", line 62, in open_text
File "lib\site-packages\importlib_resources\_py3.py", line 52, in open_binary
FileNotFoundError: 'file1.txt' resource not found in 'package1.package2.static_data'

What is the correct way to include resources used with importlib_resources?

2

There are 2 answers

1
hexbioc On

Non-binary files are not added to the generated binary by PyInstaller by default. You can manually add them using the --add-data option, as explained here.

Assuming your running windows and the resource files that you are accessing are all within the package1 top-level package, you can try something like this:

pyinstaller my_script.py -F --noconsole --noupx --add-data "package1;package1"
0
Zack Dai On

in the script needs data

import platform
if platform.sys.version.split()[0]>='3.7':
    import importlib.resources as importlib_resources
else:
    import importlib_resources

settings = json.loads(importlib_resources.read_text('packagename','data.json'))

in the setup.py

install_requires=[
        'importlib_resources ; python_version<"3.7"'
      ],