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

yipeiwu_com6年前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简单实现控制电脑的方法。分享给大家供大家参考,具体如下: 1、windows 下,CMD的一些命令: dir:列出当前的所有文件 time:打印当前的时间 tr...

详解使用django-mama-cas快速搭建CAS服务的实现

详解使用django-mama-cas快速搭建CAS服务的实现

当公司有多条产品线,或者有多个不同的应用的时候,每次都做登录是个非常烦人的事情。(原谅我没有从SSO的角度看这个问题。。对我来说能偷懒少写点东西最实在)。为什么需要每次都做个登录?做登录...

给我一面国旗 python帮你实现

给我一面国旗 python帮你实现

本文实例为大家分享了Python之给我一面国旗的具体代码,供大家参考,具体内容如下 1、“给我一面国旗@微信官方” 今天“给我一面国旗@微信官方”刷爆了朋友圈,我也蹭波热度,出个Pyth...

python如何把嵌套列表转变成普通列表

如何把[1, 5, 6, [2, 7, [3, [4, 5, 6]]]]变成[1, 5, 6, 2, 7, 3, 4, 5, 6]? 思考:   -- for循环每次都遍历列表一层   ...

用python写asp详细讲解

用python写asp详细讲解

一、ASP的平反想到ASP 很多人会说 “asp语言很蛋疼,不能面向对象,功能单一,很多东西实现不了” 等等诸如此类。 以上说法都是错误的,其一ASp不是一种语言是 微软用来代替CGI的...