Search code examples
pythonmemoryexternal-process

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?


Solution

  • 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.