analitics

Pages

Showing posts with label win32service. Show all posts
Showing posts with label win32service. Show all posts

Monday, March 10, 2025

Python 3.13.0rc1 : Python script as window 10 service.

The main reason I tested this python issues comes from this:
I have a strange usage of msedgewebview2.exe on my window 10.
The right way was to install but I cannot do that because is not my laptop.
I created a python script to make logs and kill this process:
import win32serviceutil
import servicemanager
import win32event
import win32service
import time
import logging
import psutil

class MyService(win32serviceutil.ServiceFramework):
    _svc_name_ = 'catafestService'
    _svc_display_name_ = 'My catafest Service tool'

    def __init__(self, args):
        win32serviceutil.ServiceFramework.__init__(self, args)
        self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
        self.stop_requested = False
        logging.basicConfig(filename='D:\\PythonProjects\\catafest_services\\logfile.log', level=logging.DEBUG,
                            format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')

    def SvcStop(self):
        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
        win32event.SetEvent(self.hWaitStop)
        self.stop_requested = True
        logging.info('Service stop requested')

    def SvcDoRun(self):
        servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,
                              servicemanager.PYS_SERVICE_STARTED,
                              (self._svc_name_, ''))
        logging.info('Service started')
        self.main()

    def main(self):
        while not self.stop_requested:
            try:
                # Check and terminate 'msedgewebview2.exe' process
                for proc in psutil.process_iter(['pid', 'name']):
                    if proc.info['name'] == 'msedgewebview2.exe':
                        proc.kill()
                        logging.info(f'Terminated process: {proc.info["name"]} (PID: {proc.info["pid"]})')
                logging.info('Service running...')
                time.sleep(10)  # Runs every 10 seconds
            except Exception as e:
                logging.error(f'Error occurred: {e}', exc_info=True)
                servicemanager.LogMsg(servicemanager.EVENTLOG_ERROR_TYPE,
                                      servicemanager.PYS_SERVICE_STOPPED,
                                      (self._svc_name_, f'Error occurred: {e}'))
                break
        logging.info('Service stopped')

if __name__ == '__main__':
    win32serviceutil.HandleCommandLine(MyService)
You need to install pyinstaller to make a exe file:
pip install pyinstaller
...
Successfully installed altgraph-0.17.4 pefile-2023.2.7 pyinstaller-6.12.0 pyinstaller-hooks-contrib-2025.1
pywin32-ctypes-0.2.3
The next step install the pywin32 python package:
pip install pywin32
... try to make executable:
pyinstaller --onefile catafest_services.py
... use the start:
catafest_services.exe start
Traceback (most recent call last):
  ...
  File "win32serviceutil.py", line 706, in HandleCommandLine
  File "win32serviceutil.py", line 624, in GetServiceClassString
ModuleNotFoundError: No module named 'win32timezone'
[PYI-6880:ERROR] Failed to execute script 'catafest_services' due to unhandled exception!
... this error comes from interaction on running with windows services:
try to fix with this:
pyinstaller --name=catafest_services --onefile catafest_services.py
Open the generated spec file catafest_services.spec and add the win32timezone module to the hidden imports. See:
# -*- mode: python ; coding: utf-8 -*-
block_cipher = None

a = Analysis(['catafest_services.py'],
             pathex=['D:\\PythonProjects\\catafest_services'],
             binaries=[],
             datas=[],
             hiddenimports=['win32timezone'],
             hookspath=[],
             runtime_hooks=[],
             excludes=[],
             win_no_prefer_redirects=False,
             win_private_assemblies=False,
             cipher=block_cipher,
             noarchive=False)
             
# The rest of the file remains unchanged
Rebuild the executable using the modified spec file:
pyinstaller catafest_services.spec
709 INFO: PyInstaller: 6.12.0, contrib hooks: 2025.1
711 INFO: Python: 3.13.0rc1
791 INFO: Platform: Windows-10-10.0.19045-SP0
791 INFO: Python environment: C:\Python313
...
Try again with start:
catafest_services.exe start
I got this output:
catafest_services.exe start
Starting service catafestService 
Error starting service: Access is denied.
Open the command prompt as administrator and try again:
catafest_services.exe start
Starting service catafestService
Error starting service: The service did not respond to the start or control request in a timely fashion.
Same interaction because try to kill a process and more ...
This not work, but is another good way to use it by using the debug:
catafest_services.exe debug
Debugging service catafestService - press Ctrl+C to stop.
I n f o   0 x 4 0 0 0 1 0 0 2   -   T h e   c a t a f e s t S e r v i c e   s   r v i c e   h a s   s t a r t e d .
 Stopping debug service.
Under debug all works well, some msedgewebview2 processes are gone.
I stop this run and I try to work on development ...
Next step: If all works then you can use install:
catafest_services.exe install
Installing service catafestService
Service installed
You can do more. Make sure the account running the service has the necessary permissions. You can specify a user account during service installation:
catafest_services.exe install --username your_domain\your_username --password your_password
You can use this command to see these info:
set user
Last step: You can open the Services Manager by typing services.msc in the Windows Run dialog. Use press Win + R keys to open the Run dialog.
Manage the service as any services. You can use even on command prompt:
catafest_services.exe
Usage: 'catafest_services.exe [options] install|update|remove|start [...]|stop|restart [...]|debug [...]'t_services>cd dist
Options for 'install' and 'update' commands only:
 --username domain\username : The Username the service is to run under
 --password password : The password for the username
 --startup [manual|auto|disabled|delayed] : How the service starts, default = manual
 --interactive : Allow the service to interact with the desktop.
 --perfmonini file: .ini file to use for registering performance monitor data
 --perfmondll file: .dll file to use when querying the service for
   performance data, default = perfmondata.dll
Options for 'start' and 'stop' commands only:
 --wait seconds: Wait for the service to actually start or stop.
                 If you specify --wait with the 'stop' option, the service
                 and all dependent services will be stopped, each waiting
                 the specified period.