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

如何使用Python统计系统中运行的程序实例数量

统计系统中正在运行的程序实例数量(Python实现)

方法一:使用psutil库(跨平台推荐)

psutil是跨平台的进程监控库,能直接获取进程信息,无需调用系统命令,实现更简洁。

  1. 先安装库:
pip install psutil
  1. 编写统计函数:
import psutil

def count_process_instances(target_name):
    instance_count = 0
    # 遍历所有进程,仅获取进程名字段
    for proc in psutil.process_iter(['name']):
        try:
            # 忽略大小写匹配,适配不同系统的进程名大小写差异
            if proc.info['name'].lower() == target_name.lower():
                instance_count += 1
        except (psutil.NoSuchProcess, psutil.AccessDenied):
            # 跳过已结束的进程或无权限访问的系统进程
            continue
    return instance_count

# 示例调用
# Linux下统计gnome-terminal终端实例
print(count_process_instances('gnome-terminal'))
# macOS下统计Terminal终端实例
print(count_process_instances('Terminal'))
# Windows下统计cmd.exe终端实例
print(count_process_instances('cmd.exe'))

方法二:调用系统原生命令(无需第三方库)

如果不想依赖第三方库,可直接调用系统自带的进程查询命令,解析输出结果统计数量。

Linux/macOS 平台

使用ps命令获取进程列表:

import subprocess

def count_processes_unix(target_name):
    # 执行ps命令,仅输出进程命令行内容
    result = subprocess.run(
        ['ps', '-ax', '--no-headers', '-o', 'command'],
        capture_output=True,
        text=True,
        check=True
    )
    process_lines = result.stdout.splitlines()
    # 统计包含目标进程名的条目(可改为精确匹配避免重名干扰)
    return sum(1 for line in process_lines if target_name.lower() in line.lower())

# 示例:统计konsole终端实例
print(count_processes_unix('konsole'))

Windows 平台

使用tasklist命令查询进程:

import subprocess

def count_processes_windows(target_name):
    # 过滤指定进程名,不显示表头
    result = subprocess.run(
        ['tasklist', '/FI', f'IMAGENAME eq {target_name}', '/NH'],
        capture_output=True,
        text=True,
        check=True
    )
    # 清理空行后统计有效进程行数
    process_lines = [line.strip() for line in result.stdout.splitlines() if line.strip()]
    return len(process_lines)

# 示例:统计PowerShell终端实例
print(count_processes_windows('powershell.exe'))

注意事项

  • 进程名准确性:不同系统的进程名存在差异,比如Linux终端有gnome-terminal、xfce4-terminal等,Windows终端是cmd.exe、pwsh.exe,需先确认目标程序的准确进程名。
  • 权限问题:部分系统进程需要管理员/root权限才能访问,此时会抛出权限异常,需在代码中捕获处理。
  • 精确匹配:若担心重名进程干扰,可将匹配逻辑改为精确匹配(如proc.info['name'] == target_name),或结合进程路径进一步筛选。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 01:24:30