Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7976863
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 4, 20262026-06-04T09:01:36+00:00 2026-06-04T09:01:36+00:00

I’m new to python and I need to calculate the ‘average speed’ of my

  • 0

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()
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-04T09:01:38+00:00Added an answer on June 4, 2026 at 9:01 am

    Take your main() and get_network_bytes() and wrap them in a python process:

    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()
    

    Then run with “python myscript.py start” or stop or restart, the process ID will be printed on the screen. With this running in the background you’ll need to import that script as part of your other program to query it, or you can always have your result print to a temp file each time it loops and then have your other program(s) query that temp file. “There’s a number of different ways to do this”

    Edit:

    Start with something like this and customize, this is really only one way to go about it, I would suggest another library like psutil rather then messy parsing of ifconfig which only works in linux:

    “Make sure to change the interface, I’m using WLAN0 you may be using something different”

    The following script will print out to the screen every 60 seconds the average TX and RX rates for that last minute.

    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()
    

    Again this works with: “python myscript.py start” and stop and restart. You’ll want to add some file open and write rather then print to the screen. I would also suggest that you open your files for writing with gzip.open() to save some space as they will grow large quickly.

    Edit:

    Here’s the same daemon this time writing to a file /tmp/netstats_counter.log which is a csv containing “tx rate in KB/s over 1 minute intervals, average rx rate in KB/s over 1 minute intervals, unix timestamp”

    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()
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a string like this: La Torre Eiffel paragonata all’Everest What PHP function
I'm new to using the Perl treebuilder module for HTML parsing and can't figure
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I would like to count the length of a string with PHP. The string
For some reason, after submitting a string like this Jack’s Spindle from a text
I've got a string that has curly quotes in it. I'd like to replace
I want use html5's new tag to play a wav file (currently only supported
I am trying to render a haml file in a javascript response like so:
I would like to run a str_replace or preg_replace which looks for certain words
In my XML file chapters tag has more chapter tag.i need to display chapters

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.