Pywin32 Windows服务读取目录

时间:2015-12-05 09:51:43

标签: python windows file python-2.7 text

我尝试创建一个窗口服务来监视目录。

这是我的代码,我无法使用Windows服务停止ReadDirectoryChange 但是在我停下来然后改变我监控的路径它将实现停止。

当我停止Windows服务时,如何实现以下目标,读取目录更改也会停止监控?

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)

1 个答案:

答案 0 :(得分:0)

我终于通过在我看过的补丁中创建临时文件来弄明白了。