gpt4 book ai didi

python - 在 Python 中检测网络是否空闲

转载 作者:行者123 更新时间:2023-11-28 17:46:02 25 4
gpt4 key购买 nike

我正在制作一个基于 Python 的下载器。截至目前,我有一个基于多处理的控制台脚本。我想知道如何检测网络是否空闲。即,用户自己不使用网络(浏览、冲浪等)。

在这方面它应该能够做两件事:

  1. 检测到网络空闲时恢复下载。
  2. 检测到某些网络事件时暂停下载。

定义“空闲”的一种方法可能是在网络事件连续 5 分钟处于最大带宽的 1% 时触发。

有没有更好的方法来检测网络是否空闲?

最佳答案

我建议使用 psutil.network_io_counters 模块:

Return network I/O statistics as a namedtuple including the following attributes:

  • bytes_sent: number of bytes sent
  • bytes_recv: number of bytes received
  • packets_sent: number of packets sent
  • packets_recv: number of packets received
  • errin: total number of errors while receiving
  • errout: total number of errors while sending
  • dropin: total number of incoming packets which were dropped
  • dropout: total number of outgoing packets which were dropped (always 0 on OSX and BSD)

If pernic is True return the same information for every network interface installed on the system as a dictionary with network interface names as the keys and the namedtuple described above as the values.

In [1]: import psutil
In [2]: psutil.network_io_counters(pernic=True)
Out[2]:
{'en0': iostat(bytes_sent=143391435L, bytes_recv=1541801914L,
packets_sent=827983L, packets_recv=1234558L, errin=0L, errout=0L,
dropin=0L, dropout=0),
'gif0': iostat(bytes_sent=0L, bytes_recv=0L, packets_sent=0L, packets_recv=0L,
errin=0L, errout=0L, dropin=0L, dropout=0),
'lo0': iostat(bytes_sent=6143860L, bytes_recv=6143860L, packets_sent=55671L,
packets_recv=55671L, errin=0L, errout=0L, dropin=0L, dropout=0),
'p2p0': iostat(bytes_sent=0L, bytes_recv=0L, packets_sent=0L, packets_recv=0L,
errin=0L, errout=0L, dropin=0L, dropout=0),
'stf0': iostat(bytes_sent=0L, bytes_recv=0L, packets_sent=0L, packets_recv=0L,
errin=0L, errout=0L, dropin=0L, dropout=0)
}

您可以跟踪要监控的接口(interface)上发送和接收的字节,这将为您提供网络空闲或繁忙的信息。

关于python - 在 Python 中检测网络是否空闲,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17983355/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com