iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > Python >使用Python写Windows Ser
  • 813
分享到

使用Python写Windows Ser

PythonWindowsSer 2023-01-31 05:01:55 813人浏览 独家记忆

Python 官方文档:入门教程 => 点击学习

摘要

1.背景 如果你想用python开发windows程序,并让其开机启动等,就必须写成windows的服务程序Windows Service,用python来做这个事情必须要借助第三方模块pywin32,自己去下载然后安装(注意下载符合

1.背景

如果你想用python开发windows程序,并让其开机启动等,就必须写成windows的服务程序Windows Service,用python来做这个事情必须要借助第三方模块pywin32,自己去下载然后安装(注意下载符合自己OS的版本)

2.实例

先上代码

复制代码
#encoding=utf-8  
import win32serviceutil   
import win32service   
import win32event  
import os   
import logging  
import inspect
import servicemanager
  
class PythonService(win32serviceutil.ServiceFramework):   
  
    _svc_name_ = "PythonService"  #服务名 
    _svc_display_name_ = "Python Service Test"  #服务在windows系统中显示的名称
    _svc_description_ = "This is a python service test code "  #服务的描述
  
    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):  
        import time  
        self.logger.info("service is run....")   
        while self.run:  
            self.logger.info("I am runing....")  
            time.sleep(2)  
              
    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:
            evtsrc_dll = os.path.abspath(servicemanager.__file__)
            servicemanager.PrepareToHostSingle(PythonService)
            servicemanager.Initialize('PythonService', evtsrc_dll)
            servicemanager.StartServiceCtrlDispatcher()
        except win32service.error, details:
            if details[0] == winerror.ERROR_FAILED_SERVICE_CONTROLLER_CONNECT:
                win32serviceutil.usage()
    else:
        win32serviceutil.HandleCommandLine(PythonService)
复制代码

解释一下代码:

1).在类PythonService的__init__函数执行完后,系统服务开始启动,windows系统会自动调用SvcDoRun函数,这个函数的执行不可以结束,因为结束就代表服务停止。所以当我们放自己的代码在SvcDoRun函数中执行的时候,必须确保该函数不退出。

2).当停止服务的时候,系统会调用SvcDoStop函数,该函数通过设置标志位等方式让SvcDoRun函数退出,就是正常的停止服务。例子中是通过event事件让SvcDoRun函数停止等待,从而退出该函数,从而使服务停止。系统关机时不会调用SvcDoStop函数,所以这种服务是可以设置为开机自启的。

3.服务操作命令

复制代码
#1.安装服务

python PythonService.py install

#2.让服务自动启动

python PythonService.py --startup auto install 

#3.启动服务

python PythonService.py start

#4.重启服务

python PythonService.py restart

#5.停止服务

python PythonService.py stop

#6.删除/卸载服务

python PythonService.py remove
复制代码

4.使用pyinstaller打包exe

pyinstaller.exe -F -c winService.py

效果:

image

image

5.管理windows服务操作

