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