问题描述
我正在使用 PSUTIL 库(主要是因为它是跨平台的)来终止进程及其后代。但它正在强行关闭进程。我正在使用“.terminate”命令。我想发送一个正常的关闭信号并优雅地终止一个进程。我该怎么做?
def kill_process(self,pid,including_parent=True):
'''
Kill_process method will kill the process and it's descendants recursively
'''
err_msg_temp = None
try:
parent = psutil.Process(pid)
for child in parent.children(recursive=False):
child_pid = child.pid
if child_pid not in deleted_processes:
self.kill_process(child_pid)
if including_parent:
deleted_processes[pid] = 1
parent.terminate()
except Exception as e:
err_msg_temp = str(e)
如果有跨平台命令,我也想知道。
解决方法
您是否尝试使用 child_pid.send_signal(signal.SIGTERM)
?
send_signal
是来自 Process 类的方法
信号模块文档: https://docs.python.org/3/library/signal.html
,感谢 Andrew D. bond's answer 我找到了解决方案。代码在 Windows 中运行良好。
import win32con
import win32api
import win32gui
import win32process
import psutil
def enumWindowsProc(hwnd,lParam):
if (lParam is None) or ((lParam is not None) and win32process.GetWindowThreadProcessId(hwnd)[1] == lParam):
text = win32gui.GetWindowText(hwnd)
if text:
win32api.SendMessage(hwnd,win32con.WM_CLOSE)
def stop_app(app_exe):
for process in psutil.process_iter():
if process.name() == app_exe:
win32gui.EnumWindows(enumWindowsProc,process.pid)
stop_app("chrome.exe")