使用python写nt服务

王朝other·作者佚名  2006-01-09
窄屏简体版  字體: |||超大  

使用python写nt服务

作者:梅劲松

如果我们想让系统启动的时候就执行某个程序,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:\>

安装我们的服务

C:\>test1.py install

Installing service test_python to Python class C:\test1.test1

Service installed

C:\>

我们就可以用命令或者在控制面板-》管理工具-》服务中管理我们的服务了。在服务里面可以看到test_python这个服务,虽然这个服务什么都不做,但能启动和停止他。

下面我们来写个复杂点的服务。

改天写,要下班了。

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航