Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get memory usage of an external program - python

I am trying to get the memory usage of an external program within my python script. I have tried using the script http://code.activestate.com/recipes/286222/ as follows:

m0 = memory()
subprocess.call('My program')
m1 = memory(m0)
print m1

But this seems to be just giving me the memory usage of the python script rather than 'My program'. Is there a way of outputting the memory usage of the program for use within the python script?

like image 264
user1644254 Avatar asked Mar 01 '26 13:03

user1644254


2 Answers

Try using Psutil

import psutil
import subprocess
import time

SLICE_IN_SECONDS = 1
p = subprocess.Popen('calling/your/program')
resultTable = []
while p.poll() == None:
  resultTable.append(psutil.get_memory_info(p.pid))
  time.sleep(SLICE_IN_SECONDS)
like image 128
Mikhail Karavashkin Avatar answered Mar 04 '26 03:03

Mikhail Karavashkin


If you look at the recipe you will see the line:

_proc_status = '/proc/%d/status' % os.getpid()

I suggest you replace the os.getpid() with the process id of your child process. As @Neal said, as I was typing this you need to use Popen and get the pid attribute of the returned object.

However, you have a possible race condition because you don't know at what state the child process is at, and the memory usage will vary anyway.

like image 32
cdarke Avatar answered Mar 04 '26 02:03

cdarke



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!