【问题标题】:Pywin32 Windows service reading directoryPywin32 Windows服务读取目录
【发布时间】:2015-12-05 09:51:42
【问题描述】:

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

这是我的代码,我无法使用 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)

【问题讨论】:

    标签: python windows file python-2.7 text


    【解决方案1】:

    我终于通过在我看过的补丁中创建临时文件来解决这个问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-05-09
      • 2012-11-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-12
      • 1970-01-01
      相关资源
      最近更新 更多