最近在玩的py2exe不但能夠將.py檔轉成.exe執行檔還可以製作出Windows service。以下是參考Essien Ita Essien's Blog修改而來的.py檔,名為HelloService.py(檔名很重要!):
import win32serviceutil
import win32service
import time
class HelloService(win32serviceutil.ServiceFramework):
_svc_name_ = 'HelloService'
_svc_display_name_ = 'HelloService does nothing'
def __init__(self, args):
win32serviceutil.ServiceFramework.__init__(self, args)
self.isAlive = True
self.log = open('c:\\\\log.txt', 'w')
def SvcDoRun(self):
import servicemanager
log = self.log
while self.isAlive == 1:
servicemanager.LogInfoMsg("HelloService is alive and well")
log.write("HelloService is alive and well\n")
time.sleep(10)
servicemanager.LogInfoMsg("HelloService stopped")
log.write("HelloService stopped\n")
log.close()
def SvcStop(self):
import servicemanager
log = self.log
servicemanager.LogInfoMsg("HelloService received stop signal")
log.write("HelloService received stop signal\n")
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
self.isAlive = False
if __name__ == '__main__':
win32serviceutil.HandleCommandLine(HelloService)
HelloService.py中的每個member function name,以及_svc_name_ & _svc_display_name_都不能改(為win32serviceutil.ServiceFramework中的需要被override的function),這支service做的事情就是在Windows事件紀錄簿與C磁碟的log.txt中輸入文字訊息而已。
接下來要寫的是setup.py:
from distutils.core import setup
##import sys
import win32service
import win32serviceutil
import time
import py2exe
##sys.argv.append('py2exe')
setup(
version="1.00.00",
description="hello service",
name="hello service",
options={'py2exe': {'bundle_files': 2,
'optimize': 2,
'compressed': 1}},
service=["HelloService"],
zipfile=None
)
與之前介紹的setup.py不同之處為原本寫windows/console的地方改成service。此外原本寫entry point的檔案名之處改成寫module name(也就是檔名去掉附檔名-->HelloService),但是又有tutorial說service後面要寫的是_svc_name_的內容,為了保險起見我們幫檔名(去掉附檔名)與_svc_name_取相同的名字。接下來執行python setup.py py2exe便可在dist目錄中取得.exe格式的windows service執行檔了。
將service安裝為自動啟動:
HelloService.exe -auto -install
(也可以使用windows內建sc指令)
啟動service:
sc start HelloService
停止service:
sc stop HelloService
移除service:
HelloService.exe -remove
(也可以使用windows內建sc指令)
No comments:
Post a Comment