Posted on 2007-12-25 15:12
江邊之鳥 閱讀(3876)
評(píng)論(0) 編輯 收藏 引用 所屬分類:
python
如果我們想讓系統(tǒng)啟動(dòng)的時(shí)候就執(zhí)行某個(gè)程序,windows系統(tǒng)和unix系統(tǒng)是不一樣的,對(duì)于unix只需要將要執(zhí)行的命令放到
rc.local中,系統(tǒng)重新啟動(dòng)的時(shí)候就可以加載了。windows就麻煩多了,如果你將程序放到啟動(dòng)組中,只有輸入了密碼后,程序才被執(zhí)行,如果想在
系統(tǒng)一啟動(dòng)的時(shí)候就執(zhí)行程序,必須使用nt服務(wù)。
python下如何使用nt服務(wù),其實(shí)很簡(jiǎn)單。
下載python的win32支持。我使用的是:pywin32-202.win32-py2.3.exe安裝好后就可以來寫我們的服務(wù)了。
我們先來建立一個(gè)空的服務(wù),建立test1.py這個(gè)文件,并寫入如下代碼:
# -*- coding: cp936 -*-
import win32serviceutil
import win32service
import win32event
class test1(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)
def SvcStop(self):
# 先告訴SCM停止這個(gè)過程
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
# 設(shè)置事件
win32event.SetEvent(self.hWaitStop)
def SvcDoRun(self):
# 等待服務(wù)被停止
win32event.WaitForSingleObject(self.hWaitStop, win32event.INFINITE)
if __name__=='__main__':
win32serviceutil.HandleCommandLine(test1)
這里注意,如果你需要更改文件名,比如將win32serviceutil.HandleCommandLine(test1)中的test1更改為你的文件名,同時(shí)class也需要和你的文件名一致,否則會(huì)出現(xiàn)服務(wù)不能啟動(dòng)的問題。
在命令窗口執(zhí)行,test1.py可以看到幫助提示
C:\>test1.py
Usage: 'test1.py [options] install|update|remove|start [...]|stop|restart [...]|
debug [...]'
Options for 'install' and 'update' commands only:
--username domain\username : The Username the service is to run under
--password password : The password for the username
--startup [manual|auto|disabled] : How the service starts, default = manual
--interactive : Allow the service to interact with the desktop.
C:\>
安裝我們的服務(wù)
[code:1:05b7353f1c]C:\>test1.py install
Installing service test_python to Python class C:\test1.test1
Service installed
C:\>
我們就可以用命令或者在控制面板-》管理工具-》服務(wù)中管理我們的服務(wù)了。在服務(wù)里面可以看到test_python這個(gè)服務(wù),雖然這個(gè)服務(wù)什么都不做,但能啟動(dòng)和停止他。