【问题标题】:Recommended method to pool messages in a open file loop for python在 python 的打开文件循环中汇集消息的推荐方法
【发布时间】:2016-04-13 00:47:45
【问题描述】:

我正在编写一个日志监控 python 脚本。当找到带有文本“断开连接”的条目时,它会发送消息。该脚本会读取日志,直到遇到“日志文件结束”消息。在当前状态下,它会在遇到消息时发送消息。这不是最佳的,我需要在发送收集的条目之前将它们汇集 5 分钟。我不确定这样做的最佳方法是什么。这是我正在尝试做的简化版本。到目前为止,我已经尝试了 time.sleep 和精心设计的增量计数器,但无济于事。

# Open log
f = open(log, 'r')

# Start while loop and read line
while(1):

    # Check for Disconnected 
    if line.find("disconnected") != -1:

    ltime = time.time()
    print ("Disconnected Found in Log at " + ltime)

    # Check for end of log file
    if line.find("End of file") != -1:

    # End script
    break

【问题讨论】:

标签: python file logging time pool


【解决方案1】:

这对你有用吗?

  1. 将当前时间保存在变量中,并在 while 循环之前创建一个空列表。
  2. 每次发现“断开连接”时,将消息附加到列表中。
  3. 在 while 循环的每次迭代中,您将当前时间与您保存的时间戳(在第 1 步中)进行比较 - 如果超过 5 分钟(300 秒),您将遍历列表并发送所有消息。李>
  4. 清空列表并将当前时间保存在步骤 1 中的变量中。

这有意义吗?如果需要,我可以进一步详细说明。

【讨论】:

  • 这与我最终所做的非常接近。
【解决方案2】:

这就是我最终要做的。

# Disconnects that have already been recorded
rec_disconnects = []

# Disconnects to msg
send_disconnects = []

# Start while loop
while(1):

    # Wait 5 minutes
    time.sleep(300)

    # If list isn't empty
    if send_disconnects:

        # Join all the disconnects from the send list
        msg = '\n'.join(send_disconnects)

        # print the disconnects
        print (msg)

        # Clear the list
        send_disconnects = []

    # Open the log file and read the lines
    with open(log) as log:      
        for line in log:

            # If disconnect is found log it
            if line.find("disconnected") != -1:

            ltime = time.time()

            disconnect = ("Disconnected Found in Log at " + ltime)

            # Check if disconnect is already in the list if not add it
            # to the running list and the msg list      
            if (disconnect not in rec_disconnects):
                    rec_disconnects.append(disconnect)
                    send_disconnects.append(disconnect

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-04-20
    • 2017-01-04
    • 2023-01-19
    • 2021-05-02
    • 2014-06-08
    • 1970-01-01
    • 2015-10-04
    相关资源
    最近更新 更多