Posted on 2007-12-25 15:12
江邊之鳥 閱讀(3876)
評論(0) 編輯 收藏 引用 所屬分類:
python
如果我們想讓系統啟動的時候就執行某個程序,windows系統和unix系統是不一樣的,對于unix只需要將要執行的命令放到
rc.local中,系統重新啟動的時候就可以加載了。windows就麻煩多了,如果你將程序放到啟動組中,只有輸入了密碼后,程序才被執行,如果想在
系統一啟動的時候就執行程序,必須使用nt服務。
python下如何使用nt服務,其實很簡單。
下載python的win32支持。我使用的是:pywin32-202.win32-py2.3.exe安裝好后就可以來寫我們的服務了。
我們先來建立一個空的服務,建立test1.py這個文件,并寫入如下代碼:
# -*- 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停止這個過程
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
# 設置事件
win32event.SetEvent(self.hWaitStop)
def SvcDoRun(self):
# 等待服務被停止
win32event.WaitForSingleObject(self.hWaitStop, win32event.INFINITE)
if __name__=='__main__':
win32serviceutil.HandleCommandLine(test1)
這里注意,如果你需要更改文件名,比如將win32serviceutil.HandleCommandLine(test1)中的test1更改為你的文件名,同時class也需要和你的文件名一致,否則會出現服務不能啟動的問題。
在命令窗口執行,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:\>
安裝我們的服務
[code:1:05b7353f1c]C:\>test1.py install
Installing service test_python to Python class C:\test1.test1
Service installed
C:\>
我們就可以用命令或者在控制面板-》管理工具-》服務中管理我們的服務了。在服務里面可以看到test_python這個服務,雖然這個服務什么都不做,但能啟動和停止他。