time.sleep(self.wait_time)
if win32service.QueryServiceStatus(self.handle)[1] == win32service.SERVICE_STOPPED:
return '停止服务%s成功'.encode('gbk') % self.name
else:
return '停止服务%s失败'.encode('gbk') % self.name
def restart(self):
"""重启服务"""
if not self.is_stop():
self.stop()
self.start()
return win32service.QueryServiceStatus(self.handle)
def status(self):
"""获取运行的状态"""
try:
status_info = win32service.QueryServiceStatus(self.handle)
status = status_info[1]
if status == win32service.SERVICE_STOPPED:
return "STOPPED"
elif status == win32service.SERVICE_START_PENDING:
return "STARTING"
elif status == win32service.SERVICE_STOP_PENDING:
return "STOPPING"
elif status == win32service.SERVICE_RUNNING:
return "RUNNING"
except Exception, e:
self.log(e)
def close(self):
"""释放资源"""
try:
if self.scm:
win32service.CloseServiceHandle(self.handle)
win32service.CloseServiceHandle(self.scm)
except Exception, e:
self.log(e)
def is_exists(self):
"""windows服务是否已安装"""
statuses = win32service.EnumServicesStatus(self.scm, win32service.SERVICE_WIN32, win32service.SERVICE_STATE_ALL)
for (short_name, desc, status) in statuses:
if short_name == self.name:
return True
return False
def log(self, exception):
print(exception)
if __name__=='__main__':
app= ServiceManager('PythonService')
msg= app.is_exists() # 判断是否安装 (以下操作必须先判断服务是否存在)
#msg= app.is_stop() # 判断服务是否停止
#msg= app.status() # 查看服务的状态
#msg= app.start() # 开启服务
#msg= app.stop() # 暂停服务 (服务开启才能停止,else error)
#msg= app.restart() # 重启服务
print(msg)