我有一个长时间运行的Python脚本,其中包含一个Perl工作子进程。数据通过其标准输入和输出发送到子进程中并返回。定期地,需要重新启动子进程。
不幸的是,运行一段时间后,它会耗尽文件('too many open files')。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()
Popen.kill
(或Popen.terminate
)是您最好的选择。 - Santasubprocess
无关的错误,但它可能会对_cleanup()
函数有所启示。http://bugs.python.org/issue1731717 - jfsclose_fds=True
(py3k默认) - jfs