python程序封装为win32服务的方法

本文实例为大家分享了python程序封装为win32服务的具体代码,供大家参考,具体内容如下

# encoding=utf-8
import os
import sys
import winerror
import win32serviceutil
import win32service
import win32event
import servicemanager

class PythonService(win32serviceutil.ServiceFramework):

 # 服务名
 _svc_name_ = "PythonService1"
 # 服务显示名称
 _svc_display_name_ = "PythonServiceDemo"
 # 服务描述
 _svc_description_ = "Python service demo."

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

 def _getLogger(self):
  import logging
  import os
  import inspect

  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.error("svc do run....")
  try:
   while self.isAlive:
    self.logger.error("I am alive.")
    time.sleep(1)
    # 等待服务被停止
    # win32event.WaitForSingleObject(self.hWaitStop, win32event.INFINITE)
  except Exception as e:
   self.logger.error(e)
   time.sleep(60)

 def SvcStop(self):
  # 先告诉SCM停止这个过程
  self.logger.error("svc do stop....")
  self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
  # 设置事件
  win32event.SetEvent(self.hWaitStop)
  self.isAlive = 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)
   #if details[0] == winerror.ERROR_FAILED_SERVICE_CONTROLLER_CONNECT:
    #win32serviceutil.usage()
 else:
  win32serviceutil.HandleCommandLine(PythonService) # 参数和上述定义类名一致

#pip install pywin32

# 安装服务
# 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

# 在用户变量处去掉python路径,然后在环境变量加入python路径
# C:\Users\zhongjianhui\AppData\Local\Programs\Python\Python36\Lib\site-packages\pywin32_system32;
# C:\Users\zhongjianhui\AppData\Local\Programs\Python\Python36\Lib\site-packages\win32;
# C:\Users\zhongjianhui\AppData\Local\Programs\Python\Python36\Scripts\;
#C:\Users\zhongjianhui\AppData\Local\Programs\Python\Python36\

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

(0)

