Home  >  Article  >  Backend Development  >  Share Python to print a list of the top 10 programs that occupy memory in the form of a table

Share Python to print a list of the top 10 programs that occupy memory in the form of a table

高洛峰
高洛峰Original
2017-03-28 17:11:291992browse

This question involves Pythonoperations on processes, for loopscounting the number of loops, sorting and printingtables, etc. The question is relatively simple, and the renderings are as follows :

Share Python to print a list of the top 10 programs that occupy memory in the form of a table

Share Python to print a list of the top 10 programs that occupy memory in the form of a table

The code is as follows:

#!/usr/bin/python
# encoding: utf-8
# -*- coding: utf8 -*-
"""
Created by PyCharm.
File:               LinuxBashShellScriptForOps:performanceOps.py
User:               Guodong
Create Date:        2016/9/21
Create Time:        18:11
 """
import psutil
import prettytable
 
ps_result = list()
 
for proc in psutil.process_iter():
    ps_result.append({'name': proc.name(), 'pid': proc.pid, 'cpu_percent': proc.cpu_percent(),
                      'memory_percent': proc.memory_percent()})
 
table = prettytable.PrettyTable()
table.field_names = ["No.", "Name", "pid", "Memory percent"]
for i, item in enumerate(sorted(ps_result, key=lambda x: x['memory_percent'], reverse=True)):
    table.add_row([i + 1, item['name'], item['pid'], format(item['memory_percent'] / 100, '.2%')])
    if i >= 9:
        break
print table

Two main third-party modules are used, psutil (for Obtain process information) and prettytable (used to print tables), can be used on both Windows and Linux systems. If the prompt "ImportError: No module named xxxx" is prompted, you can execute the command pip install xxxx or easy_install xxxx.

The above is the detailed content of Share Python to print a list of the top 10 programs that occupy memory in the form of a table. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn