Python停止循环,直到连续更改的日志文件中存在某些字符串

时间:2018-12-07 09:16:20

标签: python python-3.x

我想知道是否可以执行python标题中提到的以下操作。我设法编写了一个代码来检查文件是否存在,但是我被困在要读取不断变化的日志文件的步骤中,直到在其中找到某个字符串为止。目的是一旦在日志文件中找到某些字符串,就继续执行我的for循环:

这是我设法编写的代码:

list1=[20,40,60]
for i in list1:
    ##some code here
    while not os.path.exists("path.log"):
        time.sleep(1)

    if os.path.isfile("path.log"):
        while True:
             # with open ("path.log") as f:
                if 'string' in open("path.log").read()
                    break
                else 
                    time.sleep(1)
                    continue
    else:
        raise ValueError("%s isn't a file!" % file_path)

3 个答案:

答案 0 :(得分:0)

我已经使用了here的答案并对其进行了一些编辑。

此文件将紧随 tail -f 之类的文件,并在找到STOP字时停止:

import time
import re

def follow(thefile):
    thefile.seek(0,1)
    while True:
        line = thefile.readline()
        if not line:
            time.sleep(0.1)
            continue
        yield line

if __name__ == '__main__':
    regex = r'\bSTOP\b'
    logfile = open("file.log","r")
    loglines = follow(logfile)
    for line in loglines:
        check = re.search(regex,line)
        if check:
            print 'stop condition met'
            break

答案 1 :(得分:0)

由于您需要在Windows上监视特定文件的更改,因此可以选中this SO post来解决这种情况。

这篇文章中有一个链接to a valid example using Python's win32 API

import os

import win32file
import win32event
import win32con

path_to_watch = os.path.abspath (".")

#
# FindFirstChangeNotification sets up a handle for watching
#  file changes. The first parameter is the path to be
#  watched; the second is a boolean indicating whether the
#  directories underneath the one specified are to be watched;
#  the third is a list of flags as to what kind of changes to
#  watch for. We're just looking at file additions / deletions.
#
change_handle = win32file.FindFirstChangeNotification (
  path_to_watch,
  0,
  win32con.FILE_NOTIFY_CHANGE_FILE_NAME
)

#
# Loop forever, listing any file changes. The WaitFor... will
#  time out every half a second allowing for keyboard interrupts
#  to terminate the loop.
#
try:

  old_path_contents = dict ([(f, None) for f in os.listdir (path_to_watch)])
  while 1:
    result = win32event.WaitForSingleObject (change_handle, 500)

    #
    # If the WaitFor... returned because of a notification (as
    #  opposed to timing out or some error) then look for the
    #  changes in the directory contents.
    #
    if result == win32con.WAIT_OBJECT_0:
      new_path_contents = dict ([(f, None) for f in os.listdir (path_to_watch)])
      added = [f for f in new_path_contents if not f in old_path_contents]
      deleted = [f for f in old_path_contents if not f in new_path_contents]
      if added: print "Added: ", ", ".join (added)
      if deleted: print "Deleted: ", ", ".join (deleted)

      old_path_contents = new_path_contents
      win32file.FindNextChangeNotification (change_handle)

finally:
  win32file.FindCloseChangeNotification (change_handle)

或者,您可以检查名为Watchdog的python库,该库旨在在所有常见平台(Unix / Windows)上提供这种功能。

在两种情况下,其想法都是创建一个对文件系统上的文件更改做出反应的脚本。这使用操作系统特定的事件/中断来通知您的脚本您可能感兴趣的东西。这比主动轮询文件(每秒检查一个字符串)的开销要小。

答案 2 :(得分:0)

尝试

import os
import time

list1 = [20, 40, 60]

for i in list1:
    while not os.path.exists("path.log"):
        time.sleep(1)

    if os.path.isfile("path.log"):
        while True:
            if 'String' in open("path.log").read():
                break
            time.sleep(1)
    else:
        raise ValueError("%s isn't a file!" % file_path)