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