Obtain process information from Python and Ubuntu. Basic python tutorial
I want to know the memory usage of the process.
First, you must obtain the system memory information:
Def memory_stat ():
'''
Return the memory info
'''
Mem = {}
Stat = {}
F = open ('/proc/meminfo ')
Lines = f. readlines ()
For line in lines:
If len (line) <2: continue
Name = line. split (':') [0]
Var = line. split (':') [1]. split () [0]
Mem [name] = long (var) * 1024.0
Stat ['memused'] = mem ['memtotal']-mem ['memfree']-mem ['buffers']-mem ['cached']
Stat ['memtotal'] = mem ['memtotal']
Stat ['memfree'] = mem ['memfree']
Stat ['buffers'] = mem ['buffers']
Stat ['cached'] = mem ['cached']
Return stat
Because the process information I used in the following method can only be known as the percentage of memory occupied by the process. Therefore, you must first obtain the total memory size.
Next, define a function to obtain process information.
Def proc_stat (procid ):
Import commands
Ps_stat = None
Try:
# Obtain the memory information of a process
Ps_stat = commands. getoutput ('ps-fp % s-U' % procid). split ('\ n') [2]. split ()
Except t:
Return {}
ProcInfo = {}
ProcInfo ['pid '] = procid
# Here we call the defined memory_stat to get the total memory,
# Multiply by the percentage of memory occupied by the process, that is, the memory usage.
ProcInfo ['memoryused'] = memory_stat () ['memtotal'] * float (ps_stat [3])/100
ProcInfo ['start'] = ps_stat [8]
ProcInfo ['startcommand'] = ps_stat [10]
Return procInfo
Run ipython to test and start a python process. Assume that the process ID is 2168. Then:
From MachineInfo import proc_stat
Ps = proc_stat (2168)
Ps
{'Memoryused': 3650289.6639999999, # Here the unit is byte. You can also convert it by yourself.
'Pid': 2168,
'Start': '21: 56 ',
'Startcommand': 'python '}
Record completed. Over ~