Python & Ubuntu Get process information

Source: Internet
Author: User

Memo, in fact, is to know the memory condition used by the process.

To get the memory information of the system first:


defMemory_stat ():
" "
Return the memory info
" "
Mem= {}
Stat={}
F=Open ('/proc/meminfo')
Lines=F.readlines ()
for Lineinchlines:
ifLen (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']
returnStat

Because I use the method below to get the process information, you can only know the percentage of memory that the process occupies. Therefore, the total amount of memory must be obtained first.

Next, define a function to get process information.

defProc_stat (PROCID):
Importcommands
Ps_stat=None
Try:
#get memory information for a process
Ps_stat=Commands.getoutput ('PS-FP%s-u' %procid). Split ('\ n')[2].split ()
except:
return {}

ProcInfo= {}

procinfo['PID'] =ProcID

#This calls the memory_stat you just defined to get the total amount of memory,
    #then multiply the percentage of memory that the process occupies, which is the amount of memory used
procinfo['memoryused'] =Memory_stat () ['Memtotal'] *Float (ps_stat[3]) /  -

procinfo['Start'] =ps_stat[8]
procinfo['Startcommand'] =ps_stat[Ten]

returnProcInfo


Then use Ipython, test, start a Python process, assuming the process ID is 2168, then:

fromMachineinfoImportProc_stat

PS=Proc_stat (2168)

Ps

{'memoryused': 3650289.6639999999, #This is done in byte, or you can convert it yourself
 'PID': 2168,
'Start': '21:56',
'Startcommand': 'python'}

The record is complete. over~

Python & Ubuntu Get process information

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.