Meet trouble when try to register streamlit program as windows services

When visit http://localhost:5555/ got this:

In service.msc can see service is running. using “netstat -aon | findstr 5555” found no process is running.

Anyone have tried similar solution?

My program like this:

import win32serviceutil
import win32service
import win32event
import sys
import subprocess
import servicemanager
import os

class StreamlitService(win32serviceutil.ServiceFramework):
    _svc_name_ = 'StreamlitService'
    _svc_display_name_ = 'StreamlitService'
    _svc_description_ = 'Streamlit Service running in Windows service'

    def __init__(self, args):
        win32serviceutil.ServiceFramework.__init__(self, args)
        self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
        self.process = None

    def SvcStop(self):
        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
        win32event.SetEvent(self.hWaitStop)
        if self.process:
            self.process.terminate()
        self.ReportServiceStatus(win32service.SERVICE_STOPPED)

    def SvcDoRun(self):
        self.ReportServiceStatus(win32service.SERVICE_RUNNING)
        log_file_path = os.path.join('D:\\Fastapi', 'streamlit_service.log')
        with open(log_file_path, 'a') as log_file:
            self.process = subprocess.Popen(
                ['D:\\Python311\\python.exe', '-m', 'streamlit', 'run', 'streamlit_heatmap.py', '--server.port', '5555'],
                cwd='D:\\heatmap',
                stdout=log_file,
                stderr=log_file
            )
        win32event.WaitForSingleObject(self.hWaitStop, win32event.INFINITE)

if __name__ == '__main__':
    if len(sys.argv) == 1:
        servicemanager.Initialize()
        servicemanager.PrepareToHostSingle(StreamlitService)
        servicemanager.StartServiceCtrlDispatcher()
    else:
        win32serviceutil.HandleCommandLine(StreamlitService)

this function is using pywin32 module, any friend have try this?

Hello BeyondMyself !

1/Make sure that you don’t have the Microsoft distribution of python (In this distro python.exe is a symbolic link which is activated after the loading of a user profile, so System account can’t access it)

2/Use System account to run this command

3/ Write the full path to your .py file in your command.

4/ (Perhaps create empty log files manually before running your script)

Then cross the fingers :crossed_fingers: