Python & amp; Ubuntu, basic python tutorial

Source: Internet
Author: User

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 ~

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.