如何使用python从vmstat命令中删除CPU信息

2024-05-31 23:37:29 发布

您现在位置:Python中文网/ 问答频道 /正文

vmstat命令有以下输出,我尝试删除cpu部分并用python打印
虚拟机状态

procs -----------memory---------- ---swap-- -----io---- -system-- ----cpu----
 r  b   swpd   free   buff  cache   si   so    bi    bo   in   cs us sy id wa
 0  0  30468  23468  36496 837876    0    0   143   179   57  105  2  1 97  1

使用下面的python代码,我将丢失空格,如何正确格式化 所以去掉cpu部分后,输出看起来和上面一样

^{pr2}$

Tags: io命令freecacheso状态cpusystem
1条回答
网友
1楼 · 发布于 2024-05-31 23:37:29

让我们首先找到CPU头的位置,然后剥离剩余的字符。我已经将其设为通用的,因此使用字段名调用vmstat_without_field将从输出中删除它。在

import subprocess
import re

def vmstat_without_field(field = 'cpu'):
    lines = subprocess.Popen('vmstat', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).stdout.readlines()
    match_obj = re.search('\s-+%s-+' % field, lines[0])
    start = match_obj.start()
    end = match_obj.end()

    for line in lines:
        line = line[:start] + line[end:]
        line = line[:-1] if line[-1] == '\n' else line
        print(line)

vmstat_without_field()

相关问题 更多 >