1 from subprocess
import Popen
, PIPE
2 from datetime
import datetime
9 def __init__(self
, args
):
13 line_regex
= re
.compile('\s*(?P<in>\d+)\s*/\s*(?P<out>\d+)\s*--\s*(?P<proc>.*)')
15 proc
= Popen(self
.args
, stdin
=PIPE
, stdout
=PIPE
, stderr
=PIPE
, bufsize
=1)
16 records
= collections
.defaultdict(list)
18 for line
in proc
.stdout
:
20 record
= self
.get_record(line
)
25 records
[process
].append(record
)
27 if len(records
[process
]) > 1:
28 prev_record
= records
[process
][-2]
29 bw
= self
.get_bandwidth(prev_record
, record
)
34 match
= line_regex
.match(line
)
39 process
= match
.group('proc').strip()
40 bytes_in
= int(match
.group('in'))
41 bytes_out
= int(match
.group('out'))
42 record
= {'timestamp': datetime
.now(), 'in': bytes_in
, 'out': bytes_out
}
45 def get_bandwidth(rec1
, rec2
):
47 returns the mean incoming and outgoing bandwidth used between
48 the two given records.
50 rec1 represents the earlier, rec2 the later record
52 date_diff
= rec2
['timestamp'] - rec1
['timestamp']
53 in_diff
= rec2
['in'] - rec1
['diff']
54 out_diff
= rec2
['out'] - rec1
['out']
56 in_bw
= in_diff
/ date_diff
.seconds
57 out_bw
= out_diff
/ date_diff
.seconds
59 return (in_bw
, out_bw
)