如果您不介意安装Python Win32 扩展,您可以使用 Windows API 等待进程退出,如下所示:
from win32con import SYNCHRONIZE
from win32event import WaitForSingleObject, INFINITE
from win32api import OpenProcess, CloseHandle
process_handle = OpenProcess(SYNCHRONIZE, False, pid)
try:
WaitForSingleObject(process_handle, INFINITE)
finally:
CloseHandle(process_handle)
这将导致代码阻塞,直到进程退出(如果需要,可以更改INFINITE
in值;请参阅文档)。WaitForSingleObject()
或者,无需安装扩展程序,您可以使用 来执行此操作ctypes
,特别简单,因为所有必要的方法都在kernel32.dll
:
from ctypes import windll
SYNCHRONIZE = 0x100000L
INFINITE = 0xFFFFFFFFL
process_handle = windll.kernel32.OpenProcess(SYNCHRONIZE, 1, pid)
windll.kernel32.WaitForSingleObject(process_handle, INFINITE)
windll.kernel32.CloseHandle(process_handle)
当然,在这种情况下,错误处理代码(省略)要复杂一些,而且远不如 Pythonic。