已编辑
"...服务可以在电脑开机时自动启动,可以
暂停并重新启动,并且不显示任何用户界面。” ~Introduction to Windows Service Applications
Windows 服务需要实现才能使特定接口可用:
因此您需要通过 Python 访问 Windows API:
你可以看到example code,来自Python Programming On Win32,其中第18章服务(ch18_services文件夹)包含一个示例(SmallestService.py),展示了用Python编写的最小可能的服务:
# SmallestService.py
#
# A sample demonstrating the smallest possible service written in Python.
import win32serviceutil
import win32service
import win32event
class SmallestPythonService(win32serviceutil.ServiceFramework):
_svc_name_ = "SmallestPythonService"
_svc_display_name_ = "The smallest possible Python Service"
def __init__(self, args):
win32serviceutil.ServiceFramework.__init__(self, args)
# Create an event which we will use to wait on.
# The "service stop" request will set this event.
self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
def SvcStop(self):
# Before we do anything, tell the SCM we are starting the stop process.
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
# And set my event.
win32event.SetEvent(self.hWaitStop)
def SvcDoRun(self):
# We do nothing other than wait to be stopped!
win32event.WaitForSingleObject(self.hWaitStop, win32event.INFINITE)
if __name__=='__main__':
win32serviceutil.HandleCommandLine(SmallestPythonService)
您可能需要在此处为您的特定 python 环境下载适当的 pywin32 轮:
http://www.lfd.uci.edu/~gohlke/pythonlibs/#pywin32
还有install它(系统范围,来自管理员 cmd 提示符):
> cd \program files\python<ver>\scripts
> pip install \path\to\pywin32‑221‑cp<ver>‑cp<ver>m‑win_<arch>.whl
或安装它(每个用户,从常规 cmd 提示符):
> cd \program files\python<ver>\scripts
> pip install --user \path\to\pywin32‑221‑cp<ver>‑cp<ver>m‑win_<arch>.whl
一定要适当地替换<ver>和<arch>的出现。