How to get memory usage of an external program - python

user1644254 picture user1644254 · Sep 4, 2012 · Viewed 8.5k times · Source

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?

Answer

Mikhail Karavashkin picture Mikhail Karavashkin · Sep 4, 2012

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)