如何解决使用 pywin32 使用 Flask 构建 Windows 服务的问题
我正在开发 Python,并遵循了使用 Flask 和 Pywin32 构建 Windows 服务的指南here。
我的代码设置如下:
class AppServerSvc (win32serviceutil.ServiceFramework):
_svc_name_ = "my_services"
_svc_display_name_ = "My service"
logging.basicConfig(
filename = 'c:\\TMP\\{}.log'.format(_svc_name_),level = logging.DEBUG,format = '%(levelname)-7.7s @ %(asctime)s: %(message)s'
)
def __init__(self,args):
win32serviceutil.ServiceFramework.__init__(self,args)
self.hWaitStop = win32event.CreateEvent(None,None)
socket.setdefaulttimeout(60)
try:
self.log('START: Service start')
self.ReportServiceStatus(win32service.SERVICE_RUNNING)
self.start()
win32event.WaitForSingleObject(self.stop_event,win32event.INFINITE)
except Exception as e:
self.log('Exception: {}'.format(e))
self.SvcStop()
def SvcStop(self):
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
win32event.SetEvent(self.hWaitStop)
def SvcDoRun(self):
servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,servicemanager.PYS_SERVICE_STARTED,(self._svc_name_,''))
try:
self.log('START: Service start')
self.ReportServiceStatus(win32service.SERVICE_RUNNING)
self.start()
win32event.WaitForSingleObject(self.stop_event,win32event.INFINITE)
except Exception as e:
self.log('Exception: {}'.format(e))
self.SvcStop()
self.main()
def main(self):
app.run(host= '127.0.0.1',port= '5000')
pass
def log(self,msg):
servicemanager.LogInfoMsg(str(msg)) #system log
logging.info(str(msg)) #text log
@app.route('/',defaults={'path': ''})
@app.route('/<path:path>')
def send_html(path):
if path == '':
path = 'index.html'
return send_from_directory(os.path.join(root_dir(),'static-file'),path)
@app.route('/my_app',methods = ['POST'])
def my_application():
//my app
if __name__ == '__main__':
win32serviceutil.HandleCommandLine(AppServerSvc)
在调试中一切正常, 当我尝试启动服务时,日志文件出现:
INFO @ 2021-03-01 08:35:55,857: START: Service start
INFO @ 2021-03-01 08:35:55,857: Exception: 'AppServerSvc' object has no attribute 'start'
解决方法
所以,在对代码进行一些控制之后,我找到了解决方案:
def start(self):
self.runflag = True
while self.runflag:
win32api.Sleep((2*1000),True)
self.log('Service alive')
def stop(self):
self.runflag = False
self.log('Stop received')
有了这个功能,问题就解决了。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。