get system free memory in python

The psutil library provides an easy way to retrieve system information including memory usage. To get the free memory of the system, you can use the psutil.virtual_memory() method which returns a named tuple containing information about the virtual memory on the system. The free attribute of this tuple returns the amount of free memory in bytes.

Here's a code snippet that demonstrates how to use psutil to get the free memory of the system in Python:

main.py
import psutil

# get virtual memory info
mem = psutil.virtual_memory()

# get free memory in bytes
free_mem = mem.free

print(f"Free memory: {free_mem} bytes")
160 chars
10 lines

This will output something like:

main.py
Free memory: 2147483648 bytes
30 chars
2 lines

Note that the free attribute can return a large number of bytes, so you may want to convert it to a more human-readable format using the psutil._common.bytes2human() method, like this:

main.py
import psutil

# get virtual memory info
mem = psutil.virtual_memory()

# get free memory in human-readable format
free_mem = psutil._common.bytes2human(mem.free)

print(f"Free memory: {free_mem}")
198 chars
10 lines

which will output something like:

main.py
Free memory: 2.0 GiB
21 chars
2 lines

related categories

gistlibby LogSnag