复制代码
#!/usr/bin/env python
# -*- coding: UTF8 -*-
#
import win32service
import win32con
import time, sys
import datetime
reload(sys)
sys.setdefaultencoding("utf8")
class ServiceManager(object):
    """管理window服务"""

    def __init__(self, name):
        """
        name: 服务的名称
        """
        self.name = name
        
        #启动或停止服务时等待操作成功等待时间
        self.wait_time = 0.5
        #启动或停止服务时最大等待时间,超过时返回超时提示
        self.delay_time = 10
        self.scm = win32service.OpenSCManager(None, None, win32service.SC_MANAGER_ALL_ACCESS)


        if self.is_exists():
            try:
                self.handle = win32service.OpenService(self.scm, self.name, win32service.SC_MANAGER_ALL_ACCESS)
            except Exception, e:
                self.log(e)
        else:
            print '服务 %s 没有安装'.encode('gbk') % self.name
            

    def is_stop(self):
        """检查服务是否停止"""
        flag = False
        try:
            if self.handle:
                ret = win32service.QueryServiceStatus(self.handle)
                flag = ret[1] != win32service.SERVICE_RUNNING
        except Exception, e:
            self.log(e)
        return flag

    def start(self):
        """开启服务"""
        try:
            if self.handle:
                win32service.StartService(self.handle, None)
        except Exception, e:
            self.log(e)
        status_info = win32service.QueryServiceStatus(self.handle)

        if status_info[1] == win32service.SERVICE_RUNNING:
            return '启动服务%s成功'.encode('gbk') % self.name
        elif status_info[1] == win32service.SERVICE_START_PENDING:
            #如果服务正在启动中则延迟返回启动信息,直到启动成功,或返回启动时间过长信息
            start_time = datetime.datetime.now()
            while True:
                if (datetime.datetime.now() - start_time).seconds > self.delay_time:
                    return '启动服务%s时间太长'.encode('gbk') % self.name

                time.sleep(self.wait_time)
                if win32service.QueryServiceStatus(self.handle)[1] == win32service.SERVICE_RUNNING:
                    return '启动服务%s成功'.encode('gbk') % self.name
        else:
            return '启动服务%s失败'.encode('gbk') % self.name

    def stop(self):
        """停止服务"""
        try:
            status_info = win32service.ControlService(self.handle, win32service.SERVICE_CONTROL_STOP)
        except Exception, e:
            self.log(e)
        if status_info[1] == win32service.SERVICE_STOPPED:
            return '停止服务%s成功'.encode('gbk') % self.name
        elif status_info[1] == win32service.SERVICE_STOP_PENDING:
            start_time = datetime.datetime.now()
            while True:
                if (datetime.datetime.now() - start_time).seconds > self.delay_time:
                    return '停止服务%s时间太长'.encode('gbk') % self.name

                time.sleep(self.wait_time)
                if win32service.QueryServiceStatus(self.handle)[1] == win32service.SERVICE_STOPPED:
                    return '停止服务%s成功'.encode('gbk') % self.name
        else:
            return '停止服务%s失败'.encode('gbk') % self.name

    def restart(self):
        """重启服务"""
        if not self.is_stop():
            self.stop()
        self.start()
        return win32service.QueryServiceStatus(self.handle)

    def status(self):
        """获取运行的状态"""
        try:
            status_info = win32service.QueryServiceStatus(self.handle)
            status = status_info[1]
            if status == win32service.SERVICE_STOPPED:
                return "STOPPED"
            elif status == win32service.SERVICE_START_PENDING:
                return "STARTING"
            elif status == win32service.SERVICE_STOP_PENDING:
                return "STOPPING"
            elif status == win32service.SERVICE_RUNNING:
                return "RUNNING"
        except Exception, e:
            self.log(e)

    def close(self):
        """释放资源"""
        try:
            if self.scm:
                win32service.CloseServiceHandle(self.handle)
                win32service.CloseServiceHandle(self.scm)
        except Exception, e:
            self.log(e)

    def is_exists(self):
        """windows服务是否已安装"""
        statuses = win32service.EnumServicesStatus(self.scm, win32service.SERVICE_WIN32, win32service.SERVICE_STATE_ALL)
        for (short_name, desc, status) in statuses:
            if short_name == self.name:
                return True
        return False

    def log(self, exception):
        
        print(exception)
        
        

if __name__=='__main__':

    app= ServiceManager('PythonService')
    msg= app.is_exists()  # 判断是否安装  (以下操作必须先判断服务是否存在)
    #msg= app.is_stop()  # 判断服务是否停止
    #msg= app.status()  # 查看服务的状态
    #msg= app.start()  # 开启服务
    #msg= app.stop()  # 暂停服务   (服务开启才能停止,else error)
    #msg= app.restart()  # 重启服务
    
    print(msg)
复制代码

--结束END--

本文标题: 使用Python写Windows Ser

