python 脚本或者flask 注册成为windows服务

分享下脚本注册成为win服务

这个借鉴了其他大佬得 具体是谁忘记了有机会推荐 今天也是找了之前得改出来得

首先安装三个模块 最后一个是定时任务如果不需要可以不装

pip install psutil
pip install pywin32
pip install apscheduler
下面贴代码
import os
import sys
import random
import socket

import time

import psutil
import servicemanager
import win32con
import win32event
import win32process
import win32security
import win32service
import win32serviceutil
import win32timezone
from apscheduler.schedulers.background import BackgroundScheduler

sys.stdout = sys.stderr = open(os.devnull,'w')
class SpiderService(win32serviceutil.ServiceFramework):

    # 注册服务名
    _svc_name_ = 'PS'
    # 服务在windows系统中显示的名称
    _svc_display_name_ = 'Python Service'
    # 服务描述
    _svc_description_ = 'Python Service Description'

    @classmethod
    def parse_command_line(cls):
        '''
        ClassMethod 解析命令行
        '''
        win32serviceutil.HandleCommandLine(cls)

    def __init__(self, args):
        '''
        winservice的构造函数
        '''
        self.scheduler = BackgroundScheduler()
        win32serviceutil.ServiceFramework.__init__(self, args)
        self.stop_event = win32event.CreateEvent(None, 0, 0, None)
        socket.setdefaulttimeout(60)


    def SvcStop(self):
        '''
        当服务被要求停止时调用
        '''
        self.stop()
        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
        win32event.SetEvent(self.stop_event)
        self.ReportServiceStatus(win32service.SERVICE_STOPPED)
        self.run = False

    def SvcDoRun(self):
        '''
        当服务被要求启动时调用
        '''
        self.start()
        servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,
                              servicemanager.PYS_SERVICE_STARTED,
                              (self._svc_name_, ''))

        try:
            username = 'admin'
            password = 'admin'
            domain = ''
            token = win32security.LogonUser(
                username,
                domain,
                password,
                win32con.LOGON32_LOGON_SERVICE,
                win32con.LOGON32_PROVIDER_DEFAULT
            )
            win32security.ImpersonateLoggedOnUser(token)

            cmd = '<a command line programe>'
            cwd = '<a work dir>'
            env = os.environ
            priority = win32con.NORMAL_PRIORITY_CLASS
            startup = win32process.STARTUPINFO()

            (hProcess, hThread, dwProcessId, dwThreadId) = \
                win32process.CreateProcessAsUser(token, None, cmd, None, None, True, priority, env, cwd, startup)

            process = psutil.Process(dwProcessId)
            return_code = process.wait()
            print('return code: %s' % str(return_code))

        except win32security.error as e:
            print(e)



        self.main()

        win32event.WaitForSingleObject(self.stop_event, win32event.INFINITE)
        #这个如果你是后台启动得flask 后台服务要加上
        while True:
            time.sleep(10)

    def __schedule(self):
        #添加定时任务
        self.scheduler.add_job(
            self.ceshi,
            'interval',
            seconds=10
        )
    #定时任务
    def ceshi(self):
        while self.isrunning:
            random.seed()
            x = random.randint(1, 1000000)
            Path(f'c:\\{x}.txt').touch()
            time.sleep(5)


    def start(self):
        self.isrunning = True

    def stop(self):
        self.isrunning = False

    def main(self):
        self.__schedule()
        self.scheduler.start()

if __name__ == '__main__':
    if len(sys.argv) == 1:
        try:
            event_src_dll = os.path.abspath(servicemanager.__file__)
            #这里需要注意  他里边得参数要是你得类名SpiderService 下边同样得
            servicemanager.PrepareToHostSingle(SpiderService)
            servicemanager.Initialize('SpiderService', event_src_dll)
            servicemanager.StartServiceCtrlDispatcher()
        except win32service.error as details:
            if details == winerror.ERROR_FAILED_SERVICE_CONTROLLER_CONNECT:
                win32serviceutil.usage()
    else:
        win32serviceutil.HandleCommandLine(SpiderService)

命令 更多得可以搜一下 install 之后会安装到服务里边但是并没有开启
python xxx.py install
python xxx.py start
python xxx.py stop
python xxx.py remove

打包 我这边用得是pyinstaller
pyinstaller -F -w xxx.py
#打包完成后 命令是:(与之前得差不多)
xxx.exe install
xxx.exe start
...
posted @ 2021-12-10 14:32  Carl-  阅读(399)  评论(0编辑  收藏  举报