我已经使用configparser来读取python中的配置文件。当脚本转换为Windows Service时,将显示错误消息“启动服务错误:服务未及时响应启动或控制请求”。
我增加了ServicesPipeTimeout
并启用了Allow service to interact with desktop
,但是并不能解决问题。
脚本是
import logging
import configparser
import mysql.connector
import socket
import win32event
import win32service
import servicemanager
import win32serviceutil
import sys
logging.basicConfig(
filename = "C:\\Users\\Administrator\\PythonService.txt",
level = logging.INFO,
format = '%(asctime)s - %(name)s - %(levelname)s - %(message)s',
datefmt='%m/%d/%Y %I:%M:%S %p'
)
def main():
configaration = configparser.ConfigParser()
configaration.read('default.ini')
host = configaration['mysql']['host']
username = configaration['mysql']['user']
password = configaration['mysql']['password']
database = configaration['mysql']['database']
config = {'user': username,'password': password,'host': host,'database': database}
logging.info(config)
class TestService(win32serviceutil.ServiceFramework):
_svc_name_ = "ClientService"
_svc_display_name_ = "Client Service"
def __init__(self, args):
win32serviceutil.ServiceFramework.__init__(self, args)
self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
socket.setdefaulttimeout(60)
self.stop_requested = False
def SvcStop(self):
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
win32event.SetEvent(self.hWaitStop)
logging.info('Stopping service ....')
self.stop_requested = True
def SvcDoRun(self):
logging.info("Started service")
servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,
servicemanager.PYS_SERVICE_STARTED,
(self._svc_name_, ''))
rc = None
while rc != win32event.WAIT_OBJECT_0:
rc = win32event.WaitForSingleObject(self.hWaitStop, 5000)
if rc == win32event.WAIT_OBJECT_0:
servicemanager.LogInfoMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,
servicemanager.PYS_SERVICE_STARTED,
(self._svc_name_, ''))
break
else:
main()
if __name__ == '__main__':
if len(sys.argv) == 1:
servicemanager.Initialize()
servicemanager.PrepareToHostSingle(TestService)
servicemanager.StartServiceCtrlDispatcher()
else:
win32serviceutil.HandleCommandLine(TestService)
当脚本开始与文件系统中的文件进行交互时,执行停止。