3

我正在使用 windows 7 64 位 python 2.7 我正在打开文件,并监视文件更改,然后等待打开的文件关闭。这适用于简单的记事本文件打开器。由于记事本在新的进程 ID 中打开每个文件,而记事本++ 在单个记事本++ 进程 ID 中打开不同的文件。

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

class myThread (threading.Thread):
    def __init__(self, threadID, fileName, directory, origin):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.fileName = fileName
        self.daemon = True
        self.dir = directory
        self.originalFile = origin
    def run(self):
        startMonitor(self.fileName, self.dir, self.originalFile)

def startMonitor(fileMonitoring,dirPath,originalFile):
    hDir = win32file.CreateFile (
      dirPath,
      FILE_LIST_DIRECTORY,
      win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE,
      None,
      win32con.OPEN_EXISTING,
      win32con.FILE_FLAG_BACKUP_SEMANTICS,
      None
    )
    readFlags = 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
    # Wait for new data and call ProcessNewData for each new chunk that's written
    while 1:
        # Wait for a change to occur
        results = win32file.ReadDirectoryChangesW (
                                                   hDir,
                                                   1024,
                                                   False,
                                                   readFlags,
                                                   None
                                                   )
        # For each change, check to see if it's updating the file we're interested in
        for action, file_M in results:
            full_filename = os.path.join (dirPath, file_M)
            #print file, ACTIONS.get (action, "Unknown")
            if len(full_filename) == len(fileMonitoring) and action == 3:
                #copy to main file
                if os.path.exists(originalFile):
                        encrypt_file(key,fileMonitoring,originalFile,iv)





thread1 = myThread(1, FileName, tempLocation,selectedFileName)
thread1.start();
startupinfo = None
if os.name == 'nt':
    startupinfo = subprocess.STARTUPINFO()
    startupinfo.dwFlags |= subprocess._subprocess.STARTF_USESHOWWINDOW
    **ss=subprocess.Popen(FileName,shell=True)**
    ss.communicate()
    os.remove(FileName)

所以上面的代码,当我关闭记事本++(这将关闭所有不需要的不同打开的文件)而不是只关闭打开的文件类型时,它可以工作。 当我用写字板/记事本打开文件时,它的每个进程都是用一个文件创建的。而使用 notepad++,只有一个 notepad++ 进程承载所有不同的文件类型。那么,如何在每次打开新文件时为不同类型的文件打开器(如 notepad++、msoffice、openoffice)调用新进程 ID在上述情况下ss.communicate()不是阻塞调用

4

0 回答 0