本文实例讲述了以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程序设计有所帮助。