本文链接: https://www.lsjlt.com/news/188285.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • 使用Python写Windows Ser
    1.背景 如果你想用Python开发Windows程序,并让其开机启动等,就必须写成windows的服务程序Windows Service,用Python来做这个事情必须要借助第三方模块pywin32,自己去下载然后安装(注意下载符合...
    99+
    2023-01-31
    Python Windows Ser
  • 如何使用Python编写HTTP请求的Windows函数?
    随着互联网的发展,HTTP请求已经成为了我们日常开发中不可或缺的一部分。Python作为一种流行的编程语言,也提供了HTTP请求的相关模块,比如requests和urllib等。但是,有时候我们需要在Windows平台下使用Python编...
    99+
    2023-08-01
    windows 函数 http
  • 写写python中try的使用
    python中try的使用 在 Python 中,try 是用于异常处理的关键字。try 语句的语法如下: try: # 可能会抛出异常的语句块except ExceptionType1: ...
    99+
    2023-09-20
    python java 前端
  • 如何使用 Python 在 Windows 系统中编写 JavaScript 接口?
    在现代 Web 开发中,JavaScript 是一种非常流行的语言。然而,有时候我们需要在不同的语言之间进行通信,这时候就需要编写接口。本文将介绍如何使用 Python 在 Windows 系统中编写 JavaScript 接口。 安装...
    99+
    2023-08-11
    windows 接口 javascript
  • 如何在Windows上使用Python编写HTTP请求函数?
    Python是一种功能强大的编程语言,它可以用来编写各种类型的程序,包括网络应用程序。在本文中,我们将介绍如何在Windows上使用Python编写HTTP请求函数。 HTTP请求是发送到Web服务器的请求,请求可以是获取Web页面、上传...
    99+
    2023-08-01
    windows 函数 http
  • mac使用vim编写Python
    1)打开终端,输入cd + 文件夹路径 链接到你要创建的py文件路径 2)输入 vim hello.py 使用vim命令新建hello.py文件,按 i 进入编辑模式 3)输入自己的代码#!/usr/bin/env python3 p...
    99+
    2023-01-31
    mac vim Python
  • 使用python 写xml文件
    ''' 开发一个给大百度的接口,各种要求,写一个xml文件,倒是不是很难 ''' import xml,datetime,codecs import xml.dom.minidom as minidom def covert_to_un...
    99+
    2023-01-31
    文件 python xml
  • Python使用openpyxl读写ex
    Python使用读写excel文件 Python使用openpyxl读写excel文件这是一个第三方库,可以处理xlsx格式的Excel文件。pip install openpyxl安装。如果使用Aanconda,应该自带了。 读取Exce...
    99+
    2023-01-31
    Python openpyxl
  • 使用Python写CUDA程序
    使用Python写CUDA程序有两种方式: * Numba * PyCUDA numbapro现在已经不推荐使用了,功能被拆分并分别被集成到accelerate和Numba了。 例子 numba Numba通过及时编译机制(...
    99+
    2023-01-31
    程序 Python CUDA
  • 使用Python写spark 示例
    个人GitHub地址: https://github.com/LinMingQiang 为什么要使用Python来写Spark Python写spark我认为唯一的理由就是:你要做数据挖掘,AI相关的工作。因为很多做数挖的他们的基...
    99+
    2023-01-31
    示例 Python spark
  • 如何在Windows平台上使用Python编写HTTP请求函数库?
    在本篇文章中,我们将讨论如何在Windows平台上使用Python编写HTTP请求函数库。HTTP请求函数库是一个用于向Web服务器发送HTTP请求的Python库。在本文中,我们将讨论如何编写这样一个库,并提供一些示例代码来说明如何使用它...
    99+
    2023-08-01
    windows 函数 http
  • Windows下如何使用PHP编写Shell脚本?
    在Windows操作系统下,使用PHP编写Shell脚本可以帮助我们自动化执行各种任务,从而提高效率。接下来,我们将介绍如何在Windows下使用PHP编写Shell脚本。 首先,我们需要安装PHP。可以在PHP官网下载Windows版本的...
    99+
    2023-07-01
    path windows shell
  • 使用Python读写csv文件
    简介:CSV (Comma Separated Values) 格式是电子表格和数据库中最常见的输入、输出文件格式。又称逗号分隔值(Comma-Separated Values,CS...
    99+
    2024-04-02
  • 使用python脚本向influxdb写
    python3使用requests模块向influxdb的http API发送接口请求实现数据写入,如下: 1. 创建数据库 import requests posturl = 'http://192.168.220.128:8086/...
    99+
    2023-01-31
    脚本 python influxdb
  • 怎么使用vscode编写Python
    本篇内容主要讲解“怎么使用vscode编写Python”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“怎么使用vscode编写Python”吧!vscode是一款由微软开发,同时支持windows...
    99+
    2023-06-27
  • 使用Python在Windows下调用W
    import os  import time   source='C:\\Linda\\Test\\Python\\source' target_dir='C:\\Linda\\Test\\Python\\backup\\'  target...
    99+
    2023-01-31
    Python Windows
  • python学习-windows下使用p
       有时候需要处理很多报表,将一个目录下的所有excel格式报表合并,手工操作费事费力如果能使用python,将多个.xlsx同时能够合并多个excel表的话,多么方便。1、windows上python配置windows上安装的是pyth...
    99+
    2023-01-31
    python windows
  • python------用python写
    这样一个小游戏,我们用shell也是可以完成的,但是这里我们主要是练习python!具体的要求及shell的写法http://zidingyi.blog.51cto.com/10735263/1767566!#!/usr/bin/env p...
    99+
    2023-01-31
    python
  • 如何在Windows系统中使用Python编写高效的算法和接口?
    Python是一种强大的编程语言,可以用于各种任务,包括算法和接口开发。Python在Windows操作系统上的安装和使用非常简单,可以通过下载和安装Python官方发行版来开始编写代码。在本文中,我们将讨论如何在Windows系统中使用...
    99+
    2023-08-31
    windows 编程算法 接口
  • python操作Excel读写--使用x
      一、安装xlrd模块    到python官网下载http://pypi.python.org/pypi/xlrd模块安装,前提是已经安装了python 环境。 二、使用介绍   1、导入模块       import xlrd  ...
    99+
    2023-01-31
    操作 python Excel
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作