app_service.py

#!/usr/bin/evn python3

import os
import subprocess
import sys
import time

import servicemanager

from src.windows.service_adapter import ServiceAdapter


class AppService(ServiceAdapter):
    _svc_name_ = "AppService"
    _svc_display_name_ = 'App_Service'
    _svc_description_ = 'Windows service for App'

    app_path = None

    def running(self):
        # 这里有个坑:python编写的windows服务不能执行系统命令,报错 winerror 6(ERROR_INVALID_HANDLE)
        # 解决方案: stdout, stderr 用文件句柄接收
        out_file = "{}\\out.log".format(self.app_path)
        self.log(out_file)
        err_file = "{}\\error.log".format(self.app_path)
        self.log(err_file)
        # cmd = 'netstat -ano'
        # cmd = r"D:\_code\python_notes\src\windows\run.bat"
        cmd = r"D:\Software\Python\Python37\python.exe D:\_code\python_notes\src\windows\app.py"
        self.log(cmd)
        try:
            subprocess.Popen(cmd,
                             stdout=open(out_file, 'w'),
                             stderr=open(err_file, 'w'),
                             stdin=subprocess.PIPE,
                             cwd=self.app_path,
                             universal_newlines=True).communicate()
            self.log("process end.")
        except Exception as ex:
            self.log("Exception")
            self.log(ex)
        self.log("failed to run cmd, enter sleep 5")

        pass

    def stop(self):
        pass


if __name__ == '__main__':
    program_path = os.path.abspath(os.path.dirname(sys.argv[0]))
    AppService.log(program_path)
    AppService.app_path = program_path

    # import inspect
    # this_file = inspect.getfile(inspect.currentframe())
    # dir_path = os.path.abspath(os.path.dirname(this_file))
    # sys.stdout = sys.stderr = open(os.path.join(dir_path, "service.log"), 'w')

    try:
        AppService.service_main()
    except Exception as exp:
        servicemanager.LogMsg(
            servicemanager.EVENTLOG_INFORMATION_TYPE,
            servicemanager.PYS_SERVICE_STARTED,
            ("AppService", exp)
        )

    pass

猜你喜欢

转载自www.cnblogs.com/munan-zhou/p/12407578.html
py