Pyinstaller - FileNotFoundError: 'hstspreload.bin' resource not found in 'hstspreload'

10 Aug 2020

When trying to create a Windows executable with PyInstaller, one may encounter this error because hstspreload has a binary data component.

The below sample illustrates how to fix this issue by including the binary data in the spec file. For a script called foo.py in the C:\User\myuser directory named foo.spec:

block_cipher = None
package_imports = [['hstspreload', ['hstspreload.bin']]]
datas = []
for package, files in package_imports:
    proot = os.path.dirname(importlib.import_module(package).__file__)
    datas.extend((os.path.join(proot, f), package) for f in files)

a = Analysis(['instanames.py'],
             pathex=['C:\\Users\\myuser'],
             binaries=[],
             datas=datas,
             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,
          a.binaries,
          a.zipfiles,
          a.datas,
          [],
          name='foo',
          debug=False,
          bootloader_ignore_signals=False,
          strip=False,
          upx=True,
          upx_exclude=[],
          runtime_tmpdir=None,
          console=True )

The specific important lines being

block_cipher = None
package_imports = [['hstspreload', ['hstspreload.bin']]]
datas = []
for package, files in package_imports:
    proot = os.path.dirname(importlib.import_module(package).__file__)
    datas.extend((os.path.join(proot, f), package) for f in files)

And then set the datas keyword argument to the datas variable in the Analysis call.

This block of code finds the path of the given binary file(s) for the given package.

Now call pyinstaller with the changed spec file: pyinstaller foo.spec