我编写了一个 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 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_service.py install
安装服务并得到正确的输出 Installing service test_service Service installed
.当我打开服务选项卡时,我可以看到那里列出了我的服务。当我单击启动服务时,出现以下错误:任何人都可以告诉我代码中有什么问题,因为它没有启动服务。请帮忙。谢谢
更新:
我在
cmd
中以 Debug模式运行服务看起来它工作正常。但是从服务选项卡,它不工作并显示上述错误。> 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.
不知道为什么它没有运行,在 Debug模式下它运行良好。请帮忙。
最佳答案
任何遇到此问题的人,只需复制 pywintypes36.dll
来自 Python36\Lib\site-packages\pywin32_system32
至 Python36\Lib\site-packages\win32
有用的命令:
python app.py install
python app.py remove
python app.py start
python app.py update
关于python - 如何使用 Python 创建 Windows 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63754895/