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

如何正确将os.popen返回的ps命令输出格式化为字典列表

问题原因

原有代码固定从左向右按表头数量拆分字段,当COMMAND携带带空格的启动参数时,参数内容会被错误划入SIZE字段。ps输出的SIZE为右对齐纯数字,固定在每行末尾,调整拆分逻辑即可解决。

修复后代码

#!/usr/bin/env python3
import os
import pprint

output = os.popen('ps -eo pid,command,size --sort -size').readlines()
headers = [h for h in output[0].strip().split() if h]
processes = []

for line in output[1:]:
    line = line.strip()
    if not line:
        continue
    # 先从右侧拆分1次,精准提取末尾的SIZE字段
    left_content, size = line.rsplit(maxsplit=1)
    # 再从左侧拆分1次,提取PID和完整COMMAND内容
    pid, full_command = left_content.split(maxsplit=1)
    # 去除COMMAND后的启动参数,仅保留可执行文件路径
    command = full_command.split(maxsplit=1)[0]
    processes.append(dict(zip(headers, [pid, command, size])))

pprint.pprint(processes)

可选优化

如果不需要可执行文件的全路径,只需要命令名称,可以在提取command后再加一行:
command = os.path.basename(command)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 09:36:03