Python 添加windows server服务程序

简介

添加windows server服务,实现python程序开机自动


第三方库

pywin32

下载地址:https://pypi.python.org/pypi/pywin32


代码

# -*- coding: utf-8 -*-
import logging
import time
import win32service
import win32serviceutil
import win32event

logging.basicConfig(level=logging.INFO,
                    format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
                    datefmt='%a, %d %b %Y %H:%M:%S',
                    filename='e:/monitor/demo.log',
                    filemode='a')

servername = "DemoServer"  # windows服务名称


# Demo.py 10秒关闭程序,模拟程序崩溃
# author 胖胖的alex 2017/09/10
class Demo:

    def __init__(self):
        pass

    def execute(self):
        logging.info("启动程序")
        i = 1
        while True:
            logging.info("servername = " + servername + " ---------- run " + str(i) + " s ")
            time.sleep(1)
            i += 1
            if i > 10:
                break
        logging.info("程序关闭...")


# 程序加入windows服务类
class Win32Server(win32serviceutil.ServiceFramework):
    _svc_name_ = servername
    _svc_display_name_ = servername
    _svc_description_ = servername

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

    def SvcDoRun(self):

        logging.info("windows服务启动...")
        rc = None
        demo = Demo()

        # if the stop event hasn't been fired keep looping
        while rc != win32event.WAIT_OBJECT_0:
            demo.execute()
            time.sleep(2)
            # block for 5 seconds and listen for a stop event
            rc = win32event.WaitForSingleObject(self.hWaitStop, 5000)

        logging.info("windows服务关闭...")

    # called when we're being shut down
    def SvcStop(self):
        # tell the SCM we're shutting down
        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
        # fire the stop event
        win32event.SetEvent(self.hWaitStop)


if __name__ == '__main__':
    win32serviceutil.HandleCommandLine(Win32Server)


操作命令

  • 安装:python PythonService.py install
  • 自启动安装:python PythonService.py --startup auto install
  • 启动服务:python PythonService.py start 
  • 重启服务:python PythonService.py restart
  • 停止服务:python PythonService.py stop
  • 卸载服务:python PythonService.py remove


注意事项

  1. 操作命令输入的控制台必须是管理员cmd
  2. 截至2017/09/10,pywin32支持python3.5或以下版本

参考文章

  • Python 写Windows Service服务程序 http://www.cnblogs.com/dcb3688/p/4496934.html

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值