创建 python win32 服务 [英] Creating a python win32 service

查看:54
本文介绍了创建 python win32 服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在尝试使用 pywin32 创建一个 win32 服务.我的主要参考点是本教程:

I am currently trying to create a win32 service using pywin32. My main point of reference has been this tutorial:

http://code.activestate.com/recipes/551780/

我不明白的是初始化过程,因为守护进程从来没有直接由 Daemon() 初始化,而是根据我的理解,它是由以下初始化的:

What i don't understand is the initialization process, since the Daemon is never initialized directly by Daemon(), instead from my understanding its initialized by the following:

mydaemon = Daemon
__svc_regClass__(mydaemon, "foo", "foo display", "foo description")
__svc_install__(mydaemon)

其中 svc_install 处理初始化,通过调用 Daemon.init() 并向其传递一些参数.

Where svc_install, handles the initalization, by calling Daemon.init() and passing some arguments to it.

但是如何在不初始化服务的情况下初始化守护进程对象?在我初始化服务之前,我想做一些事情.有人有什么想法吗?

But how can i initialize the daemon object, without initalizing the service? I want to do a few things, before i init the service. Does anyone have any ideas?

class Daemon(win32serviceutil.ServiceFramework):
    def __init__(self, args):
        win32serviceutil.ServiceFramework.__init__(self, args)
        self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)

    def SvcDoRun(self):
        self.run()

    def SvcStop(self):
        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
        win32event.SetEvent(self.hWaitStop)

    def start(self):
        pass

    def stop(self):
        self.SvcStop()

    def run(self):
        pass

def __svc_install__(cls):
    win32api.SetConsoleCtrlHandler(lambda x: True, True)
    try:
        win32serviceutil.InstallService(
            cls._svc_reg_class_,
            cls._svc_name_,
            cls._svc_display_name_,
            startType = win32service.SERVICE_AUTO_START
            )
        print "Installed"
    except Exception, err:
        print str(err)

def __svc_regClass__(cls, name, display_name, description):

    #Bind the values to the service name
    cls._svc_name_ = name
    cls._svc_display_name_ =  display_name
    cls._svc_description_ = description
    try:
        module_path = sys.modules[cls.__module__].__file__
    except AttributeError:
        from sys import executable
        module_path = executable
    module_file = os.path.splitext(os.path.abspath(module_path))[0]
    cls._svc_reg_class_ = '%s.%s' % (module_file, cls.__name__)

推荐答案

这些API我没用过,但是翻了一下代码,貌似传入的类是用来在注册表中注册类名的,所以你不能自己做任何初始化.但是有一个名为 GetServiceCustomOption 的方法可能会有所帮助:

I've never used these APIs, but digging through the code, it looks like the class passed in is used to register the name of the class in the registry, so you can't do any initialization of your own. But there's a method called GetServiceCustomOption that may help:

http://mail.python.org/pipermail/python-win32/2006-April/004518.html

这篇关于创建 python win32 服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