您如何限制python子进程创建的文件大小?

时间:2019-01-29 19:07:29

标签: python

我从python这样运行一个子进程(不是我的脚本):

  with contextlib.redirect_stdout(log_file):
    # ....
    processResult = subprocess.run(args, 
                    stdout=sys.stdout, 
                    stderr=sys.stderr
                    timeout=3600)

有时该过程变得疯狂(由于间歇性错误),并且将大量错误转储到stdout / logfile中,使其增长到40Gb并填满了磁盘空间。

防止这种情况的最佳方法是什么?作为python新手,我有2个想法:

  • 将子流程插入head之类的子流程中,如果输出超出限制(如果不确定subprocess.run是否可能这样做,或者我必须采用低级Popen方式,则可能终止) p>

  • 查找或创建一些方便的IO包装器类IOLimiter,该类将在给定大小后引发错误(无法在stdlib中找到类似这样的东西,甚至不确定在哪里寻找它)

我怀疑会有更聪明/更清洁的方式吗?

1 个答案:

答案 0 :(得分:2)

我最近有this problem个人。我使用popen方法,设置了PYTHONUNBUFFERED=1

test_proc = subprocess.Popen(
    my_command,
    universal_newlines=True,
    stdout=subprocess.PIPE,
    stderr=subprocess.STDOUT,
)

print(time.time(), "START")
# Iterate over the lines of output produced
for out_data in iter(test_proc.stdout.readline, ""):
    # Check whatever I need.