未登录时运行Python Windows服务

时间:2020-02-20 14:54:19

标签: python windows-services

我的Flask服务停止了,因为我在Windows中注销了。重新加载我的用户名和密码后,它又可以工作了。即使重新启动或注销,如何使它始终打开?

import time
import random
import os
from pathlib import Path
from SMWinservice import SMWinservice
import sys
import win32serviceutil
import win32service
import win32event
import servicemanager

class FlaskService(SMWinservice):
    _svc_name_ = "FlaskServiceSmartFactory01"
    _svc_display_name_ = "Flask Service Smart Factory01"
    _svc_description_ = "Python service framework Smart Factory01"

    def start(self):
        self.isrunning = True

    def stop(self):
        self.isrunning = False

    def main(self):
        os.chdir(os.environ['SMARTFACTORYPATH'])
        os.system('C02_RestAPI.py')

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

1 个答案:

答案 0 :(得分:0)

Windows服务可以在Windows运行时在后台运行,但是如果Windows关闭则不能运行。 您可以根据需要将服务设置为在Windows启动时加载。