【问题标题】:Problem building Windows service with Flask with pywin32使用 pywin32 使用 Flask 构建 Windows 服务时出现问题
【发布时间】:2021-03-01 08:03:05
【问题描述】:

我正在开发 Python,并遵循here 使用 Flask 和 Pywin32 构建 Windows 服务的指南。

我的代码设置如下:

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,0,0,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'

【问题讨论】:

    标签: python windows pywin32


    【解决方案1】:

    所以,在对代码进行一些控制后,我找到了解决方案:

     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')
    

    有了这个功能,问题就解决了。

    【讨论】:

      猜你喜欢
      • 2011-06-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-26
      • 2022-08-03
      • 1970-01-01
      • 1970-01-01
      • 2022-09-25
      • 2020-09-02
      相关资源
      最近更新 更多