1
2
3
4
5
6
7
8
9
10
11 import sys
12 import re
13 import gobject
14 import gettext
15 from datetime import datetime
16 import commands
17 import time
18 import os
19 import subprocess
20 try:import poplib
21 except:pass
22
23
24 gettext.textdomain('screenlets')
25 gettext.bindtextdomain('screenlets', '/usr/share/locale')
26
28 return gettext.gettext(s)
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
46 """Calculates the system load."""
47 try:
48 data = commands.getoutput("cat /proc/stat")
49 tmp = data.split('\n')
50
51 except:
52 print _("Failed to open /proc/stat")
53 sys.exit(1)
54 if processor_number == 0 : sufix = ''
55 else: sufix = str(processor_number -1)
56 line = tmp[processor_number]
57
58 if line.startswith("cpu%s"% (sufix)):
59 cuse = float( line.split()[1] )
60 cn = float( line.split()[2] )
61 csys = float( line.split()[3])
62 if sufix == '':
63 load = cuse + cn
64 else:
65 load = cuse + csys + cn
66
67 return load
68 return None
69
71 try:
72 f = open("/proc/cpuinfo", "r")
73 tmp = f.readlines(500)
74 f.close()
75 except:
76 print _("Failed to open /proc/cpuinfo")
77 sys.exit(1)
78 list = []
79 for line in tmp:
80 if line.startswith("model name"):
81 return line.split(':')[1].strip()
82 return ''
83
85 try:
86 f = open("/proc/stat", "r")
87 tmp = f.readlines(2000)
88 f.close()
89 except:
90 print _("Failed to open /proc/stat")
91 sys.exit(1)
92 list = []
93 for line in tmp:
94 if line.startswith("cpu"):
95 list.append(line.split(' ')[0])
96
97 return list
98
100 try:
101 f = open("/proc/stat", "r")
102 tmp = f.readlines(2000)
103 f.close()
104 except:
105 print _("Failed to open /proc/stat")
106 sys.exit(1)
107 nb = 0
108 for line in tmp:
109 if line.startswith("cpu"):
110 nb = nb+1
111 return nb -1
112
113
114
115
116
117
118
119
120
122 """Get uptime using 'cat /proc/uptime'"""
123 data1 = commands.getoutput("cat /proc/uptime")
124 uptime = float( data1.split()[0] )
125 days = int( uptime / 60 / 60 / 24 )
126 uptime = uptime - days * 60 * 60 * 24
127 hours = int( uptime / 60 / 60 )
128 uptime = uptime - hours * 60 * 60
129 minutes = int( uptime / 60 )
130 return _("%s days, %s hours and %s minutes") % (str(days), str(hours), str(minutes))
131
132
134 try:
135 f = open("/proc/uptime", "r")
136 tmp = f.readlines(100)
137 f.close()
138 t = tmp[0].split()[0]
139 h = int(float(t)/3600)
140 m = int((float(t)-h*3600)/60)
141 if m < 10:
142 return str(h)+':'+'0'+str(m)
143 else:
144 return str(h)+':'+str(m)
145 except:
146 print _("Failed to open /proc/uptime")
147 return 'Error'
148
149
151 res = commands.getstatusoutput('whoami')
152 if res[0]==0:
153 return res[1].strip()
154 return ''
155
156
157
159 """Get user- and hostname and return user@hostname."""
160 hostname = commands.getoutput("hostname")
161 return hostname
162
163
164
166 """Get average load (as 3-tuple with floats)."""
167 data = commands.getoutput("cat /proc/loadavg")
168 load1 = str(float( data.split()[0] ))[:4]
169 load2 = str(float( data.split()[1] ))[:4]
170 load3 = str(float( data.split()[2] ))[:4]
171 return load1+ ','+ load2 +','+ load3
172
173
175 try:
176 f = open("/etc/issue", "r")
177 tmp = f.readlines(100)
178 f.close()
179 return tmp[0].replace('\\n','').replace('\l','').replace('\r','').strip()
180 except:
181 print _("Failed to open /etc/issue")
182 return 'Error'
183
184
186 """Get distro short name"""
187 distros = commands.getoutput("lsb_release -is")
188 return distros
189
191 """ shows kde or gnome or xface"""
192 if os.environ.get('KDE_FULL_SESSION') == 'true':
193 desktop_environment = 'kde'
194 elif os.environ.get('GNOME_DESKTOP_SESSION_ID'):
195 desktop_environment = 'gnome'
196 else:
197 try:
198 import commands
199 info = commands.getoutput('xprop -root _DT_SAVE_MODE')
200 if ' = "xfce4"' in info:
201 desktop_environment = 'xfce'
202 except (OSError, RuntimeError):
203 pass
204 return desktop_environment
205
207 res = commands.getstatusoutput('uname -r')
208 if res[0]==0:
209 return res[1].strip()
210 return _("Can't get kernel version")
211
213 res = commands.getstatusoutput('kde-config --version')
214 if res[0]==0:
215 lst = res[1].splitlines()
216 for i in lst:
217 if i.startswith('KDE:'):
218 return i[4:].strip()
219 return _("Can't get KDE version")
220
222 res = commands.getstatusoutput('gnome-about --gnome-version')
223 if res[0]==0:
224 lst = res[1].splitlines()
225 for i in lst:
226 if i.startswith('Version:'):
227 return i[8:].strip()
228 return _("Can't get Gnome version")
229
230
232 """Get linux version string."""
233 return commands.getoutput("cat /proc/version")
234
235
236
238 """Get cpu info from /proc/cpuinfo."""
239 return commands.getoutput("cat /proc/cpuinfo")
240
242 root = gtk.gdk.get_default_root_window()
243 try:
244 ident = root.property_get("_NET_SUPPORTING_WM_CHECK", "WINDOW")[2]
245 _WM_NAME_WIN = gtk.gdk.window_foreign_new(long(ident[0]))
246 except TypeError, exc:
247 _WM_NAME_WIN = ""
248
249 name = ""
250 win = _WM_NAME_WIN
251 if (win != None):
252 try:
253 name = win.property_get("_NET_WM_NAME")[2]
254 except TypeError, exc:
255
256 return name
257
258 return name
259
260
261
262
263
264
265
266
268 """Get free memory."""
269 cached = commands.getoutput("""cat /proc/meminfo | grep Cached | awk 'BEGIN {FS=":"} {print $2}' | awk '{print $1, $9}'""")
270 buffers = commands.getoutput("""cat /proc/meminfo | grep Buffers | awk 'BEGIN {FS=":"} {print $2}' | awk '{print $1, $9}'""")
271 free = commands.getoutput("""cat /proc/meminfo | grep MemFree | awk 'BEGIN {FS=":"} {print $2}' | awk '{print $1, $9}'""")
272 return int(cached.split()[0])/1024 + int(buffers)/1024 + int(free)/1024
273
274
276 """Get used memory."""
277 total = commands.getoutput("""cat /proc/meminfo | grep MemTotal | awk 'BEGIN {FS=":"} {print $2}' | awk '{print $1, $9}'""")
278 cached = commands.getoutput("""cat /proc/meminfo | grep Cached | awk 'BEGIN {FS=":"} {print $2}' | awk '{print $1, $9}'""")
279 buffers = commands.getoutput("""cat /proc/meminfo | grep Buffers | awk 'BEGIN {FS=":"} {print $2}' | awk '{print $1, $9}'""")
280 free = commands.getoutput("""cat /proc/meminfo | grep MemFree | awk 'BEGIN {FS=":"} {print $2}' | awk '{print $1, $9}'""")
281 return int(total)/1024 - int(cached.split()[0])/1024 - \
282 int(buffers)/1024 - int(free)/1024
283
285 try:
286 meminfo_file = open('/proc/meminfo')
287 meminfo = {}
288 for x in meminfo_file:
289 try:
290 (key,value,junk) = x.split(None, 2)
291 key = key[:-1]
292 meminfo[key] = int(value)
293 except:
294 pass
295 meminfo_file.close()
296 return int((100*(int(meminfo['MemTotal'])-int(meminfo['Cached']) - int(meminfo['Buffers']) - int(meminfo['MemFree'])))/int(meminfo['MemTotal']))
297 except:
298 print(_("Can't parse /proc/meminfo"))
299 return 0
300
302 try:
303 meminfo_file = open('/proc/meminfo')
304 meminfo = {}
305 for x in meminfo_file:
306 try:
307 (key,value,junk) = x.split(None, 2)
308 key = key[:-1]
309 meminfo[key] = int(value)
310 except:
311 pass
312 meminfo_file.close()
313 return int(meminfo['MemTotal'])/1024
314 except:
315 print("Can't parse /proc/meminfo")
316 return 0
317
319 try:
320 meminfo_file = open('/proc/meminfo')
321 meminfo = {}
322 for x in meminfo_file:
323 try:
324 (key,value,junk) = x.split(None, 2)
325 key = key[:-1]
326 meminfo[key] = int(value)
327 except:
328 pass
329 meminfo_file.close()
330 if(meminfo['SwapTotal']==0):
331 return 0
332 return int((100*(int(meminfo['SwapTotal'])-int(meminfo['SwapCached']) - int(meminfo['SwapFree'])))/int(meminfo['SwapTotal']))
333 except:
334 print("Can't parse /proc/meminfo")
335 return 0
336
338 try:
339 meminfo_file = open('/proc/meminfo')
340 meminfo = {}
341 for x in meminfo_file:
342 try:
343 (key,value,junk) = x.split(None, 2)
344 key = key[:-1]
345 meminfo[key] = int(value)
346 except:
347 pass
348 meminfo_file.close()
349 if(meminfo['SwapTotal']==0):
350 return 0
351 return int(meminfo['SwapTotal'])/1024
352 except:
353 print("Can't parse /proc/meminfo")
354 return 0
355
356
357
358
359
360
361
362
364 """Returns info about the given mount point (as dict)."""
365 proc = subprocess.Popen('df -h -a -P | grep ^/dev/ ', shell='true',
366 stdout=subprocess.PIPE)
367 sdevs = proc.stdout.read().rsplit('\n')
368 sdevs.pop()
369 for stdev in sdevs:
370 sdev = re.findall("(\S*)\s*", stdev)
371 dev = {
372 'device': sdev[0],
373 'size': sdev[1],
374 'used': sdev[2],
375 'free': sdev[3],
376 'quota': sdev[4],
377 'mount': sdev[5]
378 }
379 if dev['mount'] == mount_point:
380 return dev
381 return None
382
384 """Get a list of swap partitions."""
385 swap = commands.getoutput("cat /proc/swaps")
386 swap = str(swap.split()[5:])
387 swap = swap.replace("'","")
388 swap = swap.replace("[","")
389 swap = swap.replace("]","")
390 swap = swap.replace(",","")
391 return str(swap)
392
393
395 res = commands.getoutput('df -h -a -P').splitlines()
396 for i in res:
397 if i.startswith('/dev/'):
398 data = re.findall("(\S*)\s*", i)
399
400 if (data[5] == disk_disk) or (data[0] == disk_disk):
401 return data
402
404 disks = []
405 res = commands.getoutput('df -h -a -P').splitlines()
406 for i in res:
407 if i.startswith('/dev/'):
408 data = re.findall("(\S*)\s*", i)
409 disks.append(data[5])
410 return disks
411
412
413
414
415
416
417
418
420 """Returns ip if it can"""
421 ip = commands.getoutput("ifconfig")
422 x = 0
423 while True:
424 ip = ip[ip.find("inet addr:"):]
425 ip = ip[10:]
426 ipc = ip[:ip.find(chr(32))]
427 if ipc != '127.0.0.1' and ipc != None and ipc !='1':
428
429 return ipc
430
431
432 return _('Cannot get ip')
433
434
436 try:
437 f = open("/proc/net/dev", "r")
438 data = f.readlines(2000)
439 f.close()
440 newNetUp = 0
441 newNetDown = 0
442 for i in data:
443 if i.find(':') != -1 and i.strip().startswith('lo:') == False:
444 v = i.split(':')[1].split()
445 newNetUp = float( v[8] )+newNetUp
446 newNetDown = float( v[0] )+newNetDown
447
448
449 return (newNetUp/1024), (newNetDown/1024)
450 except:
451 print(_("Can't open /proc/net/dev"))
452 return 0,0
453
454
456 """This will return the total download and upload this session. As 2-tuple
457 with floats)."""
458 data = commands.getoutput("cat /proc/net/dev")
459 data = data[data.find(device + ":") + 5:]
460 return (float(data.split()[0]), float(data.split()[8]))
461
462
464 """This will return the number of connections."""
465 data = commands.getoutput("netstat -n | grep -c tcp")
466
467 return data
468
469
470
471
472
473
474
476 try:
477 interfaces = []
478 f = open("/proc/net/wireless")
479 cards = f.read(1024)
480 f.close()
481 for line in cards.splitlines():
482 colon = line.find(":")
483 if colon > 0:
484 interfaces.append(line[:colon].strip())
485 return interfaces
486 except:
487 print(_("Can't open /proc/net/wireless"))
488 return []
489
491 """Returns wireless stats as dict."""
492 stats = {}
493 iwcfd = os.popen("iwconfig " + interface)
494 iwconfig = iwcfd.read(1024)
495 iwcfd.close()
496 essid = iwconfig[iwconfig.find('ESSID:"')+7:]
497 stats['essid'] = essid[:essid.find('"')]
498 if stats['essid'].strip()[:stats['essid'].strip().find(" ")] == "unassociated":
499 return {"essid": _("Not connected"), "percentage": 0}
500 else:
501 bitrate = iwconfig[iwconfig.find("Bit Rate:")+9:]
502 stats['bitrate'] = bitrate[:bitrate.find(" ")]
503 quality = iwconfig[iwconfig.find("Link Quality=")+13:]
504 quality = quality[:quality.find(" ")]
505 if quality.find("/") > 0:
506 stats['quality'], stats['quality_max'] = quality.split("/")
507 else:
508 stats['quality'] = quality
509 try:
510 stats['percentage'] = int(float(stats['quality'])/float(stats['quality_max'])*100)
511 except:
512 return {"essid": _("Not connected"), "percentage": 0}
513 signal = iwconfig[iwconfig.find("Signal level=")+13:]
514 stats['signal'] = signal[:signal.find(" ")]
515 noise = iwconfig[iwconfig.find("Noise level=")+12:]
516 stats['noise'] = noise[:noise.find('\n')]
517 return stats
518
519
520
521
522
523
524
525
526
528 """Returns full now time and date"""
529 return str(datetime.now())
530
531
533 """returns date using local format"""
534 return str(datetime.now().strftime("%x"))
535
537 """returns date."""
538 return str(datetime.now().strftime("%d/%m/%Y"))
539
541 """returns time using local format"""
542 return str(datetime.now().strftime("%X"))
543
545 """returns time"""
546 return str(datetime.now().strftime("%H:%M:%S"))
547
549 """returns 24 hour time"""
550 return str(datetime.now().strftime("%R"))
551
553 """returns 12 hour time"""
554 return str(datetime.now().strftime("%r"))
555
557 """returns the years."""
558 return str(datetime.now().strftime("%Y"))
559
561 """returns the month"""
562 return str(datetime.now().strftime("%m"))
563
565 """returns the month name"""
566 return str(datetime.now().strftime("%B"))
567
569 """returns the day"""
570 return str(datetime.now().strftime("%d"))
571
573 """returns the number of the day of the week starting from monday"""
574 return str(datetime.now().strftime("%u"))
575
577 """returns the number of the day of the week starting from sonday"""
578 return str(datetime.now().strftime("%w"))
579
581 """returns the day name"""
582 return str(datetime.now().strftime("%A"))
583
585 """returns the hour"""
586 return str(datetime.now().strftime("%H"))
587
589 """returns the hour"""
590 return str(datetime.now().strftime("%H"))
591
593 """returns the hours"""
594 return str(datetime.now().strftime("%I"))
595
597 """returns minutes"""
598 return str(datetime.now().strftime("%M"))
599
601 """returns seconds"""
602 return str(datetime.now().strftime("%S"))
603
605 """return am/pm or None if not available"""
606 return str(datetime.now().strftime("%p"))
607
608
609
610
611
612
613
614
615
616
618 try:
619 path = "/proc/acpi/battery/"
620 files = os.listdir(path)
621 return files
622 except:
623 return[]
624
626 path = "/proc/acpi/battery/"+name+"/info"
627 try:
628 f = commands.getoutput('cat ' +path)
629 lines = f.split('\n')
630 total = 0
631 current = 0
632 full = 0
633 state = ''
634 present = True
635 for i in lines:
636 if i.startswith('present:') and i.find('yes')==-1:
637 present = False
638 elif i.startswith('design capacity:'):
639 total = int(i.split(':')[1].strip().split(' ')[0])
640 elif i.startswith('last full capacity:'):
641 full = int(i.split(':')[1].strip().split(' ')[0])
642 elif i.startswith('remaining capacity:'):
643 current = int(i.split(':')[1].strip().split(' ')[0])
644 elif i.startswith('charging state:'):
645 state = i.split(':')[1].strip().split(' ')[0]
646
647 path = "/proc/acpi/battery/"+name+"/state"
648 f = commands.getoutput('cat ' +path)
649 lines = f.split('\n')
650 for i in lines:
651 if i.startswith('present:') and i.find('yes')==-1:
652 present = False
653 elif i.startswith('design capacity:'):
654 total = int(i.split(':')[1].strip().split(' ')[0])
655 elif i.startswith('last full capacity:'):
656 full = int(i.split(':')[1].strip().split(' ')[0])
657 elif i.startswith('remaining capacity:'):
658 current = int(i.split(':')[1].strip().split(' ')[0])
659 elif i.startswith('charging state:'):
660 state = i.split(':')[1].strip().split(' ')[0]
661 return total, current, full, state, present
662 except:
663 return 0, 0, 0, '', False
664
666 return line.split(':')[1].strip().split(' ')[0]
667
668
670 data = commands.getoutput("acpi -V | grep AC | sed 's/.*: //'")
671 return data
672
673
674
675
676
677
678
679
681 res = commands.getoutput('ps -eo pcpu,pmem,comm --sort pcpu').splitlines()
682 l = res.__len__()
683 return res,l
684
686 res = commands.getoutput('ps axo comm,user,pcpu --sort=-pcpu | head -n 10')
687
688 return res
689
690
691
692
693
694
695
696
697
698
700 """This output the number of messages of mail box"""
701 f = os.popen("wget -qO - https://" + login + ":" + password + "@mail.google.com/mail/feed/atom")
702 a = f.read()
703 f.close()
704 match = re.search("<fullcount>([0-9]+)</fullcount>", a)
705 return match.group(1)
706
707
708
710
711 m = poplib.POP3(server)
712 m.user(login)
713 m.pass_(passwd)
714 out = m.stat()
715 m.quit()
716 num = out[0]
717 return num
718
719
720
721
722
723
724
725
727 res = commands.getstatusoutput('sensors')
728 output = ['Custom Sensors']
729 output.remove ('Custom Sensors')
730 if res[0]==0:
731 sol = res[1].replace(':\n ',': ').replace(':\n\t',': ').splitlines()
732 for i in sol:
733 i = i.strip()
734
735 if (i.find('temp')!= -1) or (i.find('Temp')!= -1) or (i.find(' V ')!= -1) or (i.find(' RPM ')!= -1):
736 output.append(i.lstrip())
737
738 res = commands.getstatusoutput(' nvidia-settings -q GPUAmbientTemp | grep :')
739 if res[0] == 0:
740 if res[1].strip().startswith('Attribute \'GPUAmbientTemp\''):
741 sol = res[1].splitlines()[0].split('):')[1].strip()
742 output.append('nvidia GPU ambiant: '+str(float(sol))+' C')
743 res = commands.getstatusoutput(' nvidia-settings -q GPUCoreTemp | grep :')
744 if res[0] == 0:
745 if res[1].strip().startswith('Attribute \'GPUCoreTemp\''):
746 sol = res[1].splitlines()[0].split('):')[1].strip()
747 output.append('nvidia GPU core: '+str(float(sol))+'C')
748
749
750
751 try:
752 path = "/proc/acpi/thermal_zone/"
753 files = os.listdir(path)
754 for entry in files:
755 try:
756 f = open(path+entry+'/temperature', "r")
757 tmp = f.readlines(200)
758 f.close()
759 val = tmp[0].replace('temperature:','').replace('C','').strip()
760 output.append('acpi temperature '+entry+': '+val+'C')
761 except:
762 print(_("Can't open %s/temperature") % path+entry)
763 except:
764 print(_("Can't open folder /proc/acpi/thermal_zone/"))
765
766
767 path = "/proc/acpi/ibm/thermal"
768 try:
769 f = open(path, "r")
770 tmp = f.readlines(200)
771 f.close()
772 lst = tmp[0].split(' ')
773 pos = 0
774 for i in lst:
775 i = i.strip()
776 if i != '' and i != '-128':
777 output.append('ibm temperature '+str(pos)+': '+i+'C')
778 pos = pos+1
779 except:
780 print(_("Can't open %s") % path)
781
782 path = "/proc/acpi/ibm/fan"
783 try:
784 f = open(path, "r")
785 tmp = f.readlines(200)
786 f.close()
787 for i in tmp:
788 if i.startswith('speed:'):
789 output.append('ibm fan: '+i.split(':')[1].strip()+' RPM')
790 except:
791 print(_("Can't open %s") % path)
792
793
794 res = commands.getstatusoutput("netcat 127.0.0.1 7634")
795 if res[0] != 0:
796 res = commands.getstatusoutput("nc 127.0.0.1 7634")
797 if res[0] == 0:
798 try:
799 hddtemp_data = res[1].lstrip('|').rstrip('|')
800 sol = hddtemp_data.split('||')
801 for i in sol:
802 if len(i)>1:
803 lst = i.split('|')
804 output.append("hddtemp sensor "+lst[0]+": "+lst[2]+" "+lst[3])
805 except:
806 print(_('Error during hddtemp drives search'))
807 else:
808 print(_('Hddtemp not installed'))
809 return output
810
811
813
814 if sensorName.startswith('nvidia GPU ambiant'):
815 res = commands.getstatusoutput(' nvidia-settings -q GPUAmbientTemp | grep :')
816 if res[0] == 0:
817 if res[1].strip().startswith('Attribute \'GPUAmbientTemp\''):
818
819 return str(float(res[1].splitlines()[0].split('):')[1].strip()))+'C'
820 elif sensorName.startswith('nvidia GPU core'):
821 res = commands.getstatusoutput(' nvidia-settings -q GPUCoreTemp | grep :')
822 if res[0] == 0:
823 if res[1].strip().startswith('Attribute \'GPUCoreTemp\''):
824
825 return str(float(res[1].splitlines()[0].split('):')[1].strip()))+'C'
826
827 elif sensorName.startswith('acpi temperature'):
828 name = sensorName.split()[2].strip()
829 path = "/proc/acpi/thermal_zone/"+name+"/temperature"
830 try:
831 f = open(path, "r")
832 tmp = f.readlines(200)
833 f.close()
834 val = tmp[0].replace('temperature:','').replace('C','').strip()
835
836 return val+'C'
837 except:
838 print(_("can't read temperature in: %s") % path)
839 return 'Error'
840
841 elif sensorName.startswith('ibm temperature'):
842 path = "/proc/acpi/ibm/thermal"
843 try:
844 name = sensorName
845 f = open(path, "r")
846 tmp = f.readlines(200)
847 f.close()
848 lst = tmp[0].split(' ')
849 val = int(sensorName.split(' ')[2])
850 return lst[val]+'C'
851 except:
852 print(_("Can't read value from %s") % path)
853 return 'None'
854
855 elif sensorName.startswith('ibm fan'):
856 path = "/proc/acpi/ibm/fan"
857 try:
858 name = sensorName
859 f = open(path, "r")
860 tmp = f.readlines(200)
861 f.close()
862 for i in tmp:
863 if i.startswith('speed:'):
864
865 return i.split(':')[1].strip()+' RPM'
866 return 'None'
867 except:
868 print(_("Can't read value from %s") % path)
869 return 'None'
870
871 elif sensorName.startswith('hddtemp sensor '):
872 res = commands.getstatusoutput("netcat 127.0.0.1 7634")
873 if res[0] != 0:
874 res = commands.getstatusoutput("nc 127.0.0.1 7634")
875 name = sensorName[15:]
876 if res[0] == 0:
877 hddtemp_data = res[1].lstrip('|').rstrip('|')
878 sol = hddtemp_data.split('||')
879 for i in sol:
880 if len(i)>1:
881 if i.startswith(name):
882 lst = i.split('|')
883 return lst[0]+": "+lst[2]+" "+lst[3]
884 else:
885 print(_('Hddtemp not installed'))
886 return ''
887
888
889
890
891 else:
892 res = commands.getstatusoutput('sensors')
893 if res[0] == 0:
894 sol = res[1].replace(':\n ',': ').replace(':\n\t',': ').splitlines()
895 for s in sol:
896 s.strip()
897 if s.startswith(sensorName):
898 try:
899 s = s.split(':')[1].strip(' ').strip('\t')
900 i = 0
901 while(((s[i]>='0') and (s[i]<='9')) or (s[i]=='.') or (s[i]=='+') or (s[i]=='-')):
902 i = i+1
903 return float(s[0:i])
904 except:
905 return 0
906
907
908
909
910
911
912
913
914
915
916
917
918
919 -class Sensor (gobject.GObject):
920 """A base class for deriving new Sensor-types from."""
921
922
923 __gsignals__ = dict( \
924 sensor_updated = (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, ()),
925 sensor_stopped = (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, ()) )
926
928 """Create a new sensor which updates after the given interval."""
929 gobject.GObject.__init__(self)
930 self._timeout_id = None
931 self._interval = interval
932
933 self.set_interval(interval)
934
935
936
938 """Get the update-interval time for this Sensor."""
939 return self._interval
940
942 """Set the update-interval time for this Sensor and start it."""
943 if self._timeout_id:
944 gobject.source_remove(self._timeout_id)
945 if ms and ms > 10:
946 self._interval = ms
947 self._timeout_id = gobject.timeout_add(ms, self.__timeout)
948 return True
949 return False
950
952 """Immediately stop this sensor and emit the "sensor_stopped"-signal."""
953 self.set_interval(0)
954 self.emit('sensor_stopped')
955
956
957
959 """Override this handler in subclasses to implement your calculations
960 and update the Sensor's attributes. Must return True to emit a signal
961 which can then be handled within the screenlets, returning False
962 causes the Sensor to be stopped.."""
963 return True
964
965
966
968 """The timeout function. Does nothing but calling the on_update
969 handler and emitting a signal if the handler returned True."""
970
971 if self.on_update():
972 self.emit('sensor_updated')
973 return True
974
975 self.stop()
976 return False
977
978
980 """A very simple CPU-sensor."""
981
982 - def __init__ (self, interval=1000, cpu=0):
983 """Create a new CPUSensor which emits an 'sensor_updated'-signal after a
984 given interval (default is 1000ms). The multi-cpu support is untested
985 but theoretically works :)."""
986 Sensor.__init__(self, interval)
987 self._load = 0
988 self._cpu = cpu
989
990
991
993 """Return the current CPU-load."""
994 return self._load
995
996
997
999 """Called on each interval. Calculates the CPU-load and updates the
1000 internal load-value."""
1001 try:
1002 f = open("/proc/stat", "r")
1003 tmp = f.readlines(200)
1004 f.close()
1005 except:
1006 print _("CPUSensor: Failed to open /proc/stat. Sensor stopped.")
1007 self.stop()
1008 line = tmp[self._cpu + 1]
1009 if line[0:5] == "cpu%i " % self._cpu:
1010 reg = re.compile('[0-9]+')
1011 load_values = reg.findall(line[5:])
1012
1013 cuse = int(load_values[0])
1014 csys = int(load_values[2])
1015 load = cuse + csys - old_cuse[0]
1016 if load < 0: load = 0
1017 if load > 99: load = 99
1018 self._load = load
1019 old_cuse[0] = cuse + csys
1020
1021 return True
1022 return False
1023
1024
1026
1028 """Create a new RAMSensor which emits an 'sensor_updated'-signal after a
1029 given interval (default is 1000ms)."""
1030 Sensor.__init__(self, interval)
1031 self._freemem = 0
1032 self._usedmem = 0
1033
1034
1035
1037 """Return the amount of currently free RAM."""
1038 return self._freemem
1039
1041 """Return the amount of currently used RAM."""
1042 return self._usedmem
1043
1044
1045
1047 """Called on each interval. Calculates the load and updates the
1048 internal values."""
1049 self._freemem = get_freemem()
1050 self._usedmem = get_usedmem()
1051 return True
1052
1053
1055
1056 - def __init__ (self, interval=1000, device='eth0'):
1057 """Create a new NetSensor which emits an 'sensor_updated'-signal after a
1058 given interval (default is 1000ms)."""
1059 Sensor.__init__(self, interval)
1060 self._device = device
1061 self._downloaded, self._uploaded = get_net_activity(device)
1062 self._last_down, self._last_up = self._downloaded, self._uploaded
1063
1064
1065
1067 """Return the current upload speed in b/s."""
1068 return self._uploaded - self._last_up
1069
1071 """Return the current download speed in b/s."""
1072 return self._downloaded - self._last_down
1073
1075 """Return the overall upload amount."""
1076 return self._uploaded
1077
1079 """Return the overall download amount."""
1080 return self._downloaded
1081
1082
1083
1085 """Called on each interval. Calculates the load and updates the
1086 internal values."""
1087 d, u = get_net_activity(self._device)
1088 self._last_up = self._uploaded
1089 self._last_down = self._downloaded
1090 self._downloaded = int(d)
1091 self._uploaded = int(u)
1092
1093 return True
1094
1095
1096
1097 if __name__ == '__main__':
1098
1099
1100 print get_hostname()
1101 print get_net_activity('eth0')
1102 print get_linux_version()
1103 print get_kernel()
1104 print get_cpu_info()
1105
1106
1116
1117
1118 cpu = CPUSensor()
1119 cpu.connect('sensor_updated', handle_cpusensor_updated)
1120 ram = MemorySensor(5000)
1121 ram.connect('sensor_updated', handle_ramsensor_updated)
1122 net = NetSensor(1500, 'eth0')
1123 net.connect('sensor_updated', handle_netsensor_updated)
1124
1125
1126 mainloop = gobject.MainLoop()
1127 mainloop.run()
1128