【问题标题】:Python: How to write to a file and continuously monitor it's file size changes?Python:如何写入文件并持续监控文件大小的变化?
【发布时间】:2014-09-08 21:23:37
【问题描述】:

我有一个 python 脚本,它有一个名为produce_output(input) 的方法,可以在运行一个很难预测需要多长时间的长时间运行的进程后生成一个输出文件。有时进程会挂起(由于内存或输入错误)。

在同一个脚本中,我想创建一个方法has_output_changed(),它将监视输出文件的文件大小变化,如果文件大小超过5分钟没有变化,我们将终止方法produce_output()并退出脚本。

我将如何实施?

produce_output(input) 是一个将要运行的 Celery 任务。我希望任务能够自行了解它生成的输出文件大小,并在它意识到它没有做任何工作时自行终止,因为用于将输入转换为输出的进程挂起(即内存泄漏、输入错误、资源不足)。

【问题讨论】:

  • 这是您要求的另一种方法,但可能仍然适合您:让produce_output 任务在它开始运行时将其 pid 写入文件,然后在 Celery 中定期生成另一个任务来检查输出文件。如果它检测到问题,您可以kill -9它(因为它可能挂起并且没有响应其他其他信号)。
  • 我认为是的,这也可能是一个好方法。创建一个队列来存储输出文件,运行一个工作器,它会定期检查队列是否超过 5 分钟,如果文件大小没有改变,则终止它。

标签: python celery


【解决方案1】:

假设只有脚本正在写入文件,您可以简单地监控自上次向文件写入内容以来的时间:

import signal, time

# Set time limit to 5 minutes.
time_limit = 300

class TimeoutException(Exception): 
    pass

# Create signal countdown.
def signal_handler(signum, frame):
    raise TimeoutException("Idle for too long! Exit!")
signal.signal(signal.SIGALRM, signal_handler)
signal.alarm(time_limit) 

# Reset signal countdown every time to write to file.
def print_to_file(msg):
    print(msg) #or other writing method.
    signal.alarm(time_limit)

try:
    # Do your stuff here, for example:
    print_to_file('a')
    time.sleep(time_limit + 1)
except TimeoutException, msg:
    # Nothing happened for 5 minutes!
    print msg
else:
    signal.alarm(0)

【讨论】:

猜你喜欢
  • 2011-06-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-16
  • 2011-10-25
  • 1970-01-01
相关资源
最近更新 更多