/
data.py
98 lines (87 loc) · 2.75 KB
/
data.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
# Author: Alessandro Zanni
# URL: https://github.com/AleDanish
import psutil
import time
import subprocess
import re
folder="metrics/"
cpu_file="cpu_perc.csv"
memory_file="memory_perc.csv"
disk_file="disk.csv"
io_file="io.csv"
def cpu(pid, ps_name):
'''This method returns the current CPU usage in %'''
cmd="top -p "+pid.strip()+" -b -n 1 | grep -w "+ps_name+" | awk '{print $9}'"
output=subprocess.check_output(["sh", "-c", cmd])
value = re.sub(',', '.', output.strip())
writefile(cpu_file, value, "a")
try:
return "%4.2f" %float(value)
except ValueError:
return "0"
def cpu_sys(pid):
'''This method returns the current CPU usage by the system'''
a=psutil.Process(int(pid)).cpu_times().system
return "%4.2f" %a
def cpu_user(pid):
'''This method returns the current CPU usage by the user'''
a=psutil.Process(int(pid)).cpu_times().user
return "%4.2f" %a
def mem(pid, ps_name):
'''This method returns the current RAM usage in %'''
#a=psutil.virtual_memory().total
cmd="top -p "+pid.strip()+" -b -n 1 | grep -w "+ps_name+" | awk '{print $10}'"
output=subprocess.check_output(["sh", "-c", cmd])
value = re.sub(',', '.', output.strip())
writefile(memory_file, value, "a")
try:
return "%4.2f" %float(value)
except:
return "0"
def dsk():
'''This method returns the current DISK usage'''
a=psutil.disk_partitions()
b=[]
x=0
y=0
for i in range (0,len(a)):
b.append(a[i][1])
x+=psutil.disk_usage(b[i])[0]
y+=psutil.disk_usage(b[i])[1]
z=float(y)/float(x)*100
return "%2.2f" %z
def disk():
'''This method returns the current DISK READ/WRITE speed in KB/S'''
cmd="dstat -d 1 1 | awk '{print $1} {print $2}'"
output=subprocess.check_output(["sudo", "sh", "-c", cmd])
out=output.split('\n')[-3:-1]
valueR=formatResult(out[0])
valueS=formatResult(out[1])
value=valueR+valueS
writefile(disk_file, value, "a")
return "%4.2f" %float(value)
def io():
'''This method returns the current I/O usage in KB/S'''
# Sent/Received
cmd="dstat -n 1 1 | awk '{print $1} {print $2}'"
output=subprocess.check_output(["sh", "-c", cmd])
out=output.split('\n')[-3:-1]
valueR=formatResult(out[0])
valueS=formatResult(out[1])
value=valueR+valueS
writefile(io_file, value, "a")
return "%4.2f" %float(value)
def writefile(file_name, data, options):
with open(folder+file_name, options) as myfile:
myfile.write(str(data)+";")
def formatResult(out):
if out=='0':
return int(out)
else:
value=int(out[:-1])
unit=out[-1:]
if unit=='B':
value=value/1000
elif unit=='M':
value=value*1000
return value