The provided code defines a Windows Service named `LionService` using...

August 25, 2025 at 09:10 AM

import os import psutil import servicemanager import socket import sys import win32event import win32service import win32serviceutil import win32timezone from datetime import datetime class LionService(win32serviceul.ServiceFramework): _svc_name_ = "LionService" _svc_display_name_ = "This is the Lion Service" # _svc_description_ = def __init__(self, args): win32serviceul.ServiceFramework.__init__(self, args) self.hWaitStop = win32event.CreateEvent(None, 0, 0, None) socket.setdefaultimeout(60) def SvcStop(self): self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) win32event.SetEvent(self.hWaitStop) def SvcDoRun(self): # write current date, time, CPU usage, memory usage, and running process IDs to a file current_datetime = datetime.now() current_date = current_datetime.date() current_time = current_datetime.time() cpu_usage = psutil.cpu_percent(interval=1) # compares system CPU times elapsed before and after interval memory_usage = psutil.virtual_memory() running_pids = psutil.pids() rc = None while rc != win32event.WAIT_OBJECT_0: if os.path.exists('C:\\temp\\LionService.log'): with open('C:\\temp\\LionService.log', 'a') as f: f.write('Lion service running...\n') f.write(f"Date: {str(current_date)}\n Time: {str(current_time)}\n CPU Usage: {int(cpu_usage)}\n Memory Usage: {memory_usage}\n Running PIDs: {running_pids}\n") f.write('---------------------------------------------------------------------------------------------------') rc = win32event.WaitForSingleObject(self.hWaitStop, 10000) else: with open('C:\\temp\\LionService.log', 'w') as f: f.write('Lion service running...\n') f.write(f"Date: {str(current_date)}\n Time: {str(current_time)}\n CPU Usage: {int(cpu_usage)}\n Memory Usage: {memory_usage}\n Running PIDs: {running_pids}\n") f.write('---------------------------------------------------------------------------------------------------') rc = win32event.WaitForSingleObject(self.hWaitStop, 10000) def main(): win32serviceutil.HandleCommandLine(LionService) if __name__ == '__main__': if len(sys.argv) == 1: servicemanager.Initialize() servicemanager.PrepareToHostSingle(LionService) servicemanager.StartServiceCtrlDispatcher() else: win32serviceutil.HandleCommandLine(LionService)

The provided code defines a Windows Service named LionService using Python's pywin32 library. Here's what the code does in detail:

Key Features and Behavior:

  1. Imports Required Modules: The code imports various modules required for Windows services (win32service, win32serviceutil, etc.) and system information handling (psutil, os).

  2. Defines a Custom Service Class (LionService):

    • The class LionService inherits from win32serviceutil.ServiceFramework, which is the base class for defining Windows services in Python.
  3. Service Name and Display Name:

    • _svc_name_ = "LionService": The internal service name.
    • _svc_display_name_ = "This is the Lion Service": The display name for the service as it will appear in the Windows Services Manager.
  4. Service Initialization (__init__):

    • Initializes the service using the win32serviceutil.ServiceFramework constructor.
    • Creates an event handle (self.hWaitStop) to handle stop signals.
    • Sets a default socket timeout of 60 seconds.
  5. Stop Service (SvcStop):

    • Reports to the system that the service is stopping (SERVICE_STOP_PENDING).
    • Signals the stop event by setting it using win32event.SetEvent(self.hWaitStop).
  6. Run Service Logic (SvcDoRun):

    • The SvcDoRun method implements the main logic of the service. It does the following in a loop:
      • Retrieves the current date and time.
      • Gathers system metrics:
        • CPU usage percentage using psutil.cpu_percent(interval=1).
        • Memory usage stats using psutil.virtual_memory().
        • List of active process IDs using psutil.pids().
      • Checks if a log file (C:\temp\LionService.log) exists:
        • If it exists, appends the service state, metrics, and process IDs to the file.
        • If it doesn't exist, creates the file and writes the same information.
      • Logs are written every 10 seconds (determined by the WaitForSingleObject() call's 10,000-millisecond timeout).
      • Continues running until the stop event self.hWaitStop is triggered.
  7. Main Entry Point:

    • The main() function determines how the service is run:
      • If the script is run without arguments (len(sys.argv) == 1), the service is started directly using servicemanager.
      • Otherwise, it uses win32serviceutil to handle command-line interactions, such as installing or starting the service.

Summary of What the Service Does:

  • This is a Windows service that periodically (every 10 seconds) logs the following system information to C:\temp\LionService.log (creating the file if necessary):
    • Current date and time.
    • Current CPU usage percentage.
    • Memory usage statistics.
    • List of running process IDs.
  • The service continues running until it is explicitly stopped by the system or user.

Prerequisites and Considerations:

  • The pywin32 library must be installed to run the code.
  • The directory C:\temp must exist; otherwise, the code will fail when trying to write the log file.
  • The service must be properly installed and registered using commands like python script.py install followed by python script.py start.
  • Logging to LionService.log can grow indefinitely unless managed, so additional measures (e.g., log rotation) should be implemented for production use.
Generate your own explanations
Download our vscode extension
Read other generated explanations

Built by @thebuilderjr
Sponsored by beam analytics
Read our terms and privacy policy
Forked from openai-quickstart-node