The idea of using python to obtain CPU and memory information and the realization of of Linux system

  • 2020-04-02 13:20:20
  • OfStack

Is known to all, everything as a file in Linux, in Linux/Unix, under the root directory of the/proc directory, the/proc is a kernel and the kernel module is used to send information to the process (process) mechanism (so called "/ proc"), the pseudo file systems allow interaction with the kernel internal data structure, to obtain useful information about the process, in the run (on the fly) change the Settings (by changing the parameters of the kernel). Unlike other file systems, /proc exists in memory rather than on the hard drive. The information provided by the proc file system is as follows:

The & # 8226; Process information: any process in the system has a process ID with the same name in the proc subdirectory, and you can find cmdline, mem, root, stat, statm, and status. Some information is visible only to the superuser, such as the process root directory. Each process that contains existing process information separately has some special links available, and each process in the system has a separate self-link to the process information, which is used to get command line information from the process.
The & # 8226; System information: you can also get the entire system information from /proc/stat if you need it, including CPU usage, disk space, memory swapping, interrupts, and so on.
The & # 8226; CPU information: the /proc/cpuinfo file is used to obtain the current accurate information of the CPU.
The & # 8226; Load information: the /proc/loadavg file contains system load information.
The & # 8226; System memory information: the /proc/meminfo file contains details of system memory, showing the amount of physical memory, the amount of swap space available, the amount of free memory, and so on.

This way, you can see the relevant information via the cat command:


liujl@liujl-ThinkPad-Edge-E431:~/mybash$ cat /proc/cpuinfo
processor : 0
vendor_id : GenuineIntel
cpu family : 6
model  : 58
model name : Intel(R) Core(TM) i5-3230M CPU @ 2.60GHz
stepping : 9
microcode : 0x15
cpu MHz  : 1200.000
cache size : 3072 KB
physical id : 0
siblings : 4
core id  : 0
cpu cores : 2
apicid  : 0

. .


liujl@liujl-ThinkPad-Edge-E431:~/mybash$ cat /proc/meminfo 
MemTotal:        3593316 kB
MemFree:         2145916 kB
Buffers:           93372 kB
Cached:           684864 kB
SwapCached:            0 kB
Active:           706564 kB
Inactive:         554052 kB
Active(anon):     483996 kB
Inactive(anon):   178388 kB
Active(file):     222568 kB
Inactive(file):   375664 kB

. .   .

Here's how to get the requirements programmatically in python.

1. Get the information of CPU


#! /usr/bin/env python
#Filename:CPU1.py
from __future__ import print_function
from collections import OrderedDict
import pprint
def 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 CPUinfo
if __name__ == '__main__':
    CPUinfo = CPUinfo()
    for processor in CPUinfo.keys():
        print('CPUinfo[{0}]={1}'.format(processor,CPUinfo[processor]['model name']))

Run as follows:


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

2. Get memory information


#! /usr/bin/env python
#Filename:meminfo.py
from __future__ import print_function
from collections import OrderedDict
def 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 meminfo

if __name__ == '__main__':
    meminfo = meminfo()
    print("Total memory:{0}".format(meminfo['MemTotal']))
    print("Free memory:{0}".format(meminfo['MemFree']))

The results are as follows:


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


Related articles: