How to get the memory usage of a Linux system using Python ?python 获取linux内存占用
Published on Aug. 22, 2023, 12:14 p.m.
To get the memory usage of a Linux system using Python, you can use the psutil library. Here is an example code that will print the total virtual memory size, available virtual memory size, used virtual memory size, and memory usage percentage:
import psutil
# Get virtual memory usage statistics
virtual_memory = psutil.virtual_memory()
# Print memory usage statistics
print(f"Total: {virtual_memory.total}")
print(f"Available: {virtual_memory.available}")
print(f"Used: {virtual_memory.used}")
print(f"Percent: {virtual_memory.percent}")
psutil provides a lot of other system information as well, like CPU usage, process information, network usage, etc. To install psutil, you can use pip:
pip install psutil
This code should work on any Linux, as well as other operating systems that support psutil.