创建Python Win32服务

11 投票
2 回答
30993 浏览
提问于 2025-04-11 09:34

我现在正在尝试使用pywin32创建一个win32服务。我主要参考了这个教程:

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

我不太明白的是初始化过程,因为Daemon并不是直接通过Daemon()来初始化的。根据我的理解,它是通过以下方式初始化的:

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

这里的svc_install负责初始化,它通过调用Daemon.init()并传递一些参数来完成。

但是我怎么能在不初始化服务的情况下初始化守护进程对象呢?我想在初始化服务之前做一些事情。有没有人有什么想法?

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__)

2 个回答

10

我刚刚创建了一个简单的“如何做”的教程,里面的程序放在一个模块里,而服务放在另一个地方。这个教程使用了py2exe来创建win32服务,我觉得这是给那些不想碰Python解释器或其他依赖项的用户提供的最佳解决方案。

你可以在这里查看我的教程:使用Python和py2exe创建win32服务

6

我以前从来没有用过这些API,不过我翻看了一下代码,发现传入的类是用来在注册表中登记类名的,所以你不能自己进行任何初始化。不过,有一个叫做GetServiceCustomOption的方法可能会对你有帮助:

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

撰写回答