net.py get input and output of network interface
Copy Code code as follows:
#!/usr/bin/env Python
Import time
Import Sys
If Len (SYS.ARGV) > 1:
INTERFACE = sys.argv[1]
Else
INTERFACE = ' eth0 '
STATS = []
print ' Interface: ', Interface
Def RX ():
Ifstat = open ('/proc/net/dev '). ReadLines ()
For interface in Ifstat:
If INTERFACE in INTERFACE:
Stat = float (Interface.split () [1])
Stats[0:] = [stat]
DEF TX ():
Ifstat = open ('/proc/net/dev '). ReadLines ()
For interface in Ifstat:
If INTERFACE in INTERFACE:
Stat = float (Interface.split () [9])
Stats[1:] = [stat]
print ' in Out '
Rx ()
TX ()
While True:
Time.sleep (1)
Rxstat_o = List (STATS)
Rx ()
TX ()
RX = float (stats[0])
Rx_o = rxstat_o[0]
TX = float (stats[1])
Tx_o = rxstat_o[1]
Rx_rate = Round ((rx-rx_o)/1024/1024,3)
Tx_rate = Round ((tx-tx_o)/1024/1024,3)
Print rx_rate, ' MB ', tx_rate, ' MB '
A simple illustration of Listing 4: Listing 4 reads the information in/proc/net/dev, and the file operation in Python can be done through the open function, which is indeed much like the fopen in the C language. Get a file object by using the Open function, and then call Read (), write (), and so on to read and write files. In addition Python is easy to read the contents of a text file into a string variable that can be manipulated. The file object provides three "read" Methods: Read (), ReadLine (), and ReadLines (). Each method can accept a variable to limit the amount of data read at a time, but they usually do not use a variable. read () reads the entire file at a time, and is typically used to place the contents of the file in a string variable. however. Read () generates the most direct string representation of a file's content, but it is unnecessary for sequential row-oriented processing, and is not possible if the file is larger than available memory. The difference between ReadLine () and. ReadLines () is the latter reading the entire file at a time , like. Read (). ReadLines () automatically parse the contents of a file into a list of rows, which can be made up of Python's for ... in ... Structure for processing. On the other hand,. ReadLine () reads only one row at a time, usually much slower than. ReadLines (). You should use the. ReadLine () only if there is not enough memory to read the entire file at once. The final listing 4 prints out the input and output of the network interface.
You can run the script using the Python command net.py results are shown in Figure 4