深度阅读

How to Make a Network Usage Monitor in Python

作者
作者
2023年08月22日
更新时间
18.65 分钟
阅读时间
0
阅读量

To make a network usage monitor in Python, you can use the psutil library to get information about network connections and data transfer rates. Here is an example code snippet:

import psutil
import time

def monitor_network():
    old_value = psutil.net_io_counters().bytes_sent + psutil.net_io_counters().bytes_recv
    while True:
        new_value = psutil.net_io_counters().bytes_sent + psutil.net_io_counters().bytes_recv
        bytes_per_second = (new_value - old_value) / 1
        old_value = new_value
        print("Current network usage: ", bytes_per_second, "bytes per second")
        time.sleep(1)

monitor_network()
Current network usage:  0.0 bytes per second
Current network usage:  16622.0 bytes per second
Current network usage:  290297.0 bytes per second
Current network usage:  31555.0 bytes per second
Current network usage:  11301.0 bytes per second
Current network usage:  10862.0 bytes per second
Current network usage:  2454.0 bytes per second
Current network usage:  20847.0 bytes per second
Current network usage:  200564.0 bytes per second
Current network usage:  107393.0 bytes per second

In this example, we define a function called monitor_network() that uses the psutil library to get the current number of bytes sent and received by the system through network connections. We use a while loop to continuously calculate the rate of data transfer in bytes per second and print the result to the console.

We sleep for 1 second between iterations to avoid consuming too much processing time.

You can modify this code to suit your specific monitoring requirements, such as tracking usage over a longer period or logging the data to a file.

Please note that network monitoring may require elevated privileges on some systems, and should be used responsibly and only with the appropriate permissions.

相关标签

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。