简体   繁体   中英

Pywin32 Windows service reading directory

I try to create a window service to monitor a directory.

Here's my code, I can't make to stop the ReadDirectoryChange using windows service but rather after i stop then change the path i monitor it will implement the stop.

How can i achieve the following when i stop the windows service also the Read Directory Change also stop from monitoring?

import os
import sys
import win32serviceutil
import win32service
import win32event
import win32file,win32api
import win32con
import socket, string
import time
import logging
import ConfigParser

logging.basicConfig(
    filename = 'c:\\Temp\\Log.log',
    level = logging.INFO,
    filemode='w',
    format='%(asctime)s %(message)s',
    datefmt='%m/%d/%Y %I:%M:%S %p'

)

Config = ConfigParser.ConfigParser()
Config.read("c:\\Temp\\KerrSMS.ini")

path_to_watch = "C:\Users\Admin\Documents\PRAII Email Notification\PRAII Email Notification\path"

ACTIONS = {
  1 : "Created",
  2 : "Deleted",
  3 : "Updated",
  4 : "Renamed from something",
  5 : "Renamed to something"
}
FILE_LIST_DIRECTORY = 0x0001

hDir = win32file.CreateFile (
  path_to_watch,
  FILE_LIST_DIRECTORY,
  win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE | win32con.FILE_SHARE_DELETE,
  None,
  win32con.OPEN_EXISTING,
  win32con.FILE_FLAG_BACKUP_SEMANTICS,
  None
)

def ConfigSectionMap(section):
    dict1 = {}
    options = Config.options(section)
    for option in options:
        try:
            dict1[option] = Config.get(section, option)
            if dict1[option] == -1:
                DebugPrint("skip: %s" % option)
        except:
            print("exception on %s!" % option)
            dict1[option] = None
    return dict1


class PraClient (win32serviceutil.ServiceFramework):
    _svc_name_ = "Pra-Service-v1.0.2"
    _svc_display_name_ = "PraClient-Service-v1.0.2"
    _svc_description_ = 'Pra Client'

    def __init__(self,args):
        win32serviceutil.ServiceFramework.__init__(self,args)
        self.stop_event = win32event.CreateEvent(None,0,0,None)
##        socket.setdefaulttimeout(60)
        self.stop_requested = False

    def SvcStop(self):
        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
        win32event.SetEvent(self.stop_event)
        #logging.info('Stopping service ...')
        self.stop_requested = True

    def SvcDoRun(self):
        import servicemanager
##        servicemanager.LogMsg(
##            servicemanager.EVENTLOG_INFORMATION_TYPE,
##            servicemanager.PYS_SERVICE_STARTED,
##            (self._svc_name_,'')
##        )
        rc = None
        while rc != win32event.WAIT_OBJECT_0:
            self.main()
            # block for 5 seconds and listen for a stop event
            rc = win32event.WaitForSingleObject(self.stop_event, 5000)
        logging.info('Stopping service ...')


        #self.main()

    def main(self):
##        rc = None
##        while rc != win32event.WAIT_OBJECT_0:
        try:
            """
            This is where the magic happens.
            """
            results = win32file.ReadDirectoryChangesW (
              hDir,
              1024,
              True,
              win32con.FILE_NOTIFY_CHANGE_FILE_NAME |
               win32con.FILE_NOTIFY_CHANGE_DIR_NAME |
               #win32con.FILE_NOTIFY_CHANGE_ATTRIBUTES |
               win32con.FILE_NOTIFY_CHANGE_SIZE |
               # win32con.FILE_NOTIFY_CHANGE_LAST_WRITE |
               win32con.FILE_NOTIFY_CHANGE_SECURITY,
              None,
              None
            )
            for action, file in results:
              full_filename = os.path.join (path_to_watch, file)
              #print full_filename, ACTIONS.get (action, "Unknown"), "By " + win32api.GetUserName()
              msglog = full_filename + " " + ACTIONS.get (action, "Unknown"), " By " + win32api.GetUserName()
              #praLogger.appendLog(msglog)
              logging.info(msglog[0]+msglog[1])
              s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
              s.connect(('localhost', 9999))
              s.sendall(msglog[0]+msglog[1])
              #s.sendall(full_filename + ACTIONS.get (action, "Unknown") + win32api.GetUserName())
              #thread = threading.Thread(target=notify,args=(msglog,))
              #thread.start()
              #thread.join()

            #s.sendall("hello world" + "\n")
            #time.sleep(2)
        except socket.error as e:
            logging.info("socket error {} reconnecting".format(e))


##        while 1:
##            rc = win32event.WaitForSingleObject(self.stop_event, 3000)
##            if rc == win32event.WAIT_OBJECT_0:
##                # Stop signal encountered
##                logging.info('Stopping service ...')
##                break
##            else:
##                try:
##                    """
##                    This is where the magic happens.
##                    """
##                    results = win32file.ReadDirectoryChangesW (
##                      hDir,
##                      1024,
##                      True,
##                      win32con.FILE_NOTIFY_CHANGE_FILE_NAME |
##                       win32con.FILE_NOTIFY_CHANGE_DIR_NAME |
##                       #win32con.FILE_NOTIFY_CHANGE_ATTRIBUTES |
##                       win32con.FILE_NOTIFY_CHANGE_SIZE |
##                       # win32con.FILE_NOTIFY_CHANGE_LAST_WRITE |
##                       win32con.FILE_NOTIFY_CHANGE_SECURITY,
##                      None,
##                      None
##                    )
##                    for action, file in results:
##                      full_filename = os.path.join (path_to_watch, file)
##                      #print full_filename, ACTIONS.get (action, "Unknown"), "By " + win32api.GetUserName()
##                      msglog = full_filename + " " + ACTIONS.get (action, "Unknown"), " By " + win32api.GetUserName()
##                      #praLogger.appendLog(msglog)
##                      logging.info(msglog[0]+msglog[1])
##                      s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
##                      s.connect(('localhost', 9999))
##                      s.sendall(msglog[0]+msglog[1])
##                      #s.sendall(full_filename + ACTIONS.get (action, "Unknown") + win32api.GetUserName())
##                      #thread = threading.Thread(target=notify,args=(msglog,))
##                      #thread.start()
##                      #thread.join()
##
##                    #s.sendall("hello world" + "\n")
##                    #time.sleep(2)
##                except socket.error as e:
##                    logging.info("socket error {} reconnecting".format(e))
##                    #time.sleep(5)
##                #else:
##                    #break


if __name__ == '__main__':
    win32serviceutil.HandleCommandLine(PraClient)

我终于通过在观看的补丁内创建临时文件来弄清楚了。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM