66
votes

Possible Duplicate:
How to get current CPU and RAM usage in Python?

How can I get the available and currently used memory from Python? It need to be cross-platform and at least work on at least Windows, Mac OS X and Linux.

I'd like to report the user in my application that he doesn't have enough memory free to proceed and do the next operation.

2
Do you need memory or address space? Since at least in Windows, you're not out of memory if you still have swap space - blogs.msdn.com/b/ericlippert/archive/2009/06/08/… - Michael Stum♦
Looks similar to this question, the psutil library was recommended - Colin Dunklau
You just want try: ... except MemoryError: ... - JBernardo
@JBernardo catching memory errors is a risky business that usually doesnt work. Afak cPython has NOT been written to handle memory allocation errors gracefully (that'd be a very complex business), and even if you're able to run any code after a MemoryError, the state of the interpreter is unreliable and liable to have incorrect info and/or simply fail. - drevicko

2 Answers

110
votes

You should take a look to psutil :

>>> import psutil
>>> psutil.virtual_memory()
svmem(total=16717422592, available=5376126976, percent=67.8, used=10359984128, free=1831890944, active=7191916544, inactive=2325667840, buffers=525037568, cached=4000509952, shared=626225152)