相关推荐

  • python 调用win32pai 操作cmd的方法

    实例如下: #coding=utf-8 import subprocess from time import * import win32api import win32con import win32gui subprocess.Popen('C:\windows\system32\cmd.exe') sleep(1) a=65;b=66;c=67;d=68;e=69;f=70;g=71;h=72;i=73;j=74;k=75 l=76;m=77;n=78;o=79;p=80;q=81;r=8

  • python安装pywin32clipboard的操作方法

    要使用到剪贴板的方法,搜索到有两个包可以用,pyperclip,和pywin32clipboard,pyperclip在3.5版本中不能够import,可以手动下载安装,未查到原因:pywin32clipboad不能用pip install 安装,也不能够查找到这个包,原来,这个是pywin32的一部分,直接安装pywin32就可以了. import win32clipboard win32clipboard.OpenClipboard() data = win32clipboard.GetCl

  • python win32 简单操作方法

    源由 刚开始是帮朋友做一个按键精灵操作旺信的脚本,写完后各种不稳定:后来看到python可以操作win32相关的api,恰好这一段时间正在学习python,感觉练手的时候到了~~~ 下载 要注意Python版本及位数,否则会安装失败 直接到上面的地址去找合适的版本下载安装,已包含其它的工具 下载的已经是可执行文件,直接执行即可 https://sourceforge.net/projects/pywin32/ 获取句柄的方式 VC或VS工具里面自带SPY++,可以获取句柄信息, 这个你没有,请看

  • Python win32com 操作Exce的l简单方法(必看)

    实例如下: from win32com.client import Dispatch import win32com.client class easyExcel: """A utility to make it easier to get at Excel. Remembering to save the data is your problem, as is error handling. Operates on one workbook at a time."

  • Python使用win32com实现的模拟浏览器功能示例

    本文实例讲述了Python使用win32com实现的模拟浏览器功能.分享给大家供大家参考,具体如下: # -*- coding:UTF-8 -*- #!/user/bin/env python ''' Created on 2010-9-1 @author: chenzehe ''' import win32com.client from time import sleep loginurl='http://passport.cnblogs.com/login.aspx' loginouturl

  • python程序封装为win32服务的方法

    本文实例为大家分享了python程序封装为win32服务的具体代码,供大家参考,具体内容如下 # encoding=utf-8 import os import sys import winerror import win32serviceutil import win32service import win32event import servicemanager class PythonService(win32serviceutil.ServiceFramework): # 服务名 _sv

  • apache部署python程序出现503错误的解决方法

    前言 本文主要给大家介绍了解决apahce部署python程序出现503错误的相关内容,下面话不多说了,下一起看看详细的介绍吧. 发现问题 今天更新服务器后,发现使用apache部署的某个python程序无法访问了,返回503错误,报错日志如下: [Thu Apr 13 10:54:40 2017] [error] [client 127.0.0.1] (13)Permission denied: mod_wsgi (pid=1814): Unable to connect to WSGI da

  • 小程序封装路由文件和路由方法(5种全解析)

    小程序5种路由方法使用场景,封装路由文件和路由方法,提升小程序体验和开发效率 明确要解决的问题 每次使用路由时,总是粘贴复制路径,这样在路径有修改时,需要修改所有用到该路径的地方,维护成本高 路由跳转时拼接参数让人头大,业务复杂时要拼接十几个参数 路由返回,只会返回一层,不能直接返回到目标页面,因为不知道目标页面是否在路由栈中,也不知道在第几层 这些问题都可以通过封装路由文件和路由方法解决,提供开发效率,减少BUG,省下来的时间可以多陪陪女朋友 封装路由文件,对路由进行统一管理 在根目录创建ro

  • python程序变成软件的实操方法

    本人新学python,发现python程序转成软件好麻烦,为了方便大家,同时自己整理下资源,发布以下教程哦. 下载 "pywin32"软件,选择最新的build文件夹,支持新版本的python 下载完毕后进行安装,需要相应版本的python作为支持 安装完成后,打开cmd,输入"pip install pywin32",如果pywin32程序老旧,会提示你输入 "python -m pip install --upgrade pip"命令自动更新

  • 通过Py2exe将自己的python程序打包成.exe/.app的方法

    Windows 10 x64 macOS Sierra 10.12.4 Python 2.7 准备好装哔~了么,来吧,做个真正意义上的绿色小软件 Win下发布应用 起因 今天实验室同学看到我的乞丐版二输入规则器,他挺感兴趣的,也想要玩玩,但是他没有装python的环境,总不能让他一直玩我电脑吧,所以想到了将程序打包成exe,直接运行!想法一出来,根本挡不住啊,说干就干,先百度python打包exe,一大堆答案,我整理了一下,大概有Py2exe和pyinstaller两种,但是,我给你看张图 这是

  • 在Python程序中操作MySQL的基本方法

    Python操作Mysql 最近在学习python,这种脚本语言毫无疑问的会跟数据库产生关联,因此这里介绍一下如何使用python操作mysql数据库.我python也是零基础学起,所以本篇博客针对的是python初学者,大牛可以选择绕道. 另外,本篇基于的环境是Ubuntu13.10,使用的python版本是2.7.5. MYSQL数据库 MYSQL是一个全球领先的开源数据库管理系统.它是一个支持多用户.多线程的数据库管理系统,与Apache.PHP.Linux共同组成LAMP平台,在web应

  • 在Python程序中操作文件之flush()方法的使用教程

    flush()方法刷新内部缓冲区,像标准输入输出的fflush.这类似文件的对象,无操作. Python关闭时自动刷新文件.但是可能要关闭任何文件之前刷新数据. 语法 以下是flush()方法的语法: fileObject.flush(); 参数 NA 返回值 此方法不返回任何值. 例子 下面的例子显示了flush()方法的使用. #!/usr/bin/python # Open a file fo = open("foo.txt", "wb") print &qu

  • 在Python程序中操作文件之isatty()方法的使用教程

    如果文件已连接(与终端设备相关联)到一个tty(状)的设备,isatty()方法返回True,否则返回False. 语法 以下是isatty()方法的语法: fileObject.isatty(); 参数 NA 返回值 如果该文件被连接(与终端设备相关联)到一个tty(类似终端)设备此方法返回true,否则返回false. 例子 下面的例子显示了isatty()方法的使用. #!/usr/bin/python # Open a file fo = open("foo.txt", &qu

  • python程序快速缩进多行代码方法总结

    该语言中缩进是其精髓,通过缩进可以表示函数.循环等程序结构的范围.有时写完程序后,发现所有程序需要放入函数def中,这时就需要对一整块程序同时进行缩进,还有其他一些情况,也会需要多行整体缩进.下面介绍官方的IDLE编辑器下,如何实现多行整体缩进. 这里介绍的是针对3.0及以上版本,软件自带编辑器,整块缩进的方法.首先通过开始菜单 ,找到IDLE,点击启动软件. 相关推荐:<Python视频教程> 启动软件后,通过file菜单下,打开或新建选项,打开一个已建好的或者新创建一个程序文件,这里新建一

  • 在微信小程序中使用mqtt服务的方法

    因为需求的关系,需要在小程序中使用mqtt来进行tcp的长连接,实时监听设备的返回状态. js中连接mqtt服务器是通过websocket来实现的,我在网上找了2个库,一个是eclipse开发的paho-mqtt. 项目地址:https://github.com/eclipse/paho.mqtt.javascript 一个是个人开发的mqttjs,项目地址:https://github.com/mqttjs/MQTT.js 比较了下,mqqtt.js比较灵活对小程序也有很好的支持,所以采用了这

随机推荐