以windows service方式运行Python程序的方法

yipeiwu_com5年前Python基础

本文实例讲述了以windows service方式运行Python程序的方法。分享给大家供大家参考。具体实现方法如下:

#!/usr/bin/env python 
# coding: utf-8 
# SmallestService.py 
# 
# A sample demonstrating the smallest possible service written in Python.
import win32serviceutil 
import win32service 
import win32event 
import time 
class SmallestPythonService(win32serviceutil.ServiceFramework): 
  _svc_name_ = "SmallestPythonService" 
  _svc_display_name_ = "The smallest possible Python Service" 
  def __init__(self, args): 
    win32serviceutil.ServiceFramework.__init__(self, args) 
    # Create an event which we will use to wait on. 
    # The "service stop" request will set this event. 
    self.hWaitStop = win32event.CreateEvent(None, 0, 0, None) 
  def SvcStop(self): 
    # Before we do anything, tell the SCM we are starting the stop process. 
    self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) 
    # And set my event. 
    win32event.SetEvent(self.hWaitStop) 
  def SvcDoRun(self): 
    #把你的程序代码放到这里就OK了 
    f=open('d:\\log.txt','w',0) 
    f.write(time.ctime(time.time())) 
    f.close() 
    win32event.WaitForSingleObject(self.hWaitStop, win32event.INFINITE) 
if __name__=='__main__': 
  win32serviceutil.HandleCommandLine(SmallestPythonService)  
  # 括号里的名字可以改成其他的,必须与class名字一致;

希望本文所述对大家的Python程序设计有所帮助。

相关文章

python实现识别相似图片小结

python实现识别相似图片小结

文章简介 在网上看到python做图像识别的相关文章后,真心感觉python的功能实在太强大,因此将这些文章总结一下,建立一下自己的知识体系。 当然了,图像识别这个话题作为计算机科学的...

python 专题九 Mysql数据库编程基础知识

python 专题九 Mysql数据库编程基础知识

在Python网络爬虫中,通常是通过TXT纯文本方式存储,其实也是可以存储在数据库中的;同时在WAMP(Windows、Apache、MySQL、PHP或Python)开发网站中,也可以...

Python读取Pickle文件信息并计算与当前时间间隔的方法分析

本文实例讲述了Python读取Pickle文件信息并计算与当前时间间隔的方法。分享给大家供大家参考,具体如下: python—–读取Pickle文件信息计算出与当前的时间间隔 生成h_d...

Python编程中装饰器的使用示例解析

装饰函数和方法 我们先定义两个简单的数学函数,一个用来计算平方和,一个用来计算平方差: # get square sum def square_sum(a, b): return...

Python 实现「食行生鲜」签到领积分功能

Python 实现「食行生鲜」签到领积分功能

用过食行生鲜的同学应该知道,每天可以在食行生鲜签到,签到可以领到 20 积分,在购物时可以抵 2 毛钱。钱虽少,但是积少成多,买菜时可以抵扣一两块钱还是不错的。 今天我们就用 Pytho...