Use python to obtain CPU and memory information (linux)

Source: Internet
Author: User

Everyone knows that everything in linux is a file. There is a/proc directory under the root directory of linux/unix, this/proc is a mechanism used by the kernel and kernel module to send information to the process (so it is called "/proc "), this pseudo file system allows interaction with the internal data structure of the kernel to obtain useful information about the process. on the fly, you can change the settings (by changing the kernel parameters ). Unlike other file systems,/proc exists in the memory instead of the hard disk. The proc file system provides the following information:

  • Process Information: any process in the system has a process ID with the same name in the proc subdirectory. You can find the cmdline, mem, root, stat, statm, and status. Some information is only visible to super users, such as the process root directory. Each process that contains existing process information has some available dedicated links. Any process in the system has a separate self-link pointing to process information, the command line information is obtained from the process. System Information: If you need to know the system information, you can also obtain it from/proc/stat, including CPU usage, disk space, memory swap, and interruption. CPU information: the current accurate information of the central processor can be obtained using the/proc/CPUinfo file. Load information: The/proc/loadavg file contains the system load information. System memory information: The/proc/meminfo file contains detailed information about the system memory, including the number of physical memory, the number of available swap space, and the number of idle memory.

     

    In this way, you can use the cat command to view the relevant information:

     

    liujl@liujl-ThinkPad-Edge-E431:~/mybash$ cat /proc/cpuinfoprocessor: 0vendor_id: GenuineIntelcpu family: 6model: 58model name: Intel(R) Core(TM) i5-3230M CPU @ 2.60GHzstepping: 9microcode: 0x15cpu MHz: 1200.000cache size: 3072 KBphysical id: 0siblings: 4core id: 0cpu cores: 2apicid: 0
    ... ...

     

     

    liujl@liujl-ThinkPad-Edge-E431:~/mybash$ cat /proc/meminfo MemTotal:        3593316 kBMemFree:         2145916 kBBuffers:           93372 kBCached:           684864 kBSwapCached:            0 kBActive:           706564 kBInactive:         554052 kBActive(anon):     483996 kBInactive(anon):   178388 kBActive(file):     222568 kBInactive(file):   375664 kB
    .. . ...

     

    The following describes how to obtain the required information through python programming.

    1. Obtain cpu Information

     

    #! /usr/bin/env python#Filename:CPU1.pyfrom __future__ import print_functionfrom collections import OrderedDictimport pprintdef CPUinfo():    '''Return the info in /proc/cpuinfo    as a dirctionary in the follow format:    CPU_info['proc0']={...}    CPU_info['proc1']={...}    '''        CPUinfo=OrderedDict()    procinfo=OrderedDict()    nprocs = 0    with open('/proc/cpuinfo') as f:        for line in f:            if not line.strip():                #end of one processor                CPUinfo['proc%s' % nprocs]=procinfo                nprocs = nprocs+1                #Reset                procinfo=OrderedDict()            else:                if len(line.split(':')) == 2:                    procinfo[line.split(':')[0].strip()] = line.split(':')[1].strip()                else:                    procinfo[line.split(':')[0].strip()] = ''    return CPUinfoif __name__ == '__main__':    CPUinfo = CPUinfo()    for processor in CPUinfo.keys():        print('CPUinfo[{0}]={1}'.format(processor,CPUinfo[processor]['model name']))

    Run the following command:

     

     

    liujl@liujl-ThinkPad-Edge-E431:~/mypython$ python CPU1.py CPUinfo[proc0]=Intel(R) Core(TM) i5-3230M CPU @ 2.60GHzCPUinfo[proc1]=Intel(R) Core(TM) i5-3230M CPU @ 2.60GHzCPUinfo[proc2]=Intel(R) Core(TM) i5-3230M CPU @ 2.60GHzCPUinfo[proc3]=Intel(R) Core(TM) i5-3230M CPU @ 2.60GHz

    2. Obtain memory information

     

     

    #! /usr/bin/env python#Filename:meminfo.pyfrom __future__ import print_functionfrom collections import OrderedDictdef meminfo():    '''return the info of /proc/meminfo    as a dictionary    '''    meminfo = OrderedDict()    with open('/proc/meminfo') as f:        for line in f:            meminfo[line.split(':')[0]] = line.split(':')[1].strip()    return meminfoif __name__ == '__main__':    meminfo = meminfo()    print(Total memory:{0}.format(meminfo['MemTotal']))    print(Free memory:{0}.format(meminfo['MemFree']))

    The result is as follows:

     

     

    liujl@liujl-ThinkPad-Edge-E431:~/mypython$ python meminfo.py Total memory:3593316 kBFree memory:2113712 kB

Related Article

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.