python 调用top命令获取输出信息
来源:互联网 发布:cnc编程代码 编辑:程序博客网 时间:2024/06/05 02:45
问题:如何在linux上通过python脚本获取命令行的显示结果来进行处理?
解决方法:
1. python2.7版本有commands包
2. python3.x版本使用subprocess
下面是使用python3.4版本的示例
前面已解决使用python脚本选出top命令中cpu使用率最高的进程,现在解决如何获取top命令的回显信息。
在linux mint上执行top命令,可以看到不断刷新的top信息。使用top -n 1 可以看到某一时刻的top信息:
对应的代码实现是:
#!/usr/bin/env python3# -*- coding: utf-8 -*-import subprocess##variable 'out' is subprocess output infotop_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
- python 调用top命令获取输出信息
- top命令是什么?输出的信息是什么意思?
- top 命令显示 CPU 的信息是从哪里获取?
- top命令输出详解
- perl调用shell命令并获取输出
- 获得CPU利用率(python调用top命令实现)
- [python]subprocess调用外部命令屏蔽输出
- Python 通过调用接口获取公交信息
- Python执行命令行命令并获取输出
- top命令输出内容详解
- TOP命令输出完全解释
- popen + top 获取系统信息
- top命令展示的信息
- vc++调用exe时,如何获取exe的输出信息
- vc++调用exe时,如何获取exe的输出信息
- vc++调用exe时,如何获取exe的输出信息
- shell脚本循环调用top来获取进程的资源信息
- 调用console输出信息
- C++第四次作业
- iOS UISearchBar 属性 设置详解
- JavaScript 面向对象编程
- 围圈小朋友报数退出问题
- xUtils里使用HttpUtils时出现的无法访问HttpRequestBase的错误
- python 调用top命令获取输出信息
- jQuery中的选择器
- iOS中UISearchBar(搜索框)使用总结
- linux下yum安装mysql步骤
- Mysql cluster初学
- 1001. 二哥摘苹果
- 在OS X 上安装MongoDB
- 002如何构建hadoop集群环境?
- bzoj 2060: [Usaco2010 Nov]Visiting Cows 拜访奶牛(树形DP)