pywin32 - 杀死一个进程

时间:2016-08-31 16:08:26

标签: python popen pywin32 taskkill

我正在尝试使用pywin32模块创建一个Windows服务,可以在将特定事件写入日志时终止并重新启动进程。

我可以创建,声明和运行服务,但是尽管它在事件上启动(即日志中的超时),但服务并没有正确地终止任务。

import win32service
import win32serviceutil
import win32api
import win32con
import win32event
import win32evtlogutil
from subprocess import Popen
import os, sys, string, time
import datetime


log_dir = "C:/Blablavla"
log_filename = "log"
error_strings = ("timeout", "FATAL", "error")
service_timeout = 600000
service_restart = 'batch.bat'
restart_required = False

# Make stderr and stdout will never been writen
sys.stdout = sys.stderr = open('nul', 'w')
class aservice(win32serviceutil.ServiceFramework):

   _svc_name_ = "webcomRestart"
   _svc_display_name_ = "restart webcom"
   _svc_description_ = "restart when ssh error occurs (timeout, fatal errors,...)"

   def __init__(self, args):
           win32serviceutil.ServiceFramework.__init__(self, args)
           self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)           

   def SvcStop(self):
           self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
           win32event.SetEvent(self.hWaitStop)                    

   def SvcDoRun(self):
      import servicemanager      
      servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,servicemanager.PYS_SERVICE_STARTED,(self._svc_name_, '')) 

      self.timeout = service_timeout
      while 1:
         restart_required = False
         # Wait for service stop signal, if I timeout, loop again
         rc = win32event.WaitForSingleObject(self.hWaitStop, self.timeout)
         # Check to see if self.hWaitStop happened
         if rc == win32event.WAIT_OBJECT_0:
            # Stop signal encountered
            servicemanager.LogInfoMsg("webComRestart - STOPPED")
            break
         else:
            # servicemanager.LogInfoMsg("aservice - is alive and well")

            os.chdir(log_dir)

            with open(log_filename, 'r') as f:
                for line in f.readlines():
                    if any(s in line for s in error_strings):
                         restart_required = True
            if restart_required:
                 #execute webcom reload
                 #note: I can see that in the event observer
                 servicemanager.LogInfoMsg("WebCom Restart attempt")
                 #Next command has no effect, that's my problem
                 p = Popen('taskkill /IM BaiWebCom.exe', shell=False)
                 stdout, stderr = p.communicate()
                 # Write trace of service action
                 with open("trace.txt", "a") as tracefile:
                     tracefile.write(str(datetime.datetime.now())+'\n')
                 # erase log file
                 with open(log_filename, 'w'): pass


def ctrlHandler(ctrlType):
   return True

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

有人可以帮忙吗?

0 个答案:

没有答案