[英]How to clean up after subprocess.Popen?
我有一個長期運行的python腳本與perl worker子進程。 數據通過stdin和stdout發送進出子進程。 必須定期重新啟動孩子。
不幸的是,經過一段時間的運行,它耗盡了文件('太多的打開文件')。 lsof顯示了許多剩余的開放管道。
在Popen'd過程之后清理的正確方法是什么? 這就是我現在正在做的事情:
def start_helper(self):
# spawn perl helper
cwd = os.path.dirname(__file__)
if not cwd:
cwd = '.'
self.subp = subprocess.Popen(['perl', 'theperlthing.pl'], shell=False, cwd=cwd,
stdin=subprocess.PIPE, stdout=subprocess.PIPE,
bufsize=1, env=perl_env)
def restart_helper(self):
# clean up
if self.subp.stdin:
self.subp.stdin.close()
if self.subp.stdout:
self.subp.stdout.close()
if self.subp.stderr:
self.subp.stderr.close()
# kill
try:
self.subp.kill()
except OSError:
# can't kill a dead proc
pass
self.subp.wait() # ?
self.start_helper()
我認為這就是你所需要的:
def restart_helper(self):
# kill the process if open
try:
self.subp.kill()
except OSError:
# can't kill a dead proc
pass
self.start_helper()
# the wait comes after you opened the process
# if you want to know how the process ended you can add
# > if self.subp.wait() != 0:
# usually a process that exits with 0 had no errors
self.subp.wait()
據我所知,所有文件對象將在popen進程被殺死之前關閉。
一個快速實驗表明x = open("/etc/motd"); x = 1
x = open("/etc/motd"); x = 1
自行清理並且不保留打開的文件描述符。 如果你刪除最后一個subprocess.Popen
引用管道似乎堅持。 難道你重新調用start_helper()
或者甚至一些其他Popen
)沒有明確的關,停舊的?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.