![](/img/trans.png)
[英]Python subprocess.Popen.wait(Popen) not redirecting output to file
[英]Is it possible that processes created by subprocess module in Python still use up memory (are zombies), although subprocess.Popen.wait() was called?
根據stackoverflow中另一個問題的答案( 如何使用子進程模塊殺死(或避免)僵屍進程 ),可以使用命令subprocess.Popen.wait()
避免僵屍進程。
但是,當我在腳本中運行以下函數perform_sth
幾千次時,每個進程的內存使用量往往會增加:
例如,第一個進程僅需要7 MB,但是僅需7 MB。 1000已經有500 MB,直到最后使用了超過8 GB,我必須殺死整個Python腳本。 該進程應始終使用或多或少相同數量的內存。
可能我的功能存在缺陷,是否需要額外終止進程?
我的代碼是:
def perform_sth(arg1, arg2):
import subprocess
sth_cline = ["sth", "-asequence=%s"%arg1, "-bsequence=%s"]
process = subprocess.Popen(
sth_cline,
stdout = subprocess.PIPE,
stderr = subprocess.PIPE
)
process.wait()
return
如果您不從管道讀取數據,請不要使用stdout=PIPE
。
您的子進程不是僵屍 (僵屍是一個死進程;它只需要很少的內存,即可將其退出狀態存儲在進程表中)。 您的子進程仍處於活動狀態 (這就是為什么它能夠消耗千兆字節的內存)。
嘗試寫入管道時,操作系統管道緩沖區可能已滿,並且子進程被阻塞。 您的父級應該通過從管道中讀取來耗盡緩沖區,以允許子級繼續運行,但是父級等待process.wait()
永遠返回(死鎖)。
如果不需要輸出,請改用stdout=subprocess.DEVNULL
。 或參閱如何在Python 2.7中隱藏子流程的輸出
#!/usr/bin/env python
from subprocess import check_call, DEVNULL, STDOUT
check_call(["sth", "arg 1", "arg2"], stdin=DEVNULL, stdout=DEVNULL, stderr=STDOUT)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.