Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
communitycreator
psutil

How to get swap memory statistics in Python

abhilash

The psutil module

We can retrieve information about swap memory using the psutil module in Python.

psutil (Python system and process utilities) is a Python package that retrieves information about ongoing processes and system usage (CPU, memory, storage, network, and sensors). It is mostly used for system monitoring, profiling, restricting process resources, and process management.

The module can be installed via pip as follows:

pip install psutil

The swap_memory method

The swap_memory returns the swap memory statistics.

Syntax

psutil.swap_memory()

The method has no parameters.

Return value

The method returns a named tuple with the following attributes:

  • total: This is the total swap memory.
  • used: This is the used swap memory.
  • free: This is the free swap memory.
  • percent: This is the percentage usage calculated as (total - available) / total * 100.
  • sin: This is the number of bytes the system has swapped in from the disk.
  • sout: This is the number of bytes the system has swapped out from the disk.

All the above fields are in bytes.

Code example

import psutil

print("Swap Memory Information:")
print(psutil.swap_memory())
Using swap_memory()

Explanation

  • Line 1: We import the psutil module.
  • Line 5: We retrieve the swap memory information using the swap_memory() method.

RELATED TAGS

python
communitycreator
psutil
RELATED COURSES

View all Courses

Keep Exploring