Recipe 14.3 · Python
Running as a Windows Service
The Python listings are conversions of the book's C# code to Python 3.12. Each file's header says what it needs to run. The explanations were written for the C# version, so some names in the text refer to .NET.
Problem
The job must run on a Windows server, start at boot, run under a low-privilege account and restart
if it fails. The old way meant a ServiceBase subclass, an installer class and InstallUtil.exe,
and a service that could not be run from the command line for debugging.
The way it's often written
Anti-pattern: shown so you can recognize it. Don't copy this one.
Requirements: Python 3.12+. Install: pip install pywin32 · Needs at run time: Windows (admin rights to install the service). The module loads without them; calling the code does not work without them.
"""Separate console and service code paths in main
Source: ImproveCode, Chapter 14, Recipe 14.3 "Running as a Windows Service"
Section: The way it's often written
Book page: 309 -- original C# listing
Converted from C# to Python.
ANTI-PATTERN: kept deliberately faithful to the C# 'not to copy' example; do not use.
Environment.UserInteractive -> sys.stdin.isatty(); ServiceBase.Run -> pywin32
servicemanager dispatcher; Console.ReadLine -> input().
"""
from __future__ import annotations
import sys
import servicemanager
import win32serviceutil
class SyncService(win32serviceutil.ServiceFramework):
_svc_name_ = "SyncService"
_svc_display_name_ = "Sync Service"
def SvcDoRun(self) -> None:
self.on_start(sys.argv)
def SvcStop(self) -> None:
self.on_stop()
def on_start(self, args: list[str]) -> None: ...
def on_stop(self) -> None: ...
# hand-written test hooks
def debug_start(self, args: list[str]) -> None:
self.on_start(args)
def debug_stop(self) -> None:
self.on_stop()
# Not to copy: separate code paths for service and console
def main(args: list[str]) -> None:
if sys.stdin.isatty():
service = SyncService(args)
service.debug_start(args) # hand-written test hook
input()
service.debug_stop()
else:
servicemanager.Initialize()
servicemanager.PrepareToHostSingle(SyncService)
servicemanager.StartServiceCtrlDispatcher()
if __name__ == "__main__":
main(sys.argv)
The improved recipe
Reference Microsoft.Extensions.Hosting.WindowsServices and call AddWindowsService. The same
executable runs as a console app when you start it from a terminal or Visual Studio and as a
Windows Service when the Service Control Manager starts it.
Configuration for the event log in appsettings.json, so only warnings and errors go there:
{
"Logging": {
"LogLevel": { "Default": "Information" },
"EventLog": {
"LogLevel": { "Default": "Warning" }
}
}
}
Publish and install from an elevated PowerShell prompt:
dotnet publish -c Release -r win-x64 --self-contained false `
-o C:\Services\InvoiceSync
New-EventLog -LogName Application -Source InvoiceSync
New-Service -Name InvoiceSync `
-DisplayName "ImproveCode Invoice Sync" `
-BinaryPathName "C:\Services\InvoiceSync\InvoiceSync.exe" `
-StartupType Automatic
sc.exe config InvoiceSync obj= "NT SERVICE\InvoiceSync"
sc.exe failure InvoiceSync reset= 86400 `
actions= restart/60000/restart/60000/none/0
sc.exe failureflag InvoiceSync 1
Start-Service InvoiceSync
Requirements: Python 3.12+. Install: pip install pywin32 · Needs at run time: Windows (admin rights to install the service). The module loads without them; calling the code does not work without them.
"""One program that runs as a console app or as a Windows service
Source: ImproveCode, Chapter 14, Recipe 14.3 "Running as a Windows Service"
Section: The improved recipe
Book page: 309-310 -- original C# listing
Converted from C# to Python.
Host.CreateApplicationBuilder + AddWindowsService -> the asyncio Host stand-in from the
14.1 module plus a pywin32 ServiceFramework shim: when the service control manager did
not start the process (error 1063), the same host simply runs in the console.
"""
from __future__ import annotations
import asyncio
import sys
from datetime import timedelta
import pywintypes
import servicemanager
import win32service
import win32serviceutil
from p302_r14_1_timed_job_background_service import BackgroundService, Host
from p303_r14_1_add_timed_job_registration import add_timed_job
from p303_r14_1_invoice_sync_job import InvoiceSyncJob
SERVICE_NAME = "InvoiceSync"
ERROR_FAILED_SERVICE_CONTROLLER_CONNECT = 1063
def build_host() -> Host:
services: list[BackgroundService] = []
add_timed_job(services, InvoiceSyncJob, timedelta(minutes=5))
return Host(services)
class InvoiceSyncWindowsService(win32serviceutil.ServiceFramework):
_svc_name_ = SERVICE_NAME
_svc_display_name_ = SERVICE_NAME
def __init__(self, args: list[str]) -> None:
super().__init__(args)
self._loop: asyncio.AbstractEventLoop | None = None
self._host: Host | None = None
def SvcDoRun(self) -> None:
asyncio.run(self._run())
async def _run(self) -> None:
self._loop = asyncio.get_running_loop()
self._host = build_host()
await self._host.run()
def SvcStop(self) -> None:
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
if self._loop is not None and self._host is not None:
self._loop.call_soon_threadsafe(self._host.request_stop)
def main() -> None:
if len(sys.argv) > 1:
# install / remove / start / stop
win32serviceutil.HandleCommandLine(InvoiceSyncWindowsService)
return
try:
servicemanager.Initialize()
servicemanager.PrepareToHostSingle(InvoiceSyncWindowsService)
servicemanager.StartServiceCtrlDispatcher()
except pywintypes.error as ex:
if ex.winerror != ERROR_FAILED_SERVICE_CONTROLLER_CONNECT:
raise
asyncio.run(build_host().run()) # not a service: run in the console
if __name__ == "__main__":
main()
How it works
AddWindowsService checks at start-up whether the process was launched by the Service Control
Manager. If it was, it replaces the default console lifetime with a Windows Service lifetime that
reports start and stop to the SCM and turns a stop request into the same stoppingToken
cancellation that Ctrl+C triggers in a console. If it was not, it does nothing. There is one code
path, and you debug the service by pressing F5.
It also fixes the classic content-root problem. Services start with C:\Windows\System32 as the
current directory, so appsettings.json was not found and relative paths wrote into the system
folder. Under the Windows Service lifetime the content root is set to the folder that holds the
executable. It also adds the Windows event log as a logging provider. The event source defaults to
the application name, which for a project called InvoiceSync is InvoiceSync.
The event source must exist before a low-privilege account can write to it, which is why the
install script creates it with New-EventLog while you are elevated.
NT SERVICE\InvoiceSync is a virtual account. Windows manages its password, it has minimal rights
on the local machine, and you can grant it access to a folder or a SQL Server login by that name.
It is a much better default than LocalSystem or a shared domain account whose password is in a
spreadsheet.
The sc.exe failure line sets recovery actions: restart after 60 seconds on the first and second
failure, and do nothing after that, with the counter reset daily. failureflag 1 applies those
actions when the service stops with an error, not only when the process crashes.
Variations and pitfalls
- Fatal errors and recovery. The timed service in Recipe 14.1 logs and continues, which is
right for one bad run. For a failure the service cannot recover from, such as a missing
database, Microsoft's guidance for workers is to log it and end the process with
Environment.Exit(1). The non-zero exit code is what triggers the recovery actions. - Self-contained or framework-dependent.
--self-contained falseneeds the .NET runtime on the server. A self-contained publish carries its own runtime, which you then patch yourself. - Linux. The same program runs under systemd with the
Microsoft.Extensions.Hosting.Systemdpackage andbuilder.Services.AddSystemd(). Both calls can sit side by side, and each does nothing on the other platform.