一個最簡單的用PYTHON實現的WINDOWS服務程序

2009-12-05 02:54:07

1、想寫一個監視服務器是否運行的簡單服務,網上搜到的例程不太完善,如梅勁松的許久沒有更新,而且SvcDoRun寫得不完整(見http://www.chinaunix.net/jh/55/558190.html

不知道是不是原始出處);而mail.python.org中的沒有定義_svc_name_等變量(見

http://mail.python.org/pipermail/python-list/2005-December/315190.html

2、這個實現功能很簡單,就是把當前時間寫入‘c:\\temp\\time.txt’文件,一看即知,大家可以隨意擴充。

3、用

service install 安裝

service start啟動

service stop停止

service debug調試

service remove刪除

service.py

---代碼開始

#coding:utf-8

import win32serviceutil

import win32service

import win32event

import win32evtlogutil

import time

class service(win32serviceutil.ServiceFramework):

_svc_name_ = "test_python"

_svc_display_name_ = "test_python"

def __init__(self, args):

win32serviceutil.ServiceFramework.__init__(self, args)

self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)

print '服務開始'

def SvcDoRun(self):

import servicemanager

#------------------------------------------------------

# Make entry in the event log that this service started

#------------------------------------------------------

servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,servicemanager.PYS_SERVICE_STARTED,(self._svc_name_, ''))

#-------------------------------------------------------------

# Set an amount of time to wait (in milliseconds) between runs

#-------------------------------------------------------------

self.timeout=100

while 1:

#-------------------------------------------------------

# Wait for service stop signal, if I timeout, loop again

#-------------------------------------------------------

rc=win32event.WaitForSingleObject(self.hWaitStop,self.timeout)

#

# Check to see if self.hWaitStop happened

#

if rc == win32event.WAIT_OBJECT_0:

#

# Stop signal encountered

#

break

else:

#

# Put your code here

#

#

f=open('c:\\temp\\time.txt','w',0)

f.write(time.ctime(time.time()))

f.close()

print '服務運行中'

time.sleep(1)

#

# Only return from SvcDoRun when you wish to stop

#

return

def SvcStop(self):

#---------------------------------------------------------------------

# Before we do anything, tell SCM we are starting the stop process.

#---------------------------------------------------------------------

self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)

#---------------------------------------------------------------------

# And set my event

#---------------------------------------------------------------------

win32event.SetEvent(self.hWaitStop)

print '服務結束'

return

if __name__=='__main__':

win32serviceutil.HandleCommandLine(service)

---代碼結束

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容