如何使用python从vmstat命令中删除CPU信息
vmstat命令有以下输出,我正在尝试删除cpu部分并用python打印如何使用python从vmstat命令中删除CPU信息,python,Python,vmstat命令有以下输出,我正在尝试删除cpu部分并用python打印 虚拟机 使用下面的python代码时,我会丢失空格,如何正确设置格式 因此,当cpu部分被移除时,输出看起来与上面的完全一样 import subprocess p = subprocess.Popen('vmstat', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) line1 = p.stdout.readlines() line2 = '
虚拟机 使用下面的python代码时,我会丢失空格,如何正确设置格式 因此,当cpu部分被移除时,输出看起来与上面的完全一样
import subprocess
p = subprocess.Popen('vmstat', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
line1 = p.stdout.readlines()
line2 = ' '.join(line1[0].split()[:-1])
line3 = ' '.join(line1[1].split()[:-5])
line4 = ' '.join(line1[2].split()[:-5])
print line2
print line3
print line4
procs -----------memory---------- ---swap-- -----io---- -system--
r b swpd free buff cache si so bi bo in
0 0 30468 20608 36548 837880 0 0 143 179 57
让我们先找到CPU头的位置,然后去掉剩余的字符。我将其设置为通用,因此使用字段名调用不带字段的
vmstat\u将从输出中删除它
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()
请核对我的答案。如果它解决了您的问题,请将其标记为已接受。
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()