python开发windows本地服务

2021/12/3 7:10:26

本文主要是介绍python开发windows本地服务,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

一、安装 pip install win32
import win32serviceutil
import win32service
import win32event
import win32timezone

class PythonService(win32serviceutil.ServiceFramework):
    _svc_name_ = "DectFacePythonService"                    #服务名
    _svc_display_name_ = "人脸识别Face_Recognition"                 #job在windows services上显示的名字
    _svc_description_ = "人脸识别Face_Recognition"        #job的描述

    def __init__(self, args):
        win32serviceutil.ServiceFramework.__init__(self, args)
        self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
        # self.file_path = "C:/Users/wqy/Desktop/companyfaceimage"
        # f = open(os.path.join(os.path.abspath('.'))+'/config.js')
        # j = json.load(f)
        # self.file_path =j["config"][0]["file_path"]
    def SvcDoRun(self):
        # 启动方法
        event_handler = MyHandler()
        observer = Observer()
        observer.schedule(event_handler, event_handler.file_path, recursive=True)
        observer.start()
        observer.join()
        win32event.WaitForSingleObject(self.hWaitStop, win32event.INFINITE)

    def SvcStop(self):
        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
        win32event.SetEvent(self.hWaitStop)


if __name__ == '__main__':
    if len(sys.argv) == 1:
        try:
            evtsrc_dll = os.path.abspath(servicemanager.__file__)
            servicemanager.PrepareToHostSingle(PythonService)
            servicemanager.Initialize('PythonService', evtsrc_dll)
            servicemanager.StartServiceCtrlDispatcher()
        except win32service.error as details:
            if details == winerror.ERROR_FAILED_SERVICE_CONTROLLER_CONNECT:
                win32serviceutil.usage()
    else:
        win32serviceutil.HandleCommandLine(PythonService)

 

二、生成的安装文件可以使用一下命令来执行控制服务:

DectFacePythonServer.exe install
DectFacePythonServer.exe start
DectFacePythonServer.exe stop
DectFacePythonServer.exe remove。

或者

sc  create DectFacePythonServer(运行的服务程序) binPath= E:\python\pydev\src\dist\ProductCollectWin32ServiceSetup.exe 

注意上面“=”后面是带空格的

sc start DectFacePythonServer

sc delete DectFacePythonServer

详情请运行 sc --help。



这篇关于python开发windows本地服务的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程