Python Flask as Windows Service

According to a Reddit post, Adding all the libraries to hiddenimports should fix your problem, I tried it myself and it did work!

So, create a file in your project's directory, named win32_service.spec with the following content

# -*- mode: python -*-

block_cipher = None


a = Analysis(['win32_service.py'],
             pathex=['C:\\Users\\Win7\\Desktop\\FaaS'],
             binaries=[],
             datas=[],
             hiddenimports=['win32timezone',
                            'altgraph',
                            'Click'
                            'Flask',
                            'future',
                            'itsdangerous',
                            'Jinja2',
                            'macholib',
                            'MarkupSafe',
                            'pefile',
                            'PyInstaller',
                            'pyodbc',
                            'pywin32',
                            'pywin32-ctypes',
                            'Werkzeug',],
             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='win32_service',
          debug=False,
          bootloader_ignore_signals=False,
          strip=False,
          upx=True,
          runtime_tmpdir=None,
          console=True )

Don't forget to change pathex variable

Then instead of pyinstaller --onefile --hidden-import win32timezone win32_service.py use the following command: pyinstaller --onefile win32_service.spec


I looked further into pyinstaller github repo and solved this issue.

It seems that pyinstaller has some conflicts with Windows 10, but this issue was the key to my problem. Althoug the module producing the error was not the same.

I managed to solve it by adding a SystemError exception at lib\site-packages\click\utils.py, line 260 in the echo function.

So I change this:

if message:
   file.write(message)

To this:

if message:
    try:
        file.write(message)
    except SystemError:
        pass

Rebuilt the exe using:

pyinstaller --onefile --hidden-import win32timezone win32_service.py

Installed the service, and then it started correctly.