开发环境:

python3.7

第三方库:pywin32

CS通信:socket,案例见Python3-实现网络通信,客户端调用服务端的系统命令ipconfig(Socket/Subprocess)

用途:

客户端下发操作指令,测试机(安装python服务)监听并实时执行指令,并把结果返回给客户端

脚本:

pythonservice.py

#!/usr/bin/python
#!encoding:utf-8
'''
Author:xianqc
Date:2020-08-01
'''
import win32serviceutil
import win32service
import win32event
import os,sys
import logging
import inspect
import servicemanager
import server

class PythonService(win32serviceutil.ServiceFramework):
    _svc_name_ = "PythonService"  # 服务名
    _svc_display_name_ = "PythonService"  # 服务在windows系统中显示的名称
    _svc_description_ = "PythonService"  # 服务的描述

    def __init__(self, args):
        win32serviceutil.ServiceFramework.__init__(self, args)
        self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
        self.logger = self._getLogger()
        self.run = True

    def _getLogger(self):
        logger = logging.getLogger('[PythonService]')
        this_file = inspect.getfile(inspect.currentframe())
        dirpath = os.path.abspath(os.path.dirname(this_file))
        handler = logging.FileHandler(os.path.join(dirpath, "service.log"))
        formatter = logging.Formatter('%(asctime)s %(name)-12s %(levelname)-8s %(message)s')
        handler.setFormatter(formatter)
        logger.addHandler(handler)
        logger.setLevel(logging.INFO)
        return logger

    def SvcDoRun(self):
        self.logger.info("service is run....")
        while self.run:
            try:
                server.serverRun()
                self.logger.info("I am runing....")
            except:
                self.run=False

    def SvcStop(self):
        self.logger.info("service is stop....")
        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
        win32event.SetEvent(self.hWaitStop)
        self.run = False

if __name__ == '__main__':
    if len(sys.argv) == 1:
        try:
            src_dll = os.path.abspath(servicemanager.__file__)
            servicemanager.PrepareToHostSingle(PythonService)
            servicemanager.Initialize("PythonService", src_dll)
            servicemanager.StartServiceCtrlDispatcher()
        except Exception as e:
            print(e)
    else:
        win32serviceutil.HandleCommandLine(PythonService)  # 参数和上述定义类名一致

python服务的常用命令

Windows下将服务安装到系统方法:

安装服务
python PythonService.py install

更新服务
python PythonService.py update

让服务自动启动
python PythonService.py --startup auto install

启动服务
python PythonService.py start

重启服务
python PythonService.py restart

停止服务
python PythonService.py stop

删除/卸载服务
python PythonService.py remove

使用pyinstaller打包为exe可放到任意机器上安装服务:D:\python\Scripts>pyinstaller -F --hidden-import=win32timezone D:\test\test.py

运行效果

 python服务启动

客户端发送指令,并接收到返回结果

 

Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