【问题标题】:Creating a python win32 service创建 python win32 服务
【发布时间】:2010-09-20 18:26:57
【问题描述】:

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

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

我不明白的是初始化过程,因为守护进程从不直接由 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__)

【问题讨论】:

  • 我不确定我是否理解这个问题。你能给我们举个例子说明你想做什么上面的代码不允许吗?

标签: python winapi pywin32


【解决方案1】:

我只是创建了一个简单的“操作方法”,其中程序在一个模块中,而服务在另一个地方,它使用 py2exe 创建 win32 服务,我相信这是你能为你的用户做的最好的'不想弄乱 python 解释器或其他依赖项。

你可以在这里查看我的教程:Create win32 services using Python and py2exe

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-16
      • 1970-01-01
      • 2021-11-25
      相关资源
      最近更新 更多