You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Python判断进程处于后台还是前台运行?

实现思路:跨平台判断进程是否在前台并终止后台进程

psutil本身没有直接判断进程是否处于前台的API,因为"前台/后台"的定义依赖操作系统的窗口管理机制,需要结合各平台的系统工具或API来实现。以下分平台给出可行方案:

一、Windows平台

通过pywin32库遍历系统可见窗口,匹配进程PID来判断是否有前台窗口:

  1. 先依赖安装:pip install pywin32
  2. 实现代码:
import psutil
import win32gui
import win32process

def has_visible_window(pid):
    visible_windows = []
    def enum_window_callback(hwnd, extra_list):
        if win32gui.IsWindowVisible(hwnd):
            _, window_pid = win32process.GetWindowThreadProcessId(hwnd)
            if window_pid == pid:
                extra_list.append(hwnd)
    win32gui.EnumWindows(enum_window_callback, visible_windows)
    return len(visible_windows) > 0

# 遍历目标进程并终止后台实例
for proc in psutil.process_iter(['pid', 'name']):
    proc_name = proc.info['name'].lower()
    if proc_name in ['firefox.exe', 'chrome.exe']:
        if not has_visible_window(proc.info['pid']):
            proc.terminate()
            print(f"已终止后台进程:{proc.info['name']} (PID: {proc.info['pid']})")

二、Linux平台

借助wmctrl工具(需先通过包管理器安装,如sudo apt install wmctrl),读取当前所有可见窗口的PID信息:

import psutil
import subprocess

def has_active_window(pid):
    try:
        window_list = subprocess.check_output(['wmctrl', '-lp'], text=True)
        for line in window_list.splitlines():
            parts = line.split()
            if len(parts) >= 3 and parts[2] == str(pid):
                return True
        return False
    except subprocess.CalledProcessError:
        return False

# 处理目标进程
for proc in psutil.process_iter(['pid', 'name']):
    proc_name = proc.info['name'].lower()
    if proc_name in ['firefox', 'chrome']:
        if not has_active_window(proc.info['pid']):
            proc.terminate()
            print(f"已终止后台进程:{proc.info['name']} (PID: {proc.info['pid']})")

三、macOS平台

通过osascript调用AppleScript查询进程的可见性状态:

import psutil
import subprocess

def is_process_visible(pid):
    try:
        script = f'''
        tell application "System Events"
            set target_proc to first process whose unix id is {pid}
            return visible of target_proc
        end tell
        '''
        result = subprocess.check_output(['osascript', '-e', script], text=True).strip()
        return result == 'true'
    except subprocess.CalledProcessError:
        return False

# 处理目标进程
for proc in psutil.process_iter(['pid', 'name']):
    proc_name = proc.info['name'].lower()
    if proc_name in ['firefox', 'chrome', 'safari']:
        if not is_process_visible(proc.info['pid']):
            proc.terminate()
            print(f"已终止后台进程:{proc.info['name']} (PID: {proc.info['pid']})")

注意事项

  • 浏览器多进程模型:Chrome、Firefox会生成多个子进程,这些子进程通常没有独立窗口,建议只针对主进程(名称匹配且内存占用较高的进程)进行判断。
  • 权限问题:Linux/macOS下可能需要sudo权限才能终止系统级进程或读取窗口信息。
  • 进程名称匹配:不同平台的进程名称可能有差异(如macOS下Chrome名为Google Chrome),需根据实际情况调整匹配规则。

内容的提问来源于stack exchange,提问作者Knight Rider

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 16:01:11