本文要点在于Python扩展库psutil提供的方法net_io_counters()可以查看本机网络收发包和流量情况,稍加封装就可以实现流量监视器。
import time
import psutil
def main():
#初始流量情况
traffic_io = psutil.net_io_counters()[:2]
while True:
#0.5秒之后再次获取流量情况
time.sleep(0.5)
traffic_ioNew = psutil.net_io_counters()[:2]
diff = traffic_ioNew[0]-traffic_io[0], traffic_ioNew[1]-traffic_io[1]
#记录新的流量情况,以便下次比较和计算
traffic_io = traffic_ioNew
#乘2是因为0.5秒查看一次,除1024是为了把单位变成kb
diff = tuple(map(lambda x: x*2/1024, diff))
message = '↑{0[0]:#f} kbytes/s\t↓{0[1]:#f} kbytes/s'.format(diff)
print(message)
main()