前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python 调用top命令获取输出信息

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

作者头像
py3study
发布2020-01-06 16:52:43
3.3K0
发布2020-01-06 16:52:43
举报
文章被收录于专栏:python3python3

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

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

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

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

这里写图片描述
这里写图片描述

对应的代码实现是:

代码语言:javascript
复制
#!/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')

运行结果:

这里写图片描述
这里写图片描述

ps:如果没有处理unicode-escape,得到的运行结果将是:

这里写图片描述
这里写图片描述

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

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

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-09-18 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档