如何使用Python创建windows服务
我已经编写了一个python脚本,它将作为windows服务安装在中。代码如下:如何使用Python创建windows服务,python,windows-services,pywin32,Python,Windows Services,Pywin32,我已经编写了一个python脚本,它将作为windows服务安装在中。代码如下: import datetime import logging from logging.handlers import RotatingFileHandler import os import time from random import randint import win32serviceutil import win32service import win32event import servicemana
import datetime
import logging
from logging.handlers import RotatingFileHandler
import os
import time
from random import randint
import win32serviceutil
import win32service
import win32event
import servicemanager
import socket
def setup_logger(logger_name, log_file, level=logging.ERROR):
log_formatter = logging.Formatter('%(asctime)s %(message)s')
my_handler = RotatingFileHandler(log_file, maxBytes=100 * 1024 * 1024, backupCount=5)
my_handler.setFormatter(log_formatter)
my_handler.setLevel(level)
l = logging.getLogger(logger_name)
l.handlers[:] = []
l.addHandler(my_handler)
curr_path = os.getcwd()
log_file = "F:\\Projects\\TestService\\logs\\application.log"
setup_logger('debug', log_file)
log = logging.getLogger('debug')
class AppServerSvc(win32serviceutil.ServiceFramework):
_svc_name_ = "test_service"
_svc_display_name_ = "Test Service"
def __init__(self, args):
win32serviceutil.ServiceFramework.__init__(self, args)
self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
socket.setdefaulttimeout(60)
self.isrunning = False
def SvcStop(self):
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
win32event.SetEvent(self.hWaitStop)
self.isrunning = False
def SvcDoRun(self):
servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,
servicemanager.PYS_SERVICE_STARTED,
(self._svc_name_, ''))
self.isrunning = True
self.main()
def main(self):
while self.isrunning:
log.error("Running {}".format(randint(00, 99)))
time.sleep(10)
if __name__ == '__main__':
win32serviceutil.HandleCommandLine(AppServerSvc)
我已经运行了命令python test\u service.py install
来安装服务,并获得了正确的输出Installing service test\u service installed
。当我打开“服务”选项卡时,我可以看到我的服务列在那里。当我单击“启动服务”时,我发现以下错误:
谁能告诉我代码中有什么错误导致它不能启动服务。请帮忙。谢谢
更新:
我在cmd
的调试模式下运行了该服务,看起来它工作正常。但从“服务”选项卡上看,它不起作用,并显示上述错误
> python test_service.py debug
Debugging service test_service - press Ctrl+C to stop.
Info 0x40001002 - The test_service service has started.
启动服务时,会出现相同的错误:
> python test_service.py start
Starting service test_service
Error starting service: The service did not respond to the start or control request in a timely fashion.
不确定为什么它没有运行,并且在调试模式下运行良好。请帮助。任何面临此问题的人,只需复制
pywintypes36.dll
从Python36\Lib\site packages\pywin32\u system32
到Python36\Lib\site packages\win32
有用的命令:
python app.py安装
python app.py remove
python app.py Start
python app.py更新
嗨,你看到了吗?@CarloZanocco是的,我看到了,我所有的代码都是用这个答案写的。但不管怎样,我已经找到了解决方案嗨,你能分享一下解决方案吗,我也面临着类似的问题吗?@Sripalavi我已经回答了