This topic involves Python operations on processes, for loop counting cycles, sorting and printing tables, etc. The question is relatively simple, as shown in the following code :#! Usrbinpython # encoding: UTF-8 #-*-coding: utf8-*-C .. this topic involves Python operations on processes, for loop counting cycles, sorting and printing tables, etc. The question is relatively simple, as shown below:
The code is as follows:
#!/usr/bin/python# encoding: utf-8# -*- coding: utf8 -*-"""Created by PyCharm.File: LinuxBashShellScriptForOps:performanceOps.pyUser: GuodongCreate Date: 2016/9/21Create Time: 18:11 """import psutilimport 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: breakprint table
Two major third-party modules are used: psutil (used to obtain process information) and prettytable (used to print tables), which can be used on both Windows and Linux systems. if the prompt "ImportError: no module named xxxx ", you can execute the command pip install xxxx or easy_install xxxx.
The above is to share the details of the list of programs that occupy top 10 of the memory in the form of tables in Python. For more information, see other related articles in the first PHP community!