1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 import screenlets
17 import sys
18 import re
19 import gobject
20 import gettext
21 from datetime import datetime
22 import commands
23 import time
24 import os
25 import subprocess
26 import multiprocessing
27 import gtk
28 import socket
29
30 gettext.textdomain('screenlets')
31 gettext.bindtextdomain('screenlets', screenlets.INSTALL_PREFIX + '/share/locale')
32
34 return gettext.gettext(s)
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
52 """Calculates the system load. Processor nr 0 is the average of all processors."""
53 f = open("/proc/stat", "r")
54 tmp = f.readlines(2000)
55 f.close()
56
57 if processor_number == 0 :
58 suffix = ''
59 else:
60 suffix = str(processor_number - 1)
61 line = tmp[processor_number]
62
63 if line.startswith("cpu%s "% (suffix)):
64 (junk, cuse, cn, csys, tail) = line.split(None, 4)
65 if suffix == '':
66 return (int(cuse) + int(csys) + int(cn)) / multiprocessing.cpu_count()
67 else:
68 return int(cuse) + int(cn)
69 return None
70
72 """Returns Cpu Name"""
73 try:
74 f = open("/proc/cpuinfo", "r")
75 tmp = f.readlines(500)
76 f.close()
77 except:
78 print "Failed to open /proc/cpuinfo"
79 return None
80 list = []
81 for line in tmp:
82 if line.startswith("model name"):
83 return line.split(':')[1].strip()
84 return ''
85
87 """Returns Cpu List"""
88 try:
89 f = open("/proc/stat", "r")
90 tmp = f.readlines(2000)
91 f.close()
92 except:
93 print "Failed to open /proc/stat"
94 return None
95 list = []
96 for line in tmp:
97 if line.startswith("cpu"):
98 list.append(line.split(' ')[0])
99
100 return list
101
103 """Returns Cpu Number"""
104 try:
105 f = open("/proc/stat", "r")
106 tmp = f.readlines(2000)
107 f.close()
108 except:
109 print "Failed to open /proc/stat"
110 return None
111 nb = -1
112 for line in tmp:
113 if line.startswith("cpu"):
114 nb = nb+1
115 return nb
116
118 """Returns Cpu frequency"""
119 op = commands.getoutput('cat /proc/cpuinfo | grep "cpu MHz"')
120 try:
121 op = int(op.replace(" ","").split(':')[1].split('\n')[0].replace(".",""))
122 return op
123 except: return None
124
126 """Returns Cpu governator"""
127 try:
128 op = commands.getoutput('cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor').strip()
129 return op
130 except: return None
131
133 """Returns available frequencies"""
134 try:
135 afreqsh = open("/sys/devices/system/cpu/cpu0/cpufreq/scaling_available_frequencies", "r")
136 op = afreqsh.readline().strip().split(' ')
137 afreqsh.close()
138 return op
139 except:
140 return None
141
143 """Returns available governators"""
144 try:
145 afreqsh = open("/sys/devices/system/cpu/cpu0/cpufreq/scaling_available_governors", "r")
146 op = afreqsh.readline().strip().split(' ')
147 afreqsh.close()
148 return op
149 except:
150 return None
151
152
153
154
155
156
157
158
160 """Returns uptime extended version"""
161 try:
162 f = open("/proc/uptime", "r")
163 data1 = f.readline(100)
164 f.close()
165 uptime = float( data1.split()[0] )
166 days = int( uptime / 60 / 60 / 24 )
167 uptime = uptime - days * 60 * 60 * 24
168 hours = int( uptime / 60 / 60 )
169 uptime = uptime - hours * 60 * 60
170 minutes = int( uptime / 60 )
171 return _("%(days)s days, %(hours)s hours and %(minutes)s minutes") % {"days":str(days), "hours":str(hours), "minutes":str(minutes)}
172
173 except:
174 print "Failed to open /proc/uptime"
175 return 'Error'
176
178 """Returns uptime"""
179 try:
180 f = open("/proc/uptime", "r")
181 tmp = f.readline(100)
182 f.close()
183 t = tmp.split()[0]
184 h = int(float(t)/3600)
185 m = int((float(t)-h*3600)/60)
186 if m < 10:
187 return str(h)+':'+'0'+str(m)
188 else:
189 return str(h)+':'+str(m)
190 except:
191 print "Failed to open /proc/uptime"
192 return 'Error'
193
194
196 """Returns username"""
197 return os.environ.get("USER")
198
200 """Get hostname"""
201 return socket.gethostname()
202
203
205 """Get average load (as comma-separated string)"""
206 f = open("/proc/loadavg", "r")
207 data = f.readline(100)
208 f.close()
209 data = data.rsplit(' ', 2)[0]
210 data = data.replace(' ', ',')
211 return data
212
214 try:
215 if os.path.exists('/etc/debian_version') and str(commands.getoutput('cat /etc/lsb-release')).lower().find('ubuntu') != -1:
216 return str(commands.getoutput('cat /etc/issue')).replace('\\n','').replace('\l','').replace('\r','').strip()
217 elif os.path.exists('/etc/pld-release'):
218 return str(commands.getoutput('cat /etc/pld-release'))
219 elif os.path.exists('/etc/debian_version'):
220 return 'Debian ' + str(commands.getoutput('cat /etc/debian_version'))
221 elif os.path.exists('/etc/mandriva-release'):
222 return 'Mandriva ' + str(commands.getoutput("cat /etc/mandriva-release | sed -e 's/[A-Za-z ]* release //'"))
223 elif os.path.exists('/etc/fedora-release'):
224 return 'Fedora ' + str(commands.getoutput("cat /etc/fedora-release | sed -e 's/[A-Za-z ]* release //'"))
225 elif os.path.exists('/etc/SuSE-release'):
226
227 if str(commands.getoutput('cat /etc/SuSE-release')).lower().find('openSUSE') != -1:
228 return 'openSUSE ' + str(commands.getoutput("""cat /etc/SuSE-release | grep "VERSION" | sed -e 's/VERSION = //'"""))
229 else:
230 return 'SUSE ' + str(commands.getoutput("""cat /etc/SuSE-release | grep "VERSION" | sed -e 's/VERSION = //'"""))
231 elif os.path.exists('/etc/gentoo-release'):
232 return 'Gentoo ' + str(commands.getoutput("cat /etc/gentoo-release | sed -e 's/[A-Za-z ]* release //'"))
233 elif os.path.exists('/etc/slackware-version'):
234 return 'Slackware ' + str(commands.getoutput("cat /etc/slackware-version | sed -e 's/Slackware //'"))
235 elif os.path.exists('/etc/arch-release'):
236 return 'Arch Linux'
237 elif os.path.exists('/etc/redhat-release'):
238 return 'Redhat ' + str(commands.getoutput("cat /etc/redhat-release | sed -e 's/[A-Za-z ]* release //'"))
239 else:
240 f = open("/etc/issue", "r")
241 tmp = f.readlines(100)
242 f.close()
243 return tmp[0].replace('\\n','').replace('\l','').replace('\r','').strip()
244 except:
245 print "Error getting distro name"
246 return 'Error'
247
248
250 """Get distro short name"""
251 distros = commands.getoutput("lsb_release -is")
252 return distros
253
255 """ shows kde or gnome or xface"""
256 if os.environ.get('KDE_FULL_SESSION') == 'true':
257 desktop_environment = 'kde'
258 elif os.environ.get('GNOME_DESKTOP_SESSION_ID'):
259 desktop_environment = 'gnome'
260 else:
261 try:
262 import commands
263 info = commands.getoutput('xprop -root _DT_SAVE_MODE')
264 if ' = "xfce4"' in info:
265 desktop_environment = 'xfce'
266 except (OSError, RuntimeError):
267 pass
268 return desktop_environment
269
271 """Returns kernel version"""
272 return os.uname()[2]
273
275 """Returns kde version"""
276 res = commands.getstatusoutput('kde-config --version')
277 if res[0]==0:
278 lst = res[1].splitlines()
279 for i in lst:
280 if i.startswith('KDE:'):
281 return i[4:].strip()
282 return _("Can't get KDE version")
283
285 """Returns gnome version"""
286 res = commands.getstatusoutput('gnome-about --gnome-version')
287 if res[0]==0:
288 lst = res[1].splitlines()
289 for i in lst:
290 if i.startswith('Version:'):
291 return i[8:].strip()
292 return _("Can't get Gnome version")
293
295 """Get linux version string."""
296 return ' '.join(os.uname())
297
298
300 """Get cpu info from /proc/cpuinfo."""
301 return open('/proc/cpuinfo').read()
302
304 """Returns window manager name"""
305 root = gtk.gdk.get_default_root_window()
306 try:
307 ident = root.property_get("_NET_SUPPORTING_WM_CHECK", "WINDOW")[2]
308 _WM_NAME_WIN = gtk.gdk.window_foreign_new(long(ident[0]))
309 except TypeError, exc:
310 _WM_NAME_WIN = ""
311
312 name = ""
313 win = _WM_NAME_WIN
314 if (win != None):
315 try:
316 name = win.property_get("_NET_WM_NAME")[2]
317 except TypeError, exc:
318
319 return name
320
321 return name
322
323
324
325
326
327
328
329
331 """Helper function for mem_get_* functions"""
332 meminfo_file = open('/proc/meminfo')
333 meminfo = {}
334 for l in meminfo_file:
335 if l.startswith('MemTotal') or l.startswith('MemFree') or l.startswith('Cached') or l.startswith('Buffers'):
336 c = l.index(':')
337 e = l.index('kB')
338 meminfo[l[:c]] = int(l[c+1:e])
339 if len(meminfo) >= 4:
340 break
341 meminfo_file.close()
342 return meminfo
343
344
346 """Get free memory."""
347 meminfo = _get_meminfo()
348 return (meminfo['Cached'] + meminfo['Buffers'] + meminfo['MemFree']) / 1024
349
350
352 """Get used memory."""
353 meminfo = _get_meminfo()
354 return (meminfo['MemTotal'] - meminfo['Cached'] - meminfo['Buffers'] - meminfo['MemFree']) / 1024
355
357 """Returns memory usage"""
358 meminfo = _get_meminfo()
359 return int(round((100*(meminfo['MemTotal'] - meminfo['Cached'] - meminfo['Buffers'] - meminfo['MemFree']) / meminfo['MemTotal'] )))
360
362 meminfo = _get_meminfo()['MemTotal'] / 1024
363 return meminfo
364
366 """Helper function for mem_get_*swap functions"""
367 meminfo_file = open('/proc/meminfo')
368 meminfo = {}
369 for l in meminfo_file:
370 if l.startswith('SwapTotal') or l.startswith('SwapFree') or l.startswith('SwapCached'):
371 c = l.index(':')
372 e = l.index('kB')
373 meminfo[l[:c]] = int(l[c+1:e])
374 if len(meminfo) >= 3:
375 break
376 meminfo_file.close()
377 return meminfo
378
380 """Returns used swap"""
381 swapinfo = _get_swapinfo()
382 if(swapinfo['SwapTotal']==0):
383 return 0
384 return int(round((100*(swapinfo['SwapTotal'] - swapinfo['SwapCached'] - swapinfo['SwapFree']) / swapinfo['SwapTotal'] )))
385
386
388 """Returns total swap"""
389 swapinfo = _get_swapinfo()
390 if(swapinfo['SwapTotal']==0):
391 return 0
392 return swapinfo['SwapTotal']/1024
393
394
395
396
397
398
399
400
401
403 """Returns info about the given mount point (as dict)."""
404 proc = subprocess.Popen('df -h -a -P | grep ^/dev/ ', shell='true',
405 stdout=subprocess.PIPE)
406 sdevs = proc.stdout.read().rsplit('\n')
407 sdevs.pop()
408 for stdev in sdevs:
409 sdev = re.findall("(\S*)\s*", stdev)
410 dev = {
411 'device': sdev[0],
412 'size': sdev[1],
413 'used': sdev[2],
414 'free': sdev[3],
415 'quota': sdev[4],
416 'mount': sdev[5]
417 }
418 if dev['mount'] == mount_point:
419 return dev
420 return None
421
423 """Get a list of swap partitions."""
424 try:
425 f = open("/proc/swaps", "r")
426 swap = f.read()
427 f.close()
428 swap = str(swap.split()[5:])
429 swap = swap.replace("'","")
430 swap = swap.replace("[","")
431 swap = swap.replace("]","")
432 swap = swap.replace(",","")
433 return str(swap)
434 except:
435 print "Failed to open /proc/swaps"
436 return 'Error'
437
439 """Returns disk usage"""
440 res = commands.getoutput('df -h -a -P').splitlines()
441 for i in res:
442 if i.startswith('/dev/'):
443 data = re.findall("(\S*)\s*", i)
444
445 if (data[5] == disk_disk) or (data[0] == disk_disk):
446 return data
447
449 """Returns disk list"""
450 disks = []
451 res = commands.getoutput('df -h -a -P').splitlines()
452 for i in res:
453 if i.startswith('/dev/'):
454 data = re.findall("(\S*)\s*", i)
455 disks.append(data[5])
456 return disks
457
458
459
460
461
462
463
464
466 """Returns ip if it can"""
467 command = 'ifconfig'
468 command_path=os.popen("whereis -b "+command+" | sed 's/"+command+": //g'").readlines()
469 command_string = ''.join(command_path)[:-1]
470 ip = commands.getoutput("LANG=\"\" "+command_string)
471 while True:
472 ip = ip[ip.find("inet "):]
473 if len(ip) < 7:
474 break
475 ip = ip[ip.find(":")+1:]
476 ipc = ip[:ip.find(" ")]
477 if ipc != '127.0.0.1' and ipc != None and ipc !='1':
478 return ipc
479
480 return _('Cannot get ip')
481
482
484 """Returns upload and download"""
485 try:
486 f = open("/proc/net/dev", "r")
487 data = f.readlines(2000)
488 f.close()
489 newNetUp = 0
490 newNetDown = 0
491 for i in data:
492 if i.find(':') != -1 and i.strip().startswith('lo:') == False:
493 v = i.split(':')[1].split()
494 newNetUp = float( v[8] )+newNetUp
495 newNetDown = float( v[0] )+newNetDown
496
497
498 return (newNetUp/1024), (newNetDown/1024)
499 except:
500 print("Can't open /proc/net/dev")
501 return 0,0
502
503
505 """This will return the total download and upload this
506 session, as a 2-tuple with floats."""
507 prefix = '%6s:' % device
508 net = open('/proc/net/dev')
509 for line in net:
510 if line.startswith(prefix):
511 data = line[7:].split()
512 net.close()
513 return (float(data[0]), float(data[8]))
514
515
517 """This will return the number of connections."""
518 data = commands.getoutput("netstat -n | grep -c tcp")
519
520 return data
521
522
523
524
525
526
527
529 """Returns wireless interfaces"""
530 try:
531 interfaces = []
532 f = open("/proc/net/wireless")
533 cards = f.read(1024)
534 f.close()
535 for line in cards.splitlines():
536 colon = line.find(":")
537 if colon > 0:
538 interfaces.append(line[:colon].strip())
539 return interfaces
540 except:
541 print("Can't open /proc/net/wireless")
542 return []
543
546
548 """Returns wireless stats as dict."""
549 stats = {}
550
551 command = 'iwconfig'
552
553 command_path=os.popen("whereis -b "+command+" | sed 's/"+command+": //g'").readlines()
554
555 command_string = ''.join(command_path)[:-1] + ' ' + interface
556 iwcfd = os.popen(command_string)
557 iwconfig = iwcfd.read(1024)
558 iwcfd.close()
559
560
561 command = 'ifconfig'
562 command_path=os.popen("whereis -b "+command+" | sed 's/"+command+": //g'").readlines()
563 command_string = ''.join(command_path)[:-1] + ' ' + interface
564
565 ip = commands.getoutput("LANG=\"\" "+command_string)
566 ip = ip[ip.find("inet"):]
567 ip = ip[ip.find(":")+1:]
568 ip = ip[:ip.find(" ")]
569 stats['local_ip'] = ip
570
571 essid = iwconfig[iwconfig.find('ESSID:"')+7:]
572 stats['essid'] = essid[:essid.find('"')]
573 if stats['essid'].strip()[:stats['essid'].strip().find(" ")] == "unassociated":
574 return {"essid": _("Not connected"), "percentage": 0}
575 else:
576 bitrate = iwconfig[iwconfig.find("Bit Rate:")+9:]
577 stats['bitrate'] = bitrate[:bitrate.find(" ")]
578 quality = iwconfig[iwconfig.find("Link Quality")+13:]
579 quality = quality[:quality.find(" ")]
580 if quality.find("/") > 0:
581 stats['quality'], stats['quality_max'] = quality.split("/")
582 else:
583 stats['quality'] = quality
584 try:
585 stats['percentage'] = int(float(stats['quality'])/float(stats['quality_max'])*100)
586 except:
587 return {"essid": _("Not connected"), "percentage": 0}
588 signal = iwconfig[iwconfig.find("Signal level")+13:]
589 stats['signal'] = signal[:signal.find(" ")]
590 noise = iwconfig[iwconfig.find("Noise level")+12:]
591 stats['noise'] = noise[:noise.find('\n')]
592 return stats
593
594
595
596
597
598
599
600
601
603 """Returns full now time and date"""
604 return str(datetime.now())
605
606
608 """returns date using local format"""
609 return str(datetime.now().strftime("%x"))
610
612 """returns date."""
613 return str(datetime.now().strftime("%d/%m/%Y"))
614
616 """returns time using local format"""
617 return str(datetime.now().strftime("%X"))
618
620 """returns time"""
621 return str(datetime.now().strftime("%H:%M:%S"))
622
624 """returns 24 hour time"""
625 return str(datetime.now().strftime("%R"))
626
628 """returns 12 hour time"""
629 return str(datetime.now().strftime("%r"))
630
632 """returns the years."""
633 return str(datetime.now().strftime("%Y"))
634
636 """returns the month"""
637 return str(datetime.now().strftime("%m"))
638
640 """returns the month name"""
641 return str(datetime.now().strftime("%B"))
642
644 """returns the day"""
645 return str(datetime.now().strftime("%d"))
646
648 """returns the number of the day of the week starting from monday"""
649 return str(datetime.now().strftime("%u"))
650
652 """returns the number of the day of the week starting from sonday"""
653 return str(datetime.now().strftime("%w"))
654
656 """returns the day name"""
657 return str(datetime.now().strftime("%A"))
658
660 """returns the hour"""
661 return str(datetime.now().strftime("%H"))
662
664 """returns the hour"""
665 return str(datetime.now().strftime("%H"))
666
668 """returns the hours"""
669 return str(datetime.now().strftime("%I"))
670
672 """returns minutes"""
673 return str(datetime.now().strftime("%M"))
674
676 """returns seconds"""
677 return str(datetime.now().strftime("%S"))
678
680 """return am/pm or None if not available"""
681 return str(datetime.now().strftime("%p"))
682
683
684
685
686
687
688
689
690
691
693 """Returns battery list"""
694 try:
695 path = "/proc/acpi/battery/"
696 files = os.listdir(path)
697 return files
698 except:
699 return[]
700
702 """Returns battery data"""
703 path = "/proc/acpi/battery/"+name+"/info"
704 try:
705 f = open(path)
706 data = f.readlines()
707 f.close()
708 total = 0
709 current = 0
710 full = 0
711 rate = 0
712 state = ''
713 present = True
714 for line in data:
715 if line.startswith('present:') and line.find('yes')==-1:
716 present = False
717 elif line.startswith('design capacity:'):
718 total = int(line.split(':')[1].strip().split(' ')[0])
719 elif line.startswith('last full capacity:'):
720 full = int(line.split(':')[1].strip().split(' ')[0])
721 path = "/proc/acpi/battery/"+name+"/state"
722 f = open(path)
723 data = f.readlines()
724 f.close()
725 for line in data:
726 if line.startswith('present:') and line.find('yes')==-1:
727 present = False
728 elif line.startswith('remaining capacity:'):
729 current = int(line.split(':')[1].strip().split(' ')[0])
730 elif line.startswith('charging state:'):
731 state = line.split(':')[1].strip().split(' ')[0]
732 elif line.startswith('present rate:'):
733 rate = line.split(':')[1].strip().split(' ')[0]
734 return total, current, full, state, present, rate
735 except:
736 return 0, 0, 0, '', False, 0
737
739 """Returns battery value"""
740 return line.split(':')[1].strip().split(' ')[0]
741
742
744 """Returns battery ac"""
745 data = commands.getoutput("acpi -V | grep AC | sed 's/.*: //'")
746 return data
747
748
749
750
751
752
753
754
756 """Returns process list"""
757 res = commands.getoutput('ps -eo pcpu,pmem,comm --sort pcpu').splitlines()
758 l = res.__len__()
759 return res,l
760
762 """Returns top list"""
763 res = commands.getoutput('ps axo comm,user,pcpu --sort=-pcpu | head -n 10')
764
765 return res
766
767
768
769
770
771
772
773
774
775
777 """return GPU Type to its caller"""
778 output = commands.getoutput("nvidia-settings -q Gpus | cut -d '(' -f 2 -s | cut -d ')' -f 1")
779 return output
780
781
782
784 """return GPU Ram size in MB to its caller"""
785 output = commands.getoutput("nvidia-settings -q VideoRam | cut -d ':' -f 3 -s | cut -d ' ' -f 2 | cut -d '.' -f 1")
786 return str(int(output)/1024) + " MB"
787
788
790 """return current GPU Driver version to its caller"""
791 output = commands.getoutput("nvidia-settings -q NvidiaDriverVersion | cut -d ':' -f 3 -s | cut -d ' ' -f 2")
792 return output
793
794
796 """return current screen resolution to its caller"""
797 output = commands.getoutput("nvidia-settings -q FrontendResolution")
798 return output[74:83].replace(",", "x")
799
800
802 """return current refreshrate to its caller"""
803 output = commands.getoutput("nvidia-settings -q RefreshRate | cut -d ':' -f 4 -s | cut -d ' ' -f 2 | cut -d ',' -f 1")
804 return str(int(output)) + " Hz"
805
806
808 """return current GPU Clock Frequency to its caller"""
809 output = commands.getoutput("nvidia-settings -q gpuperfmodes | cut -d '=' -f 3 | cut -d ',' -f 1 -s")
810 return str(output) + " MHz"
811
813 """return current GPU Memory Clock Frequency to its caller"""
814 output = commands.getoutput("nvidia-settings -q gpuperfmodes | grep 'memclock'")
815 return str(output).lstrip()[9:] + " MHz"
816
818 """return current GPU Core Temperature to its caller"""
819 output = commands.getoutput("nvidia-settings -q GPUCoreTemp | cut -d ':' -f 3 -s | cut -d ' ' -f 2 | cut -d '.' -f 1")
820 return output
821
822
823
824
825
826
827
828
829
831 res = commands.getstatusoutput('sensors')
832 output = ['Custom Sensors']
833 output.remove ('Custom Sensors')
834 if res[0]==0:
835 sol = res[1].replace(':\n ',': ').replace(':\n\t',': ').splitlines()
836 for i in sol:
837 i = i.strip()
838 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):
839 output.append(i.lstrip())
840
841 res = commands.getstatusoutput(' nvidia-settings -q GPUAmbientTemp | grep :')
842 if res[0] == 0:
843 if res[1].strip().startswith('Attribute \'GPUAmbientTemp\''):
844 sol = res[1].splitlines()[0].split('):')[1].strip()
845 output.append('nvidia GPU ambiant: '+str(float(sol))+' C')
846 res = commands.getstatusoutput(' nvidia-settings -q GPUCoreTemp | grep :')
847 if res[0] == 0:
848 if res[1].strip().startswith('Attribute \'GPUCoreTemp\''):
849 sol = res[1].splitlines()[0].split('):')[1].strip()
850 output.append('nvidia GPU core: '+str(float(sol))+'C')
851
852
853
854 try:
855 path = "/proc/acpi/thermal_zone/"
856 files = os.listdir(path)
857 for entry in files:
858 try:
859 f = open(path+entry+'/temperature', "r")
860 tmp = f.readlines(200)
861 f.close()
862 val = tmp[0].replace('temperature:','').replace('C','').strip()
863 output.append('acpi temperature '+entry+': '+val+'C')
864 except:
865 print("Can't open %s/temperature" % path+entry)
866 except:
867 print("Can't open folder /proc/acpi/thermal_zone/")
868
869
870 path = "/proc/acpi/ibm/thermal"
871 try:
872 f = open(path, "r")
873 tmp = f.readlines(200)
874 f.close()
875 lst = tmp[0].split(' ')
876 pos = 0
877 for i in lst:
878 i = i.strip()
879 if i != '' and i != '-128':
880 output.append('ibm temperature '+str(pos)+': '+i+'C')
881 pos = pos+1
882 except:
883 print("Can't open %s" % path)
884
885 path = "/proc/acpi/ibm/fan"
886 try:
887 f = open(path, "r")
888 tmp = f.readlines(200)
889 f.close()
890 for i in tmp:
891 if i.startswith('speed:'):
892 output.append('ibm fan: '+i.split(':')[1].strip()+' RPM')
893 except:
894 print("Can't open %s" % path)
895
896
897 res = commands.getstatusoutput("netcat 127.0.0.1 7634")
898 if res[0] != 0:
899 res = commands.getstatusoutput("nc 127.0.0.1 7634")
900 if res[0] == 0:
901 try:
902 hddtemp_data = res[1].lstrip('|').rstrip('|')
903 sol = hddtemp_data.split('||')
904 for i in sol:
905 if len(i)>1:
906 lst = i.split('|')
907 output.append("hddtemp sensor "+lst[0]+": "+lst[2]+" "+lst[3])
908 except:
909 print('Error during hddtemp drives search')
910 else:
911 print('Hddtemp not installed')
912 return output
913
914
916
917 if sensorName.startswith('nvidia GPU ambiant'):
918 res = commands.getstatusoutput(' nvidia-settings -q GPUAmbientTemp | grep :')
919 if res[0] == 0:
920 if res[1].strip().startswith('Attribute \'GPUAmbientTemp\''):
921
922 return str(float(res[1].splitlines()[0].split('):')[1].strip()))+'C'
923 elif sensorName.startswith('nvidia GPU core'):
924 res = commands.getstatusoutput(' nvidia-settings -q GPUCoreTemp | grep :')
925 if res[0] == 0:
926 if res[1].strip().startswith('Attribute \'GPUCoreTemp\''):
927
928 return str(float(res[1].splitlines()[0].split('):')[1].strip()))+'C'
929
930 elif sensorName.startswith('acpi temperature'):
931 name = sensorName.split()[2].strip()
932 path = "/proc/acpi/thermal_zone/"+name+"/temperature"
933 try:
934 f = open(path, "r")
935 tmp = f.readlines(200)
936 f.close()
937 val = tmp[0].replace('temperature:','').replace('C','').strip()
938
939 return val+'C'
940 except:
941 print("can't read temperature in: %s" % path)
942 return 'Error'
943
944 elif sensorName.startswith('ibm temperature'):
945 path = "/proc/acpi/ibm/thermal"
946 try:
947 name = sensorName
948 f = open(path, "r")
949 tmp = f.readlines(200)
950 f.close()
951 lst = tmp[0].split(' ')
952 val = int(sensorName.split(' ')[2])
953 return lst[val]+'C'
954 except:
955 print("Can't read value from %s" % path)
956 return 'None'
957
958 elif sensorName.startswith('ibm fan'):
959 path = "/proc/acpi/ibm/fan"
960 try:
961 name = sensorName
962 f = open(path, "r")
963 tmp = f.readlines(200)
964 f.close()
965 for i in tmp:
966 if i.startswith('speed:'):
967
968 return i.split(':')[1].strip()+' RPM'
969 return 'None'
970 except:
971 print("Can't read value from %s" % path)
972 return 'None'
973
974 elif sensorName.startswith('hddtemp sensor'):
975 res = commands.getstatusoutput("netcat 127.0.0.1 7634")
976 if res[0] != 0:
977 res = commands.getstatusoutput("nc 127.0.0.1 7634")
978 name = sensorName[sensorName.rfind(' ')+1:]
979 if res[0] == 0:
980 hddtemp_data = res[1].lstrip('|').rstrip('|')
981 sol = hddtemp_data.split('||')
982 for i in sol:
983 if len(i)>1:
984 if i.startswith(name):
985 lst = i.split('|')
986 if sensorName.startswith('hddtemp sensor-numeric'):
987 return int(lst[2])
988 else:
989 return lst[0]+": "+lst[2]+" "+lst[3]
990 else:
991 print('Hddtemp not installed')
992 return ''
993
994
995
996
997 else:
998 res = commands.getstatusoutput('sensors')
999 if res[0] == 0:
1000 sol = res[1].replace(':\n ',': ').replace(':\n\t',': ').splitlines()
1001 for s in sol:
1002 s.strip()
1003 if s.startswith(sensorName):
1004 try:
1005 s = s.split(':')[1].strip(' ').strip('\t')
1006 i = 0
1007 while(((s[i]>='0') and (s[i]<='9')) or (s[i]=='.') or (s[i]=='+') or (s[i]=='-')):
1008 i = i+1
1009 return float(s[0:i])
1010 except:
1011 return 0
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025 -class Sensor (gobject.GObject):
1026 """A base class for deriving new Sensor-types from."""
1027
1028
1029 __gsignals__ = dict( \
1030 sensor_updated = (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, ()),
1031 sensor_stopped = (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, ()) )
1032
1034 """Create a new sensor which updates after the given interval."""
1035 gobject.GObject.__init__(self)
1036 self._timeout_id = None
1037 self._interval = interval
1038
1039 self.set_interval(interval)
1040
1041
1042
1044 """Get the update-interval time for this Sensor."""
1045 return self._interval
1046
1048 """Set the update-interval time for this Sensor and start it."""
1049 if self._timeout_id:
1050 gobject.source_remove(self._timeout_id)
1051 if ms and ms > 10:
1052 self._interval = ms
1053 self._timeout_id = gobject.timeout_add(ms, self.__timeout)
1054 return True
1055 return False
1056
1058 """Immediately stop this sensor and emit the "sensor_stopped"-signal."""
1059 self.set_interval(0)
1060 self.emit('sensor_stopped')
1061
1062
1063
1065 """Override this handler in subclasses to implement your calculations
1066 and update the Sensor's attributes. Must return True to emit a signal
1067 which can then be handled within the screenlets, returning False
1068 causes the Sensor to be stopped.."""
1069 return True
1070
1071
1072
1074 """The timeout function. Does nothing but calling the on_update
1075 handler and emitting a signal if the handler returned True."""
1076
1077 if self.on_update():
1078 self.emit('sensor_updated')
1079 return True
1080
1081 self.stop()
1082 return False
1083
1084
1086 """A very simple CPU-sensor."""
1087
1088 - def __init__ (self, interval=1000, cpu=0):
1089 """Create a new CPUSensor which emits an 'sensor_updated'-signal after a
1090 given interval (default is 1000ms). The multi-cpu support is untested
1091 but theoretically works :)."""
1092 Sensor.__init__(self, interval)
1093 self._load = 0
1094 self._cpu = cpu
1095
1096
1097
1099 """Return the current CPU-load."""
1100 return self._load
1101
1102
1103
1105 """Called on each interval. Calculates the CPU-load and updates the
1106 internal load-value."""
1107 try:
1108 f = open("/proc/stat", "r")
1109 tmp = f.readlines(200)
1110 f.close()
1111 except:
1112 print "CPUSensor: Failed to open /proc/stat. Sensor stopped."
1113 self.stop()
1114 line = tmp[self._cpu + 1]
1115 if line[0:5] == "cpu%i " % self._cpu:
1116 reg = re.compile('[0-9]+')
1117 load_values = reg.findall(line[5:])
1118
1119 cuse = int(load_values[0])
1120 csys = int(load_values[2])
1121 load = cuse + csys - old_cuse[0]
1122 if load < 0: load = 0
1123 if load > 99: load = 99
1124 self._load = load
1125 old_cuse[0] = cuse + csys
1126
1127 return True
1128 return False
1129
1130
1132
1134 """Create a new RAMSensor which emits an 'sensor_updated'-signal after a
1135 given interval (default is 1000ms)."""
1136 Sensor.__init__(self, interval)
1137 self._freemem = 0
1138 self._usedmem = 0
1139
1140
1141
1143 """Return the amount of currently free RAM."""
1144 return self._freemem
1145
1147 """Return the amount of currently used RAM."""
1148 return self._usedmem
1149
1150
1151
1153 """Called on each interval. Calculates the load and updates the
1154 internal values."""
1155 self._freemem = mem_get_freemem()
1156 self._usedmem = mem_get_usedmem()
1157 return True
1158
1159
1161
1162 - def __init__ (self, interval=1000, device='eth0'):
1163 """Create a new NetSensor which emits an 'sensor_updated'-signal after a
1164 given interval (default is 1000ms)."""
1165 Sensor.__init__(self, interval)
1166 self._device = device
1167 self._downloaded, self._uploaded = net_get_activity(device)
1168 self._last_down, self._last_up = self._downloaded, self._uploaded
1169
1170
1171
1173 """Return the current upload speed in b/s."""
1174 return self._uploaded - self._last_up
1175
1177 """Return the current download speed in b/s."""
1178 return self._downloaded - self._last_down
1179
1181 """Return the overall upload amount."""
1182 return self._uploaded
1183
1185 """Return the overall download amount."""
1186 return self._downloaded
1187
1188
1189
1191 """Called on each interval. Calculates the load and updates the
1192 internal values."""
1193 d, u = net_get_activity(self._device)
1194 self._last_up = self._uploaded
1195 self._last_down = self._downloaded
1196 self._downloaded = int(d)
1197 self._uploaded = int(u)
1198
1199 return True
1200
1201
1202
1203 if __name__ == '__main__':
1204
1205 old_cpu = cpu_get_load(0)
1206 time.sleep(1)
1207 new_cpu = cpu_get_load(0)
1208 print 'CPU0: %i%%' % (new_cpu-old_cpu)
1209 sys.exit(0)
1210
1211
1212 print sys_get_hostname()
1213 print net_get_activity('eth0')
1214 print sys_get_linux_version()
1215 print sys_get_kernel_version()
1216
1217 print 'CPU0: %i%%' % cpu_get_load (0)
1218 print 'USED RAM: %i MB' % mem_get_usedmem()
1219 print 'FREE RAM: %i MB' % mem_get_freemem()
1220 print sensors_get_sensor_value('hddtemp sensor /dev/sda')
1221 sys.exit(0)
1222
1232
1233
1234 cpu = CPUSensor()
1235 cpu.connect('sensor_updated', handle_cpusensor_updated)
1236 ram = MemorySensor(5000)
1237 ram.connect('sensor_updated', handle_ramsensor_updated)
1238 net = NetSensor(1500, 'eth0')
1239 net.connect('sensor_updated', handle_netsensor_updated)
1240
1241
1242 mainloop = gobject.MainLoop()
1243 mainloop.run()
1244