红联Linux门户
Linux帮助

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

发布时间:2016-05-13 15:50:06来源:linux网站作者:justheretobe

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


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

下面是使用python3.4版本的示例,现在解决如何获取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命令获取输出信息


本文永久更新地址:http://www.linuxdiyf.com/linux/20620.html