[Python third-party package] Quickly obtain hardware information and usage (psutil, platform)

Article directory

  • Preface
  • 1. psutil package
    • 1.1 Install psutil package
    • 1.2 How to use psutil
      • Get CPU usage
      • Get memory usage
      • Change memory usage into GB and MB
      • Get disk usage
      • Disk memory for conversion
      • Get network information
      • Network info
  • 2. platform
    • 2.1 Introduction to platform
    • 2.2 How to use platform
      • Get the name of the operating system
      • Get the name of the schema
  • Summarize

Foreword

During development, understanding your system’s hardware information and usage is critical to optimizing performance and troubleshooting issues. Python provides some powerful third-party packages that can easily obtain hardware information and usage. This article will introduce two commonly used packages: psutil and platform.

1. psutil package

1.1 Install psutil package

we can use

pip install psutil -i https://pypi.tuna.tsinghua.edu.cn/simple

If you don’t want to use a mirror, you can install it like this:

pip install psutil

If you are a user of a higher version of Ubuntu, you can only use:

pip3 install psutil -i https://pypi.tuna.tsinghua.edu.cn/simple

This command installs

1.2 How to use psutil

Get CPU usage

psutil.cpu_percent(interval=1)

In the psutil.cpu_percent(interval=1) function, the interval parameter represents the sampling interval, in seconds. The function of this parameter is to specify the period of time to calculate the CPU usage.

Specifically, when you call psutil.cpu_percent(interval=1), it monitors the CPU usage over the next 1 second and returns the average CPU usage during this period. This value is usually expressed as a percentage and indicates how much of the CPU was used during the specified time interval. This function can be used to monitor the CPU load of the system, especially in applications that require real-time monitoring of system performance in order to take timely actions or record performance data.

You can adjust the value of the interval parameter according to specific needs to obtain CPU usage data in different time intervals. Shorter time intervals provide more real-time data but may introduce more noise, while longer time intervals provide smoother data but may miss performance fluctuations over shorter periods of time.

Get memory usage

memory_info = psutil.virtual_memory()

Just call the function directly!

Change the memory usage into GB and MB

psutil.virtual_memory() returns a named tuple containing system virtual memory information, including the values of various memory indicators. The units of these values are usually bytes. If you wish to convert these values into more common units such as MB (megabytes) or GB (gigabytes), you can do so using:

Extract the required values from the named tuple returned by psutil.virtual_memory().
Convert bytes to MB or GB, considering 1MB = 1024KB and 1GB = 1024MB.
Here is a sample code showing how to convert the return value of psutil.virtual_memory() into MB and GB:

import psutil

# Get system virtual memory information
memory_info = psutil.virtual_memory()

# Extract the values of total memory, used memory, and free memory (unit: bytes)
total_memory_bytes = memory_info.total
used_memory_bytes = memory_info.used
free_memory_bytes = memory_info.available # Note that available is used instead of free here

# Convert to MB and GB
total_memory_mb = total_memory_bytes / 1024**2 # Convert to MB
used_memory_mb = used_memory_bytes / 1024**2 # Convert to MB
free_memory_mb = free_memory_bytes / 1024**2 # Convert to MB

total_memory_gb = total_memory_bytes / 1024**3 # Convert to GB
used_memory_gb = used_memory_bytes / 1024**3 # Convert to GB
free_memory_gb = free_memory_bytes / 1024**3 # Convert to GB

#Print the converted memory information
print(f"Total memory: {<!-- -->total_memory_mb:.2f} MB / {<!-- -->total_memory_gb:.2f} GB")
print(f"Used memory: {<!-- -->used_memory_mb:.2f} MB / {<!-- -->used_memory_gb:.2f} GB")
print(f"Free memory: {<!-- -->free_memory_mb:.2f} MB / {<!-- -->free_memory_gb:.2f} GB")
This code will convert the memory information from byte units to MB and GB units and print out the results. You can further process or display these values as needed.

Get disk usage

disk_info = psutil.disk_usage('/')

The psutil.disk_usage(/’) function is used to obtain the disk usage information of the specified path (in this case, the root directory). The parameter of this function is a string representing the path of the disk partition to be queried. Here, /’ represents the root directory, which usually represents the entire root file system.

Disk memory conversion

