我试图使用python看门狗库来观看指定的文件夹&用于创建新文件夹的子文件夹(它们具有特殊性:名称的结尾是" .D")。
麻烦的是,为了观看指定的文件夹&子文件夹,我在创建recursive = True
时设置了Observer
参数。但它没有看到同时发生的文件夹.D创作。如果我放置recursive = False
参数,它只会监视指定的文件夹(不是子文件夹),但能够看到同时创建Folders.D。
源代码:
import os
import sys
import time
import logging
import configparser
from watchdog.observers import Observer
import watchdog.events as we
from pathtools.path import absolute_path, parent_dir_path
def LectureINI(path):
data = path.split('\\')
data = data[-1]
print(data)
file_runstart = path + '\\runstart.txt'
tps1 = time.clock()
while os.path.isfile(file_runstart) == False:
time.sleep(1)
tps2 = time.clock()
print(tps2-tps1)
if (tps2-tps1) > 15:
break
try:
file_runstart = open(file_runstart, 'r')
lines = file_runstart.readlines()
ilines = iter(lines)
for i in ilines:
if "Sample Name" in i:
sample = i.split(' = ')
sample = sample[-1]
break
except:
sample = '<Sample Name non récupérable>'
file_ini = path + '\\PRE_POST.INI'
while os.path.isfile(file_ini) == False:
time.sleep(1)
cfg.read(file_ini)
try:
date = cfg['POSTRUN']['Date']
except:
date = '<Date non récupérable>'
try:
instr = cfg['POSTRUN']['Instrument Name']
except:
instr = '<Nom instrument non récupérable>'
infos = date + '\t' + instr + '\t' + data + '\t' + sample
return infos
class MonHandler(we.FileSystemEventHandler):
def on_created(self, event):
my_path = event.src_path
if my_path[-2:]== ".D" and not "$" in my_path:
print('Détection DATA')
fileinfo = LectureINI(my_path)
logging.info("%s\t%s", my_path, fileinfo)
cfg = configparser.ConfigParser()
cfg.read('C:\Windows\win.ini')
read_path = cfg['WatchData']['Path']
BASEDIR = read_path[:-1]
if read_path == None:
BASEDIR == 'C:\\'
logging.basicConfig(filename='WatchData.log', level=logging.INFO,
format='%(asctime)s\t%(message)s',
datefmt='%Y-%m-%d\t%H:%M:%S')
event_handler = MonHandler()
observer = Observer()
observer.schedule(event_handler, BASEDIR, recursive = True)
observer.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
#CRTL+C to stop
observer.stop()
observer.join()
如果有人知道原因,那会很有帮助!