错误:服务实例没有属性'SvcDoRun

0 投票
1 回答
750 浏览
提问于 2025-04-17 21:50

在一台运行Windows 7 64位系统的机器上,我使用的是Python 2.7。我按照这个链接的步骤操作过:http://essiene.blogspot.in/2005/04/python-windows-services.html,但是在查看事件查看器的Windows日志时,出现了错误,内容是:追踪记录(最近的调用在最后):文件 "C:\Python27\lib\site-packages\win32\lib\win32serviceutil.py",第835行,在 SvcRun 中,self.SvcDoRun(),属性错误:Myservice 实例没有属性 'SvcDoRun'

以下是代码片段:

import win32service
import win32serviceutil
import win32api
import win32con
class Myservice(win32serviceutil.ServiceFramework):
    _svc_name_ = "Myservice"
    _svc_display_name_ = "Myservice"

def __init__(self,args):
    win32serviceutil.ServiceFramework.__init__(self,args)
    self.isAlive = True

def SvcDoRun(self):
    while self.isAlive:
        if len(List)!=0:
            for i in range(0,len(List)):
                t = ThreadClass(NameList[i],name)
                t.start()

def SvcStop(self):
    import servicemanager

    self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
    self.isAlive = False

def ctrlHandler(ctrlType):
    return True

if __name__ == '__main__':
    win32api.SetConsoleCtrlHandler(ctrlHandler, True)
    win32serviceutil.HandleCommandLine(Myservice)

1 个回答

1

我也遇到过同样的问题。你需要给函数定义加上缩进,不然它们就不算在 MyService 这个类里面。所以你的代码应该像这样:

import win32service
import win32serviceutil
import win32api
import win32con
class Myservice(win32serviceutil.ServiceFramework):
    _svc_name_ = "Myservice"
    _svc_display_name_ = "Myservice"

    def __init__(self,args):
        win32serviceutil.ServiceFramework.__init__(self,args)
        self.isAlive = True

    def SvcDoRun(self):
        while self.isAlive:
            if len(List)!=0:
                for i in range(0,len(List)):
                    t = ThreadClass(NameList[i],name)
                    t.start()

    def SvcStop(self):
        import servicemanager

        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
        self.isAlive = False

    def ctrlHandler(ctrlType):
        return True

if __name__ == '__main__':
    win32api.SetConsoleCtrlHandler(ctrlHandler, True)
    win32serviceutil.HandleCommandLine(Myservice)

撰写回答