带Flask的Windows服务仅在调试模式下运行。普通模式似乎崩溃了

时间:2018-10-08 08:38:57

标签: python flask service window

我想将python脚本(使用Flask)安装为Windows服务。 我使用下面的简单代码(在myservice.py中):

import win32serviceutil
import win32service
import win32event
import win32evtlogutil
import servicemanager
import socket
import time
import logging
from multiprocessing import Process
import traceback
import logging
from datetime import datetime,tzinfo,timedelta
from flask import Flask
import os
import sys
sys.path.append(os.path.dirname(__name__))

app = Flask(__name__)

class Zone(tzinfo):
    def __init__(self,offset,isdst,name):
        self.offset = offset
        self.isdst = isdst
        self.name = name
    def utcoffset(self, dt):
        return timedelta(hours=self.offset) + self.dst(dt)
    def dst(self, dt):
            return timedelta(hours=1) if self.isdst else timedelta(0)
    def tzname(self,dt):
         return self.name

@app.route('/')
def hello_world():
    logging.info('[GET] hello_world ...')
    KST = Zone(+9,False,'KST')
    now_time = datetime.now(KST).strftime('%Y-%m-%d %H:%M:%S %Z')
    return 'Hello, World! ' + now_time

logging.basicConfig(
    filename = 'c:\\Temp\\hello-service.log',
    level = logging.DEBUG, 
    format = '[helloflask] %(levelname)-7.7s %(message)s'
)

class HelloFlaskSvc (win32serviceutil.ServiceFramework):
    _svc_name_ = "AIHello"
    _svc_display_name_ = "AI Hello"

    def __init__(self, *args):
        win32serviceutil.ServiceFramework.__init__(self, *args)
        self.hWaitStop = win32event.CreateEvent(None,0,0,None)
        #socket.setdefaulttimeout(5)
        self.stop_requested = False

    def SvcStop(self):
        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
        #self.process.terminate()
        win32event.SetEvent(self.hWaitStop)
        self.ReportServiceStatus(win32service.SERVICE_STOPPED)
        logging.info('Stopped service ...')
        self.stop_requested = True

    def SvcDoRun(self):
        servicemanager.LogMsg(
            servicemanager.EVENTLOG_INFORMATION_TYPE,
            servicemanager.PYS_SERVICE_STARTED,
            (self._svc_name_,'')
        )
        logging.info('Before main')

        app.run()

if __name__ == '__main__':
    if len(sys.argv) == 1:
        servicemanager.Initialize()
        servicemanager.PrepareToHostSingle(HelloFlaskSvc)
        servicemanager.StartServiceCtrlDispatcher()
    else:
        win32serviceutil.HandleCommandLine(HelloFlaskSvc)

我可以通过以下命令安装此脚本: python.exe myservice.py -install ,它显示在“服务”列表中,但是当我尝试启动它时,说“ AI Hello服务”在本地计算机上启动,然后停止。如果其他服务或程序未使用某些服务,则该服务会自动停止”。

我检查了Event Viewer日志,它显示“”实例的SvcRun()方法失败 。错误获取回溯-traceback.print_exception()失败%2:%3“

我在Windows 10 64bit上使用Python 3.6.4,Flask 1.0.2,pywin32-224。

此脚本可以通过以下命令在DEBUG模式下工作: python myservice.py debug

希望有人可以帮助我

已更新:我切换到了Python 2.7。它显示相同的错误。但是在事件查看器日志中:

The instance's SvcRun() method failed 
Traceback (most recent call last):
  File "C:\Python27\lib\site-packages\win32\lib\win32serviceutil.py", line 839, in SvcRun
    self.SvcDoRun()
  File "D:\MusFatAI\FlaskServiceWin32-master\FlaskServiceWin32-master\win32_service.py", line 73, in SvcDoRun
    app.run(debug=False)
  File "C:\Python27\lib\site-packages\flask\app.py", line 938, in run
    cli.show_server_banner(self.env, self.debug, self.name, False)
  File "C:\Python27\lib\site-packages\flask\cli.py", line 629, in show_server_banner
    click.echo(message)
  File "C:\Python27\lib\site-packages\click\utils.py", line 261, in echo
    file.flush()
IOError: (9, 'Bad file descriptor') 

1 个答案:

答案 0 :(得分:0)

我遇到了类似的问题,并通过将以下行放在脚本顶部来解决了该问题:

sys.stdout = sys.stderr = open(os.devnull, 'w')