4

I'm new to python and I need to calculate the 'average speed' of my network interface(like the tool nload) on a linux machine. The below code is telling me how much bytes have been sent and received. I would appreciate if someone could help me print the average speed of my network interface.

def main():
    rx_bytes, tx_bytes = get_network_bytes('eth0')
    print '%i bytes received' % rx_bytes
    print '%i bytes sent' % tx_bytes

def get_network_bytes(interface):
    for line in open('/proc/net/dev', 'r'):
        if interface in line:
            data = line.split('%s:' % interface)[1].split()
            rx_bytes, tx_bytes = (data[0], data[8])
            return (int(rx_bytes), int(tx_bytes))

if __name__ == '__main__':
    main()
4

1 回答 1

0

拿你的 main() 和 get_network_bytes() 并将它们包装在一个 python 进程中:

import subprocess
import time
from daemon import runner
import datetime

class App():
    def __init__(self):
        self.stdin_path = '/dev/null'
        self.stdout_path = '/dev/tty'
        self.stderr_path = '/dev/tty'
        self.pidfile_path =  '/tmp/YOUR_PROCESS_NAME.pid'
        self.pidfile_timeout = 5
    def run(self):

        counter1 = 0
        counter_log = 0
        try:
            while True:

                # INSERT YOUR FUNCTIONS HERE

                # SET YOUR LOOP SLEEP TIMER (IN SECONDS) HERE
                time.sleep(60)

        except Exception, e:
            raise

app = App()
daemon_runner = runner.DaemonRunner(app)
daemon_runner.do_action()

然后用“python myscript.py start”运行或停止或重新启动,进程ID将打印在屏幕上。在后台运行时,您需要将该脚本作为其他程序的一部分导入以对其进行查询,或者您始终可以在每次循环时将结果打印到临时文件,然后让其他程序查询那个临时文件。“有很多不同的方法可以做到这一点”

编辑:

从这样的东西开始并自定义,这实际上只是一种方法,我建议使用另一个库,如 psutil,而不是只在 linux 中使用的 ifconfig 的混乱解析:

“请务必更改接口,我使用的是 WLAN0,您可能使用的是不同的接口”

以下脚本将每 60 秒在屏幕上打印最后一分钟的平均 TX 和 RX 速率。

import os
import subprocess
import time
from daemon import runner
import datetime
import re 

class App():
    def __init__(self):
        self.stdin_path = '/dev/null'
        self.stdout_path = '/dev/tty'
        self.stderr_path = '/dev/tty'
        self.pidfile_path =  '/tmp/bandwidth_counter.pid'
        self.pidfile_timeout = 5
    def run(self):
        rx_megabits_new = 0
        tx_megabits_new = 0
        try:
                while True:
                        output = subprocess.Popen(['ifconfig', "wlan0"], stdout=subprocess.PIPE).communicate()[0]
                        rx_bytes = re.findall('RX bytes:([0-9]*) ', output)[0]
                        tx_bytes = re.findall('TX bytes:([0-9]*) ', output)[0]
                        rx_megabits = (((int(rx_bytes) * 8) / 1024) / 1024)
                        tx_megabits = (((int(tx_bytes) * 8) / 1024) / 1024)
                        current_rx_usage = rx_megabits - rx_megabits_new
                        current_tx_usage = tx_megabits - tx_megabits_new
                        rx_megabits_new = rx_megabits
                        tx_megabits_new = tx_megabits 
                        print 'average megabits received', current_rx_usage / 60
                        print 'average kilobits received', (current_rx_usage * 1024) / 60
                        print 'average megabits sent', current_tx_usage / 60
                        print 'average kilobits sent', (current_tx_usage * 1024) / 60
                        time.sleep(60)

        except Exception, e:
            raise


app = App()
daemon_runner = runner.DaemonRunner(app)
daemon_runner.do_action()

这同样适用于:“python myscript.py start”并停止并重新启动。您需要添加一些打开并写入的文件,而不是打印到屏幕上。我还建议您使用 gzip.open() 打开文件进行编写以节省一些空间,因为它们会迅速变大。

编辑:

这次是同一个守护进程写入文件 /tmp/netstats_counter.log,它是一个 csv,包含“1 分钟间隔内以 KB/s 为单位的 tx 速率,1 分钟间隔内以 KB/s 为单位的平均 rx 速率,unix 时间戳”

import os
import subprocess
import time
from daemon import runner
import datetime
import re 

class App():
    def __init__(self):
        self.stdin_path = '/dev/null'
        self.stdout_path = '/dev/tty'
        self.stderr_path = '/dev/tty'
        self.pidfile_path =  '/tmp/twitter_counter.pid'
        self.pidfile_timeout = 5
    def run(self):
        rx_megabits_new = 0
        tx_megabits_new = 0
        try:
                while True:
                        output_csv = open("/tmp/netstats_counter.log", 'a')
                        output = subprocess.Popen(['ifconfig', "wlan0"], stdout=subprocess.PIPE).communicate()[0]

                        rx_bytes = re.findall('RX bytes:([0-9]*) ', output)[0]
                        tx_bytes = re.findall('TX bytes:([0-9]*) ', output)[0]
                        rx_megabits = (((int(rx_bytes) * 8) / 1024) / 1024)
                        tx_megabits = (((int(tx_bytes) * 8) / 1024) / 1024)

                        current_rx_usage = (rx_megabits - rx_megabits_new) / 60
                        current_tx_usage = (tx_megabits - tx_megabits_new) / 60
                        current_rx_usage_kb = current_rx_usage * 1024
                        current_tx_usage_kb = current_tx_usage * 1024

                        rx_megabits_new = rx_megabits
                        tx_megabits_new = tx_megabits 

                        now = str(datetime.datetime.now())

                        col1 = str(current_tx_usage_kb) 
                        col2 = str(current_rx_usage_kb)
                        output_csv.write(col1)
                        output_csv.write(", ")
                        output_csv.write(col2)
                        output_csv.write(", ")
                        output_csv.write(now)
                        output_csv.write("\n")

                        output_csv.close( )


#                       print 'average megabits received', current_rx_usage / 60
#                       print 'average kilobits received', (current_rx_usage * 1024) / 60
#                       print 'average megabits sent', current_tx_usage / 60
#                       print 'average kilobits sent', (current_tx_usage * 1024) / 60


                        time.sleep(60)

        except Exception, e:
            raise


app = App()
daemon_runner = runner.DaemonRunner(app)
daemon_runner.do_action()
于 2012-05-23T04:53:16.520 回答