簡體   English   中英

您如何限制python子進程創建的文件大小?

[英]How would you limit file size created by a python subprocess?

我從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方式)

  • 查找或創建一些方便的IO包裝器類IOLimiter,該類將在給定大小后引發錯誤(無法在stdlib中找到類似這樣的東西,甚至不確定在哪里尋找它)

我懷疑會有更聰明/更清潔的方式嗎?

我本人最近有這個問題 我用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.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM