get system total memory in python

To get the system's total memory in Python, you can use the psutil library. psutil is a cross-platform library for retrieving information on running processes and system utilization (CPU, memory, disks, network, sensors) in Python.

Here's the code to get the total system memory using psutil:

main.py
import psutil

# Get the total memory in bytes
total_memory = psutil.virtual_memory().total

# Convert bytes to gigabytes
total_memory_gb = total_memory / (1024 ** 3)

print(f"Total memory: {total_memory_gb:.2f} GB")
217 chars
10 lines

This code first imports the psutil library, then uses the virtual_memory() function to get the current virtual memory usage, which includes the total amount of memory available on the system. We then divide this by the number of bytes in a gigabyte to get the total memory in gigabytes.

Finally, we print the total memory in gigabytes with two decimal places.

gistlibby LogSnag