This Python code defines and runs a Windows service called...

August 25, 2025 at 09:58 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(win32serviceutil.ServiceFramework): _svc_name_ = "LionService" _svc_display_name_ = "This is the Lion Service" # _svc_description_ = def __init__(self, args): win32serviceutil.ServiceFramework.__init__(self, args) self.hWaitStop = win32event.CreateEvent(None, 0, 0, None) socket.setdefaulttimeout(60) def SvcStop(self): self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) win32event.SetEvent(self.hWaitStop) def SvcDoRun(self): rc = None while rc != win32event.WAIT_OBJECT_0: # 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() with open('C:\\temp\\LionService.log', 'a') as f: f.write('Lion service running...\n') f.write(f"Date: {str(current_date)}\nTime: {str(current_time)}\nCPU Usage: {int(cpu_usage)}\nMemory Usage: {memory_usage}\nRunning PIDs: {running_pids}\n") f.write('---------------------------------------------------------------------------------------------------\n') rc = win32event.WaitForSingleObject(self.hWaitStop, 10000) def main(): if len(sys.argv) == 1: servicemanager.Initialize() servicemanager.PrepareToHostSingle(LionService) servicemanager.StartServiceCtrlDispatcher() #-> when its running as a service else: win32serviceutil.HandleCommandLine(LionService) if __name__ == '__main__': main()

This Python code defines and runs a Windows service called "LionService" that logs system information periodically. Its functionality can be broken down as follows:

Overview:

  • Service Name & Description:
    • It creates a Windows Service named LionService with the display name "This is the Lion Service".
  • Main Purpose:
    • When running, the service periodically writes system information (date, time, CPU usage, memory usage, and running process IDs) to a log file located at C:\temp\LionService.log.

Code Behavior:

  1. Dependencies and Libraries:

    • The code imports several modules:
      • os, psutil: Used to gather system information like CPU usage, memory statistics, and process IDs.
      • win32service, win32serviceutil, win32event, win32timezone: These are used to implement and manage the Windows service.
      • socket: Sets default network timeout just in case networking operations are used indirectly.
      • datetime: Captures the current date and time for logging purposes.
      • servicemanager: Provides Windows service-related functionality.
  2. Windows Service Class Definition:

    • The class LionService inherits win32serviceutil.ServiceFramework, which allows it to act as a Windows service.
    • Important components of the class:
      • _svc_name_ and _svc_display_name_:
        • Sets the unique name and display name for the service.
      • __init__ method:
        • Initializes the service and creates an event (self.hWaitStop) that will signal the service to stop.
        • Configures a socket timeout.
      • SvcStop method:
        • Called when the service is stopped.
        • Updates the service's status to SERVICE_STOP_PENDING and sets the stop event.
      • SvcDoRun method:
        • The main logic of the service.
        • Continuously performs the following in a loop until the stop event (self.hWaitStop) is triggered:
          • Captures and logs:
            • The current date (current_date).
            • The current time (current_time).
            • CPU usage percentage.
            • Memory usage statistics (via psutil.virtual_memory()).
            • List of all currently running process IDs.
          • Writes this information to a log file (C:\temp\LionService.log).
          • Waits 10 seconds before repeating.
  3. Main Function:

    • If executed without command-line arguments (len(sys.argv) == 1), the service is initialized to run under the control of the Windows Service Manager.
    • If executed with command-line arguments, allows for service management (e.g., installation, removal) using win32serviceutil.HandleCommandLine.
  4. Execution:

    • When run as a Python script, the main() function is executed, either installing, managing, or starting the service.

What Happens When the Service Runs?

When the LionService is installed and started:

  • It begins an infinite loop until a stop signal is received.
  • During each iteration:
    • Captures:
      • Current date and time.
      • The system's CPU usage over 1 second.
      • Memory usage stats such as total, free, used memory, etc.
      • Process IDs of all currently running processes.
    • Logs this information to the file at C:\temp\LionService.log.
    • Waits 10 seconds (10000 ms) before repeating.

Notes:

  • Dependencies:
    • The script requires the pywin32 package for win32* modules and the psutil package to function properly.
  • File Path:
    • The log file is hard-coded to C:\temp\LionService.log. If C:\temp doesn't exist, the script will raise an error unless the directory is created manually.
  • Platform:
    • The script is designed for Windows only. It will not work on non-Windows systems because of the use of Windows-specific modules.
  • Permissions:
    • Requires administrative privileges to install the service or write to certain files (like the log file in C:\temp).

Summary:

In short, this code implements a Windows service (LionService) that logs system resource usage and running processes to a file at regular intervals. The service is designed to continuously run in the background until stopped.

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