Home > Article > Backend Development > Share Python to print a list of the top 10 programs that occupy memory in the form of a table
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 :
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!