遇到与它https://yq.aliyun.com/ask/60529/相同的问题
本来已经在它的问题下面回答了,但答复没有显示,在此记录一下。同时也借用它的图片文字:

'''python

import win32service
import win32serviceutil
import win32event

import os, time

import winerror

class service(win32serviceutil.ServiceFramework):

_svc_name_ = 'service' _svc_display_name_ = 'service' _svc_description_ = 'service' def __init__(self, args):
    win32serviceutil.ServiceFramework.__init__(self, args) self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
    self.isAlive = True

def SvcDoRun(self): while self.isAlive: print('do something') time.sleep(2) self.ReportServiceStatus(win32service.SERVICE_RUNNING) win32event.WaitForSingleObject(self.hWaitStop, win32event.INFINITE) def SvcStop(self):
    self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) win32event.SetEvent(self.hWaitStop) self.isAlive = False 

if name == '__main__':

import sys import servicemanager if len(sys.argv) == 1: try:
        evtsrc_dll = os.path.abspath(servicemanager.__file__)
        servicemanager.PrepareToHostSingle(service)
        servicemanager.Initialize('service', evtsrc_dll)
        servicemanager.StartServiceCtrlDispatcher()
    except win32service.error as details: import winerror if details == winerror.ERROR_FAILED_SERVICE_CONTROLLER_CONNECT:
            win32serviceutil.usage() else:
    win32serviceutil.HandleCommandLine(service) 

'''
服务能安装,但是启动就显示如题的错误,代码我也debug过,能输入run里面那句话。然后我查看windows事件查看器,有两条错误启动的记录。


解决参考:https://stackoverflow.com/questions/8943371/cant-start-windows-service-written-in-python-win32serviceutil
What you need to do is to add the Python27 to SYSTEM PATH, and not to USER PATH, since as a default the python service will get installed as a 'LocalSystem' and so when it attempts to start it uses the SYSTEM PATH variable - that's why you can run it from the command prompt, your USER PATH is right.

把python path环境变量由user path 改为system path即可


09-13 02:36