开源之路

忆往昔, 项羽不过江. 江东好风光! 今振臂一呼,率甲三千, 试问天!
posts - 86, comments - 55, trackbacks - 0, articles - 0
  C++博客 :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

python 脚本作为Windows服务启动

Posted on 2007-12-25 15:12 江边之鸟 阅读(3848) 评论(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这个服务,虽然这个服务什么都不做,但能启动和停止他。

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理