使用e4c5的答案,我得到了这段代码,该代码还解决了
readline()每秒调用多次的问题。
在第一次调用期间,它会跳到文件末尾并等待修改。移动文件后,它将重新打开文件并读取全部内容,然后开始等待。
import osimport timeimport tracebackimport threadingimport inotify.adapterslogfile = b'/var/log/auth.log'#logfile = b'logfile.log'##################################################################def process(line, history=False): if history: print '=', line.strip('n') else: print '>', line.strip('n')##################################################################from_beginning = Falsenotifier = inotify.adapters.Inotify()while True: try: #------------------------- check if not os.path.exists(logfile): print 'logfile does not exist' time.sleep(1) continue print 'opening and starting to watch', logfile #------------------------- open file = open(logfile, 'r') if from_beginning: for line in file.readlines(): process(line, history=True) else: file.seek(0,2) from_beginning = True #------------------------- watch notifier.add_watch(logfile) try: for event in notifier.event_gen(): if event is not None: (header, type_names, watch_path, filename) = event if set(type_names) & set(['IN_MOVE_SELF']): # moved print 'logfile moved' notifier.remove_watch(logfile) file.close() time.sleep(1) break elif set(type_names) & set(['IN_MODIFY']): # modified for line in file.readlines(): process(line, history=False) except (KeyboardInterrupt, SystemExit): raise except: notifier.remove_watch(logfile) file.close() time.sleep(1) #------------------------- except (KeyboardInterrupt, SystemExit): break except inotify.calls.InotifyError: time.sleep(1) except IOError: time.sleep(1) except: traceback.print_exc() time.sleep(1)##################################################################


