需要在python程序的while循环中进行改进 [英] Need improvement in the while loop in python program

查看:42
本文介绍了需要在python程序的while循环中进行改进的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在此论坛的帮助下(@COLDSPEED ...非常感谢),我已经能够读取目录中创建的最新文件.该程序正在寻找文件创建时间的最大时间戳.但我需要两个改进

with some help of from this forum (@COLDSPEED...Thanks a lot )I have been able to read the latest file created in the directory. The program is looking for the max timestamp of file creation time. But I need two improvement

1.但是,如果在同一时间戳中创建2个文件怎么办?2.当while循环检查最新文件时,我想跳过已经读取的文件(以防没有新文件到达).

1.But what if 2 files are created in the same time stamp? 2.I want to skip the file which is already read(in case no new file arrives) when the while loop is checking for the latest file.

import os
import time

def detect_suspects(file_path, word_list):
    with open(file_path) as LogFile:
        Summary = {word: [] for word in word_list}
        failure = ':'
        for num, line in enumerate(LogFile, start=1):
            for word in word_list:
                if word in line:
                    failure += '<li>' + line + '</li>'
    return failure

while True:
 
 files = os.listdir('.')
 latest_file = max(files, key=os.path.getmtime)
 Error_Suspects = ['Error', 'ERROR', 'Failed', 'Failure']
 print(latest_file)   
 Result = detect_suspects(latest_file, Error_Suspects)
 print (Result)
 time.sleep(5)    
 




 

推荐答案

要解决您的第一个问题,当2个文件的时间戳完全相同时,max会选择一个并返回.返回与最大修改时间相关联的列表中出现的第一个字符串.

To address your first question, when 2 files have the exact same timestamp, max picks one and returns it. The first string that appears in the list that is associated with the max modification time is returned.

对于第二个问题,可以通过跟踪先前的文件和先前的修改时间来对现有代码进行少量添加.

For your second question, you could make a small addition to your existing code by keeping track of the previous file and previous modification time.

Error_Suspects = ['Error', 'ERROR', 'Failed', 'Failure']

prev_file = None
prev_mtime = None

while True:     
    files = os.listdir('.')
    latest_file = max(files, key=os.path.getmtime)

    if latest_file != prev_file or (latest_file == prev_file and prev_mtime != os.path.getmtime(latest_file):
        Result = detect_suspects(latest_file, Error_Suspects)     
        prev_file = latest_file
        prev_mtime = os.path.getmtime(latest_file)

    time.sleep(5) 

在此代码中, if 条件仅在以下情况下执行您的代码:1)您的新文件与旧文件不同,或2)您的旧文件与新文件相同,但已被修改自上次以来.

In this code, the if condition will execute your code only if 1) your new file is different from your old file, or 2) your old and new file is the same but it was modified since the last time.

这篇关于需要在python程序的while循环中进行改进的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