python 调用top命令获取输出信息

时间:2021-12-01 02:57:05

问题:如何在linux上通过python脚本获取命令行的显示结果来进行处理?

解决方法:
1. python2.7版本有commands包
2. python3.x版本使用subprocess

下面是使用python3.4版本的示例
前面已解决使用python脚本选出top命令中cpu使用率最高的进程,现在解决如何获取top命令的回显信息。

在linux mint上执行top命令,可以看到不断刷新的top信息。使用top -n 1 可以看到某一时刻的top信息:
python 调用top命令获取输出信息

对应的代码实现是:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import subprocess


#
#variable 'out' is subprocess output info
top_info = subprocess.Popen(["top", "-n", "1"], stdout=subprocess.PIPE)
out, err = top_info.communicate()

#output info get from console has many unicode escape character ,such as \x1b(B\x1b[m\x1b[39;49m\x1b[K\n\x1b(B\x1b[m
#use decode('unicode-escape') to process

out_info = out.decode('unicode-escape')
print(out_info)

lines = []
lines = out_info.split('\n')

运行结果:
python 调用top命令获取输出信息

ps:如果没有处理unicode-escape,得到的运行结果将是:
python 调用top命令获取输出信息


process的使用:
http://*.com/questions/2502833/store-output-of-subprocess-popen-call-in-a-string
http://*.com/questions/14436499/saving-top-output-using-python
http://*.com/questions/25680033/python-script-to-capture-output-of-top-command
http://*.com/questions/20415467/python-attributeerror-int-object-has-no-attribute-replace
http://*.com/questions/15817420/subprocess-and-type-str-doesnt-support-the-buffer-api

unicode-escape 字符的处理:
http://*.com/questions/36279015/what-does-x1bb-do
http://*.com/questions/2936174/how-to-split-line-at-non-printing-ascii-character-in-python
http://www.qmailer.net/archives/251.html