我使用Popen
来维护Python程序中的子流程池。在我的程序中有一些自然的点来执行"清理"——在这些点上,我调用Popen.poll()
来确定特定进程是否仍在运行,如果没有,我会从池中删除其Popen
对象,并回收它正在使用的任何资源。
是否需要调用Popen.wait()
来执行某种语言或操作系统级别的清理?对Popen.poll()
的调用已经确定进程已经终止,它甚至设置了returncode
属性。是否还有其他理由致电Popen.wait()
?
不,如果您正在调用poll
,则不必调用wait
。他们基本上做同样的事情,只是wait
无限等待。
poll
:
if self.returncode is None:
if _WaitForSingleObject(self._handle, 0) == _WAIT_OBJECT_0:
self.returncode = _GetExitCodeProcess(self._handle)
return self.returncode
wait
:
if self.returncode is None:
_subprocess.WaitForSingleObject(self._handle,
_subprocess.INFINITE)
self.returncode = _subprocess.GetExitCodeProcess(self._handle)
return self.returncode
这是用于subprocess
模块的windows实现的代码,但所有其他模块都应遵循相同的规则。
在MacOSX上,我假设Linux的实现是相同的,它们都调用os.waitpid
。