最近做了公司签到的小工具,有同事要求做成Windows服务,开机自启。先说下怎么用Python写Windows服务程序。

 #encoding=utf-8
import win32serviceutil
import win32service
import win32event
import win32timezone
import os class PythonService(win32serviceutil.ServiceFramework):
_svc_name_ = 'PythonService' #服务名称
_svc_display_name_ = 'regMeal'
_svc_description_ = '每天晚上6:40后自动签到' 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):
import inspect
import logging
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
import readconfig
import regMeal
self.logger.info('service is run...')
while self.run:
self.logger.info('service is running...')
paraList = readconfig.readConfig()
bFlag = regMeal.main(paraList[0],paraList[1],paraList[2])
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__':
import sys
import servicemanager
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 as details:
import winerror
if details == winerror.ERROR_FAILED_SERVICE_CONTROLLER_CONNECT:
win32serviceutil.usage()
else:
win32serviceutil.HandleCommandLine(PythonService)

推荐大家对比网上其他的人的代码对照看下。SvcDoRun这个函数里面放的就是你实际想做的事情。

安装服务

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

我自己是用pyinstaller打包成exe给别人用的。

PS:脚本编好之后,调试了很久。刚开始会报服务无法启动的问题。具体的排查方式可以看Windows事件查看。

Python3编写Windows服务程序的更多相关文章

  1. C语言编写Windows服务程序

    原文:C语言编写Windows服务程序 #include <Windows.h> #include <stdio.h> #define SLEEP_TIME 5000 // 间 ...

  2. 编写windows服务程序

    2012-11-02 08:54 (分类:计算机程序) windows服务是一个运行在后台并实现勿需用户交互的任务的控制台程序,对于隐藏程序有很大帮助. 用了几天时间概括了编写windows服务程序的 ...

  3. 用 C 语言编写 Windows 服务程序的五个步骤

    Windows 服务被设计用于需要在后台运行的应用程序以及实现没有用户交互的任务.为了学习这种控制台应用程序的基础知识,C(不是C++)是最佳选择.本文将建立并实现一个简单的服务程序,其功能是查询系统 ...

  4. 用C语言编写Windows服务程序的五个步骤

    Windows 服务被设计用于需要在后台运行的应用程序以及实现没有用户交互的任务.为了学习这种控制台应用程序的基础知识,C(不是C++)是最佳选择.本文将建立并实现一个简单的服务程序,其功能是查询系统 ...

  5. C#编写Windows服务程序图文教程

    安装服务程序C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe  要安装的服务程序路径(如F:\***.exe)卸载服务程序C: ...

  6. C#编写Windows服务程序 (服务端),client使用 消息队列 实现淘宝 订单全链路效果

    需求: 针对 淘宝提出的 订单全链路 产品接入 .http://open.taobao.com/doc/detail.htm?id=102423&qq-pf-to=pcqq.group oms ...

  7. C#编写windows服务程序

    Windows Service这一块并不复杂,但是注意事项太多了,网上资料也很凌乱,偶尔自己写也会丢三落四的.所以本文也就产生了,本文不会写复杂的东西,完全以基础应用的需求来写,所以不会对Window ...

  8. C#编写Windows服务程序图文教程(转载)

    Windows Service这一块并不复杂,但是注意事项太多了,网上资料也很凌乱,偶尔自己写也会丢三落四的.所以本文也就产生了,本文不会写复杂的东西,完全以基础应用的需求来写,所以不会对Window ...

  9. 用Visual C#创建Windows服务程序

    一.Windows服务介绍: Windows服务以前被称作NT服务,是一些运行在Windows NT.Windows 2000和Windows XP等操作系统下用户环境以外的程序.在以前,编写Wind ...

随机推荐

  1. web开发如何使用高德地图API(四)通过AMap.Marker自定义标点

    说两句: 以下内容除了我自己写的部分,其他部分在高德开放平台都有(可点击外链访问). 我所整理的内容以实际项目为基础希望更有针对性的,更精简. 点击直奔主题. 准备工作: 首先,注册开发者账号,成为高 ...

  2. 2、ceph-deploy之配置使用RBD

    说明 部署完ceph集群(active+clean状态)之后, 我们来实践下ceph block device(即RBD或RADOS block device). 我们需要在一台新的client节点上 ...

  3. VI 快捷操作 【持续更新】

    2014-9-23 一.   大小写转换 vim中大小写转化的命令是 gu或者gU 形象一点的解释就是小u意味着转为小写:大U意味着转为大写. 剩下的就是对这两个命令的限定(限定操作的行,字母,单词) ...

  4. 【ACM】hdu_1808_Halloween treats_201308132022

    Halloween treats Time Limit: 1000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others) ...

  5. 【ACM】hdu_1276_士兵队列训练问题_201308131032

    士兵队列训练问题Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)Total Sub ...

  6. 洛谷 P2548 [AHOI2004]智能探险车

    P2548 [AHOI2004]智能探险车 题目描述 输入输出格式 输入格式: 输出格式: 输入输出样例 输入样例#1: 复制 4 3 sunny plain full many sunny moun ...

  7. springmvc 中开发Server Send Event

    springmvc 中开发Server Send Event 学习了:http://blog.csdn.net/leiliz/article/details/55195203 https://www. ...

  8. jQuery Validate 使用

    jQuery Validate 使用 <script src="js/b/js/jquery.validate.js"></script> <styl ...

  9. Shredding Company (hdu 1539 dfs)

    Shredding Company Time Limit: 5000/2000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others ...

  10. 基于Windows Azure 搭建基于SharePoint 2010 Intranet、Extranet、Internet (4): 配置传出邮件服务: 使用 outlook.com 发送邮件通知

    前几篇文章,已经安装了SharePoint 2010,今天将演示如何配置传出邮件.由于某些原因,企业可能没有安装自己邮件服务器,此时我们可以使用公共的邮箱服务来发送邮件通知,比如outlook.com ...