The returned object contains information about disk usage, including total capacity, used capacity, free capacity, and so on. These values are usually in bytes. If you want to convert these values to more common units such as GB (gigabytes), MB (megabytes) or TB (terabytes), you can do so as follows:

Extract the required value from the object returned by psutil.disk_usage(/’).
Convert bytes to GB, MB or TB, considering 1GB = 1024MB, 1MB = 1024KB, 1TB = 1024GB.
Here is a sample code that shows how to convert the disk usage information returned by psutil.disk_usage(/’) into GB, MB, and TB:

import psutil

# Get root directory disk usage information
disk_info = psutil.disk_usage('/')

# Extract the values of total capacity, used capacity, and available capacity (unit: bytes)
total_bytes = disk_info.total
used_bytes = disk_info.used
free_bytes = disk_info.free

# Convert to GB, MB, TB
total_gb = total_bytes / (1024**3) # Convert to GB
used_gb = used_bytes / (1024**3) # Convert to GB
free_gb = free_bytes / (1024**3) # Convert to GB

# Print the converted disk usage information
print(f"Total capacity: {<!-- -->total_gb:.2f} GB")
print(f"Used capacity: {<!-- -->used_gb:.2f} GB")
print(f"Available capacity: {<!-- -->free_gb:.2f} GB")

This code converts disk usage information from bytes to GB and prints the result. You can further process or display these values as needed.

Get network information

network_info = psutil.net_io_counters()

Network info

The psutil.net_io_counters() function returns a named tuple containing network IO counter information, including input and output statistics for various network interfaces. Here’s the main information it contains, along with some example values:

bytes_sent: Number of bytes sent.
bytes_recv: Number of bytes received.
packets_sent: Number of packets sent.
packets_recv: Number of received packets.
errin: Number of error packets on reception.
errout: Number of error packets when sending.
dropin: The number of packets dropped when receiving.
dropout: The number of packets dropped when sending.
Sample code demonstrating how to obtain and list information about the return value of psutil.net_io_counters():

import psutil

# Get network IO counter information
network_info = psutil.net_io_counters()

# OK
bytes_sent = network_info.bytes_sent
bytes_recv = network_info.bytes_recv
packets_sent = network_info.packets_sent
packets_recv = network_info.packets_recv
errin = network_info.errin
errout = network_info.errout
dropin = network_info.dropin
dropout = network_info.dropout

#Print information
print(f"Number of bytes sent: {<!-- -->bytes_sent} bytes")
print(f"Number of bytes received: {<!-- -->bytes_recv} bytes")
print(f"Number of packets sent: {<!-- -->packets_sent} packets")
print(f"Number of received packets: {<!-- -->packets_recv} packets")
print(f"Number of error packets when receiving: {<!-- -->errin} packets")
print(f"Number of error packets when sending: {<!-- -->errout} packets")
print(f"Number of packets dropped when receiving: {<!-- -->dropin} packets")
print(f"Number of packets dropped when sending: {<!-- -->dropout} packets")

This information helps monitor your system’s network activity, including the amount of data sent and received, as well as network errors and packet drops. This is useful for network performance analysis and troubleshooting.

2. platform

Introduction to 2.1 platform

Platform is a built-in library in Python that provides a way to obtain general information about the system, such as operating system, hardware architecture, etc.
The library is easy to use and can quickly obtain key information related to the operating system and hardware.

2.2 How to use platform

Get the name of the operating system

platform.system()

Get the name of the schema

platform.architecture()

Summary

By using the third-party packages psutil and platform, we can easily obtain hardware information and usage. psutil provides a rich interface to monitor CPU, memory, disk and network usage. The platform library provides a simple way to obtain general information about the system, such as operating system and hardware architecture. These tools are very useful for developers in performance optimization, resource management, and troubleshooting.

Whether you are developing desktop applications, server-side applications, or system tools, understanding hardware information and usage is critical. These Python third-party packages are easy to use and powerful, and can help developers better understand the operating status of the system and thereby optimize application performance.

Although this article introduces psutil and platform, two commonly used packages, there are other related third-party packages available in the Python ecosystem. Depending on the specific needs and usage scenarios, you can further explore and try other packages suitable for your project.

I hope this article can help you understand how to quickly obtain hardware information and usage, and facilitate your development work.