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

Source: Internet
Author: User
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!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.