Copy the Code code as follows:
#!/usr/bin/env Python
From __future__ import print_function
From collections Import Ordereddict
Def meminfo ():
"Return The information in/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__ ':
#print (Meminfo ())
Meminfo = Meminfo ()
Print (' Total memory: {0} '. Format (meminfo[' Memtotal '))
Print (' free memory: {0} '. Format (meminfo[' Memfree '))
A brief explanation of Listing 3: Listing 3 reads the information in Proc/meminfo, and the split method of the Python string is used more frequently or more. For example, we need to store a very long data, and according to the structure of the method of storage, convenient to take the data later processing. Of course, it can be in JSON form. But you can also store the data in a field and then have some kind of identifier to split it. The strip in Python is used to remove the first character of the string, and the last listing 3 prints out the total memory and the number of idle numbers.
You can run the script using the Python command mem.py the results are shown in Figure 3.