Package screenlets :: Module sensors
[hide private]
[frames] | no frames]

Source Code for Module screenlets.sensors

   1  # This application is released under the GNU General Public License  
   2  # v3 (or, at your option, any later version). You can find the full  
   3  # text of the license under http://www.gnu.org/licenses/gpl.txt.  
   4  # By using, editing and/or distributing this software you agree to  
   5  # the terms and conditions of this license.  
   6  # Thank you for using free software! 
   7   
   8  # The screenlets.sensors module contains helper-functions to aid in 
   9  # creating CPU/RAM/*-meters and in retrieving general system information. 
  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  gettext.textdomain('screenlets') 
  21  gettext.bindtextdomain('screenlets', '/usr/share/locale') 
  22   
23 -def _(s):
24 return gettext.gettext(s)
25 26 27 # ------------------------------------------------------------------------------ 28 # FUNCTIONS 29 # ------------------------------------------------------------------------------ 30 31 32 33 ########################################### 34 # # 35 # CPU # 36 # # 37 ########################################### 38 39 # calculate cpu-usage by values from /proc/stat 40 # (written by Helder Fraga aka Whise
41 -def cpu_get_load (processor_number=0):
42 """Calculates the system load.""" 43 try: 44 data = commands.getoutput("cat /proc/stat") 45 tmp = data.split('\n') 46 47 except: 48 print _("Failed to open /proc/stat") 49 sys.exit(1) 50 if processor_number == 0 : sufix = '' 51 else: sufix = str(processor_number -1) 52 line = tmp[processor_number] 53 54 if line.startswith("cpu%s"% (sufix)): 55 cuse = float( line.split()[1] ) 56 cn = float( line.split()[2] ) 57 csys = float( line.split()[3]) 58 load = cuse + csys + cn 59 60 #load = int(load / .update_interval) 61 return load 62 return None
63
64 -def cpu_get_cpu_name():
65 try: 66 f = open("/proc/cpuinfo", "r") 67 tmp = f.readlines(500) 68 f.close() 69 except: 70 print "Failed to open /proc/cpuinfo" 71 sys.exit(1) 72 list = [] 73 for line in tmp: 74 if line.startswith("model name"): 75 return line.split(':')[1].strip() 76 return ''
77
78 -def cpu_get_cpu_list ():
79 try: 80 f = open("/proc/stat", "r") 81 tmp = f.readlines(2000) 82 f.close() 83 except: 84 print "Failed to open /proc/stat" 85 sys.exit(1) 86 list = [] 87 for line in tmp: 88 if line.startswith("cpu"): 89 list.append(line.split(' ')[0]) 90 91 return list
92
93 -def cpu_get_nb_cpu ():
94 try: 95 f = open("/proc/stat", "r") 96 tmp = f.readlines(2000) 97 f.close() 98 except: 99 print "Failed to open /proc/stat" 100 sys.exit(1) 101 nb = 0 102 for line in tmp: 103 if line.startswith("cpu"): 104 nb = nb+1 105 return nb -1
106 107 108 ########################################### 109 # # 110 # System info # 111 # # 112 ########################################### 113 114 # written by Hendrik Kaju
115 -def sys_get_uptime_long ():
116 """Get uptime using 'cat /proc/uptime'""" 117 data1 = commands.getoutput("cat /proc/uptime") 118 uptime = float( data1.split()[0] ) 119 days = int( uptime / 60 / 60 / 24 ) 120 uptime = uptime - days * 60 * 60 * 24 121 hours = int( uptime / 60 / 60 ) 122 uptime = uptime - hours * 60 * 60 123 minutes = int( uptime / 60 ) 124 return str(days) + " days, " + str(hours) + " hours and " + str(minutes) + " minutes"
125
126 -def sys_get_uptime():
127 try: 128 f = open("/proc/uptime", "r") 129 tmp = f.readlines(100) 130 f.close() 131 t = tmp[0].split()[0] 132 h = int(float(t)/3600) 133 m = int((float(t)-h*3600)/60) 134 if m < 10: 135 return str(h)+':'+'0'+str(m) 136 else: 137 return str(h)+':'+str(m) 138 except: 139 print "Failed to open /proc/uptime" 140 return 'Error'
141 142
143 -def sys_get_username():
144 res = commands.getstatusoutput('whoami') 145 if res[0]==0: 146 return res[1].strip() 147 return ''
148 149 150 # written by Hendrik Kaju
151 -def sys_get_hostname ():
152 """Get user- and hostname and return user@hostname.""" 153 hostname = commands.getoutput("hostname") 154 return hostname
155 156 157 # written by Hendrik Kaju
158 -def sys_get_average_load ():
159 """Get average load (as 3-tuple with floats).""" 160 data = commands.getoutput("cat /proc/loadavg") 161 load1 = str(float( data.split()[0] ))[:4] 162 load2 = str(float( data.split()[1] ))[:4] 163 load3 = str(float( data.split()[2] ))[:4] 164 return load1+ ','+ load2 +','+ load3
165 166
167 -def sys_get_distrib_name():
168 try: 169 f = open("/etc/issue", "r") 170 tmp = f.readlines(100) 171 f.close() 172 return tmp[0].replace('\\n','').replace('\l','').replace('\r','').strip() 173 except: 174 print "Failed to open /etc/issue" 175 return 'Error'
176 177
178 -def sys_get_distroshort ():
179 """Get distro short name""" 180 distros = commands.getoutput("lsb_release -is") 181 return distros
182
183 -def sys_get_desktop_enviroment():
184 """ shows kde or gnome or xface""" 185 if os.environ.get('KDE_FULL_SESSION') == 'true': 186 desktop_environment = 'kde' 187 elif os.environ.get('GNOME_DESKTOP_SESSION_ID'): 188 desktop_environment = 'gnome' 189 else: 190 try: 191 import commands 192 info = commands.getoutput('xprop -root _DT_SAVE_MODE') 193 if ' = "xfce4"' in info: 194 desktop_environment = 'xfce' 195 except (OSError, RuntimeError): 196 pass 197 return desktop_environment
198
199 -def sys_get_kernel_version():
200 res = commands.getstatusoutput('uname -r') 201 if res[0]==0: 202 return res[1].strip() 203 return "Can't get kernel version"
204
205 -def sys_get_kde_version():
206 res = commands.getstatusoutput('kde-config --version') 207 if res[0]==0: 208 lst = res[1].splitlines() 209 for i in lst: 210 if i.startswith('KDE:'): 211 return i[4:].strip() 212 return "Can't get KDE version"
213
214 -def sys_get_gnome_version():
215 res = commands.getstatusoutput('gnome-about --gnome-version') 216 if res[0]==0: 217 lst = res[1].splitlines() 218 for i in lst: 219 if i.startswith('Version:'): 220 return i[8:].strip() 221 return "Can't get Gnome version"
222 223 # by whise
224 -def sys_get_linux_version ():
225 """Get linux version string.""" 226 return commands.getoutput("cat /proc/version")
227 228 # by whise 229 # TODO: return dict and parse the output of cpuinfo (function does not much yet)
230 -def sys_get_full_info ():
231 """Get cpu info from /proc/cpuinfo.""" 232 return commands.getoutput("cat /proc/cpuinfo") 233
234 -def sys_get_window_manager():
235 root = gtk.gdk.get_default_root_window() 236 try: 237 ident = root.property_get("_NET_SUPPORTING_WM_CHECK", "WINDOW")[2] 238 _WM_NAME_WIN = gtk.gdk.window_foreign_new(long(ident[0])) 239 except TypeError, exc: 240 _WM_NAME_WIN = "" 241 log("Your window manager doesn't support " 242 "_NET_SUPPORTING_WM_CHECK! Switch to a compliant WM!" 243 "The following error occurred:\n%s" % (exc,)) 244 name = "" 245 win = _WM_NAME_WIN 246 if (win != None): 247 try: 248 name = win.property_get("_NET_WM_NAME")[2] 249 except TypeError, exc: 250 log("Your window manager doesn't support _NET_WM_NAME!\n" 251 "Switch to a EWMH compliant WM.\n" 252 "The following error occurred:\n%s" % (exc,)) 253 return name 254 255 return name
256 257 ########################################### 258 # # 259 # Memory # 260 # # 261 ########################################### 262 263
264 -def mem_get_freemem ():# written by Hendrik Kaju
265 """Get free memory.""" 266 cached = commands.getoutput("""cat /proc/meminfo | grep Cached | awk 'BEGIN {FS=":"} {print $2}' | awk '{print $1, $9}'""") 267 buffers = commands.getoutput("""cat /proc/meminfo | grep Buffers | awk 'BEGIN {FS=":"} {print $2}' | awk '{print $1, $9}'""") 268 free = commands.getoutput("""cat /proc/meminfo | grep MemFree | awk 'BEGIN {FS=":"} {print $2}' | awk '{print $1, $9}'""") 269 return int(cached.split()[0])/1024 + int(buffers)/1024 + int(free)/1024 270 271
272 -def mem_get_usedmem ():# written by Hendrik Kaju
273 """Get used memory.""" 274 total = commands.getoutput("""cat /proc/meminfo | grep MemTotal | awk 'BEGIN {FS=":"} {print $2}' | awk '{print $1, $9}'""") 275 cached = commands.getoutput("""cat /proc/meminfo | grep Cached | awk 'BEGIN {FS=":"} {print $2}' | awk '{print $1, $9}'""") 276 buffers = commands.getoutput("""cat /proc/meminfo | grep Buffers | awk 'BEGIN {FS=":"} {print $2}' | awk '{print $1, $9}'""") 277 free = commands.getoutput("""cat /proc/meminfo | grep MemFree | awk 'BEGIN {FS=":"} {print $2}' | awk '{print $1, $9}'""") 278 return int(total)/1024 - int(cached.split()[0])/1024 - \ 279 int(buffers)/1024 - int(free)/1024 280
281 -def mem_get_usage():
282 try: 283 meminfo_file = open('/proc/meminfo') 284 meminfo = {} 285 for x in meminfo_file: 286 try: 287 (key,value,junk) = x.split(None, 2) 288 key = key[:-1] 289 meminfo[key] = int(value) 290 except: 291 pass 292 meminfo_file.close() 293 return int((100*(int(meminfo['MemTotal'])-int(meminfo['Cached']) - int(meminfo['Buffers']) - int(meminfo['MemFree'])))/int(meminfo['MemTotal'])) 294 except: 295 print("Can't parse /proc/meminfo") 296 return 0
297
298 -def mem_get_usedswap():
299 try: 300 meminfo_file = open('/proc/meminfo') 301 meminfo = {} 302 for x in meminfo_file: 303 try: 304 (key,value,junk) = x.split(None, 2) 305 key = key[:-1] 306 meminfo[key] = int(value) 307 except: 308 pass 309 meminfo_file.close() 310 if(meminfo['SwapTotal']==0): 311 return 0 312 return int((100*(int(meminfo['SwapTotal'])-int(meminfo['SwapCached']) - int(meminfo['SwapFree'])))/int(meminfo['SwapTotal'])) 313 except: 314 print("Can't parse /proc/meminfo") 315 return 0
316 317 ########################################### 318 # # 319 # Disks # 320 # # 321 ########################################### 322 323
324 -def disk_get_drive_info (mount_point):
325 """Returns info about the given mount point (as dict).""" 326 proc = subprocess.Popen('df -h -a -P | grep ^/dev/ ', shell='true', 327 stdout=subprocess.PIPE) 328 sdevs = proc.stdout.read().rsplit('\n') 329 sdevs.pop() 330 for stdev in sdevs: 331 sdev = re.findall("(\S*)\s*", stdev) 332 dev = { 333 'device': sdev[0], 334 'size': sdev[1], 335 'used': sdev[2], 336 'free': sdev[3], 337 'quota': sdev[4], 338 'mount': sdev[5] 339 } 340 if dev['mount'] == mount_point: 341 return dev 342 return None
343
344 -def disk_get_swap ():
345 """Get a list of swap partitions.""" 346 swap = commands.getoutput("cat /proc/swaps") 347 swap = str(swap.split()[5:]) 348 swap = swap.replace("'","") 349 swap = swap.replace("[","") 350 swap = swap.replace("]","") 351 swap = swap.replace(",","") 352 return str(swap)
353 354
355 -def disk_get_usage(disk_disk):
356 res = commands.getoutput('df -h -a -P').splitlines() 357 for i in res: 358 if i.startswith('/dev/'): 359 data = re.findall("(\S*)\s*", i) 360 361 if (data[5] == disk_disk) or (data[0] == disk_disk): 362 return data
363
364 -def disk_get_disk_list():
365 disks = [] 366 res = commands.getoutput('df -h -a -P').splitlines() 367 for i in res: 368 if i.startswith('/dev/'): 369 data = re.findall("(\S*)\s*", i) 370 disks.append(data[5]) 371 return disks
372 373 374 ########################################### 375 # # 376 # Internet # 377 # # 378 ########################################### 379
380 -def net_get_ip(): # by Whise
381 """Returns ip if it can""" 382 ip = commands.getoutput("ifconfig") 383 x = 0 384 while True: 385 ip = ip[ip.find("inet addr:"):] 386 ip = ip[10:] 387 ipc = ip[:ip.find(chr(32))] 388 if ipc != '127.0.0.1' and ipc != None and ipc !='1': 389 390 return ipc 391 392 393 return 'Cannot get ip' 394 395
396 -def net_get_updown():
397 try: 398 f = open("/proc/net/dev", "r") 399 data = f.readlines(2000) 400 f.close() 401 newNetUp = 0 402 newNetDown = 0 403 for i in data: 404 if i.find(':') != -1 and i.strip().startswith('lo:') == False: 405 v = i.split(':')[1].split() 406 newNetUp = float( v[8] )+newNetUp 407 newNetDown = float( v[0] )+newNetDown 408 409 410 return (newNetUp/1024), (newNetDown/1024) 411 except: 412 print("Can't open /proc/net/dev") 413 return 0,0
414 415
416 -def net_get_activity (device):
417 """This will return the total download and upload this session. As 2-tuple 418 with floats).""" 419 data = commands.getoutput("cat /proc/net/dev") 420 data = data[data.find(device + ":") + 5:] 421 return (float(data.split()[0]), float(data.split()[8]))
422 423 424 ########################################### 425 # # 426 # Wireless # 427 # # 428 ########################################### 429
430 -def wir_get_interfaces():
431 try: 432 interfaces = [] 433 f = open("/proc/net/wireless") 434 cards = f.read(1024) 435 f.close() 436 for line in cards.splitlines(): 437 colon = line.find(":") 438 if colon > 0: 439 interfaces.append(line[:colon].strip()) 440 return interfaces 441 except: 442 print("Can't open /proc/net/wireless") 443 return []
444
445 -def wir_get_stats (interface):
446 """Returns wireless stats as dict.""" 447 stats = {} 448 iwcfd = os.popen("iwconfig " + interface) 449 iwconfig = iwcfd.read(1024) 450 iwcfd.close() 451 essid = iwconfig[iwconfig.find('ESSID:"')+7:] 452 stats['essid'] = essid[:essid.find('"')] 453 if stats['essid'].strip()[:stats['essid'].strip().find(" ")] == "unassociated": 454 return {"essid": "Not connected", "percentage": 0} 455 else: 456 bitrate = iwconfig[iwconfig.find("Bit Rate:")+9:] 457 stats['bitrate'] = bitrate[:bitrate.find(" ")] 458 quality = iwconfig[iwconfig.find("Link Quality=")+13:] 459 quality = quality[:quality.find(" ")] 460 if quality.find("/") > 0: 461 stats['quality'], stats['quality_max'] = quality.split("/") 462 else: 463 stats['quality'] = quality 464 try: 465 stats['percentage'] = int(float(stats['quality'])/float(stats['quality_max'])*100) 466 except: 467 return {"essid": "Not connected", "percentage": 0} 468 signal = iwconfig[iwconfig.find("Signal level=")+13:] 469 stats['signal'] = signal[:signal.find(" ")] 470 noise = iwconfig[iwconfig.find("Noise level=")+12:] 471 stats['noise'] = noise[:noise.find('\n')] 472 return stats
473 474 ########################################### 475 # # 476 # calendar # 477 # # 478 ########################################### 479 480 481 # by whise
482 -def cal_get_now ():
483 """Returns full now time and date""" 484 return str(datetime.now())
485 486
487 -def cal_get_local_date ():
488 """returns date using local format""" 489 return str(datetime.now().strftime("%x"))
490
491 -def cal_get_date ():
492 """returns date.""" 493 return str(datetime.now().strftime("%d/%m/%Y"))
494
495 -def cal_get_local_time ():
496 """returns time using local format""" 497 return str(datetime.now().strftime("%X"))
498
499 -def cal_get_time ():
500 """returns time""" 501 return str(datetime.now().strftime("%H:%M:%S"))
502
503 -def cal_get_time24 ():
504 """returns 24 hour time""" 505 return str(datetime.now().strftime("%R"))
506
507 -def cal_get_time12 ():
508 """returns 12 hour time""" 509 return str(datetime.now().strftime("%r"))
510
511 -def cal_get_year ():
512 """returns the years.""" 513 return str(datetime.now().strftime("%Y"))
514
515 -def cal_get_month ():
516 """returns the month""" 517 return str(datetime.now().strftime("%B"))
518
519 -def cal_get_month_name ():
520 """returns the month name""" 521 return str(datetime.now().strftime("%m"))
522
523 -def cal_get_day ():
524 """returns the day""" 525 return str(datetime.now().strftime("%d"))
526
527 -def cal_get_day_monday ():
528 """returns the number of the day of the week starting from monday""" 529 return str(datetime.now().strftime("%u"))
530
531 -def cal_get_day_sonday ():
532 """returns the number of the day of the week starting from sonday""" 533 return str(datetime.now().strftime("%w"))
534
535 -def cal_get_day_name ():
536 """returns the day name""" 537 return str(datetime.now().strftime("%A"))
538
539 -def cal_get_hour ():
540 """returns the hour""" 541 return str(datetime.now().strftime("%H"))
542
543 -def cal_get_hour24 ():
544 """returns the hour""" 545 return str(datetime.now().strftime("%H"))
546
547 -def cal_get_hour12 ():
548 """returns the hours""" 549 return str(datetime.now().strftime("%I"))
550
551 -def cal_get_minute ():
552 """returns minutes""" 553 return str(datetime.now().strftime("%M"))
554
555 -def cal_get_second ():
556 """returns seconds""" 557 return str(datetime.now().strftime("%S"))
558
559 -def cal_get_ampm ():
560 """return am/pm or None if not available""" 561 return str(datetime.now().strftime("%p"))
562 563 564 565 ########################################### 566 # # 567 # Battery # 568 # # 569 ########################################### 570 571
572 -def bat_get_battery_list():
573 try: 574 path = "/proc/acpi/battery/" 575 files = os.listdir(path) 576 return files 577 except: 578 return[]
579
580 -def bat_get_data(name):
581 path = "/proc/acpi/battery/"+name+"/info" 582 try: 583 f = commands.getoutput('cat ' +path) 584 lines = f.split('\n') 585 total = 0 586 current = 0 587 full = 0 588 state = '' 589 present = True 590 for i in lines: 591 if i.startswith('present:') and i.find('yes')==-1: 592 present = False 593 elif i.startswith('design capacity:'): 594 total = int(i.split(':')[1].strip().split(' ')[0]) 595 elif i.startswith('last full capacity:'): 596 full = int(i.split(':')[1].strip().split(' ')[0]) 597 elif i.startswith('remaining capacity:'): 598 current = int(i.split(':')[1].strip().split(' ')[0]) 599 elif i.startswith('charging state:'): 600 state = i.split(':')[1].strip().split(' ')[0] 601 602 path = "/proc/acpi/battery/"+name+"/state" 603 f = commands.getoutput('cat ' +path) 604 lines = f.split('\n') 605 for i in lines: 606 if i.startswith('present:') and i.find('yes')==-1: 607 present = False 608 elif i.startswith('design capacity:'): 609 total = int(i.split(':')[1].strip().split(' ')[0]) 610 elif i.startswith('last full capacity:'): 611 full = int(i.split(':')[1].strip().split(' ')[0]) 612 elif i.startswith('remaining capacity:'): 613 current = int(i.split(':')[1].strip().split(' ')[0]) 614 elif i.startswith('charging state:'): 615 state = i.split(':')[1].strip().split(' ')[0] 616 return total, current, full, state, present 617 except: 618 return 0, 0, 0, '', False
619
620 -def bat_get_value(line):
621 return line.split(':')[1].strip().split(' ')[0]
622 623 624 ########################################### 625 # # 626 # Processes # 627 # # 628 ########################################### 629 630
631 -def top_process_get_list():
632 res = commands.getoutput('ps -eo pcpu,pmem,comm --sort pcpu').splitlines() 633 l = res.__len__() 634 return res,l
635 636 637 638 639 ########################################### 640 # # 641 # Custom Sensors # thanks Mathieu Villegas for you great watermark 642 # # 643 ########################################### 644 645
646 -def sensors_get_sensors_list():
647 res = commands.getstatusoutput('sensors') 648 output = ['Custom Sensors'] 649 output.remove ('Custom Sensors') 650 if res[0]==0: 651 sol = res[1].replace(':\n ',': ').replace(':\n\t',': ').splitlines() 652 for i in sol: 653 i = i.strip() 654 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): 655 output.append(i.lstrip())#.split(')')[0]+')') 656 #now look for nvidia sensors 657 res = commands.getstatusoutput(' nvidia-settings -q GPUAmbientTemp | grep :') 658 if res[0] == 0: 659 if res[1].strip().startswith('Attribute \'GPUAmbientTemp\''): 660 sol = res[1].splitlines()[0].split('):')[1].strip() 661 output.append('nvidia GPU ambiant: '+str(float(sol))+'°C') 662 res = commands.getstatusoutput(' nvidia-settings -q GPUCoreTemp | grep :') 663 if res[0] == 0: 664 if res[1].strip().startswith('Attribute \'GPUCoreTemp\''): 665 sol = res[1].splitlines()[0].split('):')[1].strip() 666 output.append('nvidia GPU core: '+str(float(sol))+'°C') 667 668 669 #recherche des senseurs ACPI 670 try: 671 path = "/proc/acpi/thermal_zone/" 672 files = os.listdir(path) 673 for entry in files: 674 try: 675 f = open(path+entry+'/temperature', "r") 676 tmp = f.readlines(200) 677 f.close() 678 val = tmp[0].replace('temperature:','').replace('C','').strip() 679 output.append('acpi temperature '+entry+': '+val+'°C') 680 except: 681 print("Can't open "+path+entry+'/temperature') 682 except: 683 print("Can't open folder /proc/acpi/thermal_zone/") 684 685 #recherche des senseurs IBM 686 path = "/proc/acpi/ibm/thermal" 687 try: 688 f = open(path, "r") 689 tmp = f.readlines(200) 690 f.close() 691 lst = tmp[0].split(' ') 692 pos = 0 693 for i in lst: 694 i = i.strip() 695 if i != '' and i != '-128': 696 output.append('ibm temperature '+str(pos)+': '+i+'°C') 697 pos = pos+1 698 except: 699 print("Can't open "+path) 700 701 path = "/proc/acpi/ibm/fan" 702 try: 703 f = open(path, "r") 704 tmp = f.readlines(200) 705 f.close() 706 for i in tmp: 707 if i.startswith('speed:'): 708 output.append('ibm fan: '+i.split(':')[1].strip()+' RPM') 709 except: 710 print("Can't open "+path) 711 712 #recherche des temperatures de disque 713 res = commands.getstatusoutput("netcat 127.0.0.1 7634") 714 if res[0] != 0: 715 res = commands.getstatusoutput("nc 127.0.0.1 7634") 716 if res[0] == 0: 717 try: 718 hddtemp_data = res[1].lstrip('|').rstrip('|') 719 sol = hddtemp_data.split('||') 720 for i in sol: 721 if len(i)>1: 722 lst = i.split('|') 723 output.append("hddtemp sensor "+lst[0]+": "+lst[2]+" °"+lst[3]) 724 except: 725 print('Error during hddtemp drives search') 726 else: 727 print('Hddtemp not installed') 728 return output
729 730
731 -def sensors_get_sensor_value(sensorName):
732 733 if sensorName.startswith('nvidia GPU ambiant'): 734 res = commands.getstatusoutput(' nvidia-settings -q GPUAmbientTemp | grep :') 735 if res[0] == 0: 736 if res[1].strip().startswith('Attribute \'GPUAmbientTemp\''): 737 #ici, je fais un str(float()) comme ca ca transforme 48. en 48.0 738 return str(float(res[1].splitlines()[0].split('):')[1].strip()))+'°C' 739 elif sensorName.startswith('nvidia GPU core'): 740 res = commands.getstatusoutput(' nvidia-settings -q GPUCoreTemp | grep :') 741 if res[0] == 0: 742 if res[1].strip().startswith('Attribute \'GPUCoreTemp\''): 743 #ici, je fais un str(float()) comme ca ca transforme 48. en 48.0 744 return str(float(res[1].splitlines()[0].split('):')[1].strip()))+'°C' 745 746 elif sensorName.startswith('acpi temperature'): 747 name = sensorName.split()[2].strip() 748 path = "/proc/acpi/thermal_zone/"+name+"/temperature" 749 try: 750 f = open(path, "r") 751 tmp = f.readlines(200) 752 f.close() 753 val = tmp[0].replace('temperature:','').replace('C','').strip() 754 755 return val+'°C' 756 except: 757 print("can't read temperature in: "+path) 758 return 'Error' 759 760 elif sensorName.startswith('ibm temperature'): 761 path = "/proc/acpi/ibm/thermal" 762 try: 763 name = sensorName 764 f = open(path, "r") 765 tmp = f.readlines(200) 766 f.close() 767 lst = tmp[0].split(' ') 768 val = int(sensorName.split(' ')[2]) 769 return lst[val]+'°C' 770 except: 771 print("Can't read value from "+path) 772 return 'None' 773 774 elif sensorName.startswith('ibm fan'): 775 path = "/proc/acpi/ibm/fan" 776 try: 777 name = sensorName 778 f = open(path, "r") 779 tmp = f.readlines(200) 780 f.close() 781 for i in tmp: 782 if i.startswith('speed:'): 783 784 return i.split(':')[1].strip()+' RPM' 785 return 'None' 786 except: 787 print("Can't read value from "+path) 788 return 'None' 789 790 elif sensorName.startswith('hddtemp sensor '): 791 res = commands.getstatusoutput("netcat 127.0.0.1 7634") 792 if res[0] != 0: 793 res = commands.getstatusoutput("nc 127.0.0.1 7634") 794 name = sensorName[15:] 795 if res[0] == 0: 796 hddtemp_data = res[1].lstrip('|').rstrip('|') 797 sol = hddtemp_data.split('||') 798 for i in sol: 799 if len(i)>1: 800 if i.startswith(name): 801 lst = i.split('|') 802 return lst[0]+": "+lst[2]+" °"+lst[3] 803 else: 804 print('Hddtemp not installed') 805 return '' 806 807 808 809 #maintenant, je recherche dans lm-sensors 810 else: 811 res = commands.getstatusoutput('sensors') 812 if res[0] == 0: 813 sol = res[1].replace(':\n ',': ').replace(':\n\t',': ').splitlines() 814 for s in sol: 815 s.strip() 816 if s.startswith(sensorName): 817 try: 818 s = s.split(':')[1].strip(' ').strip('\t') 819 i = 0 820 while(((s[i]>='0') and (s[i]<='9')) or (s[i]=='.') or (s[i]=='+') or (s[i]=='-')): 821 i = i+1 822 return float(s[0:i]) 823 except: 824 return 0
825 826 827 828 829 830 831 832 833 834 # ------------------------------------------------------------------------------ 835 # CLASSES should not be used , calling classes from multiple screenlets instances causes erros due to goobject multiple instaces 836 # ------------------------------------------------------------------------------ 837
838 -class Sensor (gobject.GObject):
839 """A base class for deriving new Sensor-types from.""" 840 841 # define custom signals 842 __gsignals__ = dict( \ 843 sensor_updated = (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, ()), 844 sensor_stopped = (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, ()) ) 845
846 - def __init__ (self, interval=1000):
847 """Create a new sensor which updates after the given interval.""" 848 gobject.GObject.__init__(self) 849 self._timeout_id = None 850 self._interval = interval 851 # start sensor timeout 852 self.set_interval(interval)
853 854 # + public functions 855
856 - def get_interval (self):
857 """Get the update-interval time for this Sensor.""" 858 return self._interval
859
860 - def set_interval (self, ms):
861 """Set the update-interval time for this Sensor and start it.""" 862 if self._timeout_id: 863 gobject.source_remove(self._timeout_id) 864 if ms and ms > 10: 865 self._interval = ms 866 self._timeout_id = gobject.timeout_add(ms, self.__timeout) 867 return True 868 return False
869
870 - def stop (self):
871 """Immediately stop this sensor and emit the "sensor_stopped"-signal.""" 872 self.set_interval(0) 873 self.emit('sensor_stopped')
874 875 # + handlers to be overridden in subclasses 876
877 - def on_update (self):
878 """Override this handler in subclasses to implement your calculations 879 and update the Sensor's attributes. Must return True to emit a signal 880 which can then be handled within the screenlets, returning False 881 causes the Sensor to be stopped..""" 882 return True
883 884 # + internals 885
886 - def __timeout (self):
887 """The timeout function. Does nothing but calling the on_update 888 handler and emitting a signal if the handler returned True.""" 889 # call sensor's on_update-handler 890 if self.on_update(): 891 self.emit('sensor_updated') 892 return True 893 # on_update returned False? Stop 894 self.stop() 895 return False
896 897
898 -class CPUSensor (Sensor):
899 """A very simple CPU-sensor.""" 900
901 - def __init__ (self, interval=1000, cpu=0):
902 """Create a new CPUSensor which emits an 'sensor_updated'-signal after a 903 given interval (default is 1000ms). The multi-cpu support is untested 904 but theoretically works :).""" 905 Sensor.__init__(self, interval) 906 self._load = 0 907 self._cpu = cpu
908 909 # + public functions 910
911 - def get_load (self):
912 """Return the current CPU-load.""" 913 return self._load
914 915 # + internals 916
917 - def on_update (self, old_cuse=[0]):
918 """Called on each interval. Calculates the CPU-load and updates the 919 internal load-value.""" 920 try: 921 f = open("/proc/stat", "r") 922 tmp = f.readlines(200) 923 f.close() 924 except: 925 print _("CPUSensor: Failed to open /proc/stat. Sensor stopped.") 926 self.stop() 927 line = tmp[self._cpu + 1] 928 if line[0:5] == "cpu%i " % self._cpu: 929 reg = re.compile('[0-9]+') 930 load_values = reg.findall(line[5:]) 931 # extract values from /proc/stat 932 cuse = int(load_values[0]) 933 csys = int(load_values[2]) 934 load = cuse + csys - old_cuse[0] 935 if load < 0: load = 0 936 if load > 99: load = 99 937 self._load = load 938 old_cuse[0] = cuse + csys 939 # return True to emit the "update_event"-signal 940 return True 941 return False
942 943
944 -class MemorySensor (Sensor):
945
946 - def __init__ (self, interval=1000):
947 """Create a new RAMSensor which emits an 'sensor_updated'-signal after a 948 given interval (default is 1000ms).""" 949 Sensor.__init__(self, interval) 950 self._freemem = 0 951 self._usedmem = 0
952 953 # + public functions 954
955 - def get_freemem (self):
956 """Return the amount of currently free RAM.""" 957 return self._freemem
958
959 - def get_usedmem (self):
960 """Return the amount of currently used RAM.""" 961 return self._usedmem
962 963 # + internals 964
965 - def on_update (self):
966 """Called on each interval. Calculates the load and updates the 967 internal values.""" 968 self._freemem = get_freemem() 969 self._usedmem = get_usedmem() 970 return True
971 972
973 -class NetSensor (Sensor):
974
975 - def __init__ (self, interval=1000, device='eth0'):
976 """Create a new NetSensor which emits an 'sensor_updated'-signal after a 977 given interval (default is 1000ms).""" 978 Sensor.__init__(self, interval) 979 self._device = device 980 self._downloaded, self._uploaded = get_net_activity(device) 981 self._last_down, self._last_up = self._downloaded, self._uploaded
982 983 # + public functions 984
985 - def get_upload_speed (self):
986 """Return the current upload speed in b/s.""" 987 return self._uploaded - self._last_up
988
989 - def get_download_speed (self):
990 """Return the current download speed in b/s.""" 991 return self._downloaded - self._last_down
992
993 - def get_uploaded (self):
994 """Return the overall upload amount.""" 995 return self._uploaded
996
997 - def get_downloaded (self):
998 """Return the overall download amount.""" 999 return self._downloaded
1000 1001 # + internals 1002
1003 - def on_update (self):
1004 """Called on each interval. Calculates the load and updates the 1005 internal values.""" 1006 d, u = get_net_activity(self._device) 1007 self._last_up = self._uploaded 1008 self._last_down = self._downloaded 1009 self._downloaded = int(d) 1010 self._uploaded = int(u) 1011 #print get_net_activity(self._device) 1012 return True
1013 1014 1015 # TEST: 1016 if __name__ == '__main__': 1017 1018 # some tests 1019 print get_hostname() 1020 print get_net_activity('eth0') 1021 print get_linux_version() 1022 print get_kernel() 1023 print get_cpu_info() 1024 1025 # callbacks which get notified about updates of sensor's values
1026 - def handle_cpusensor_updated (cs):
1027 print 'CPU0: %i%%' % cs.get_load()
1028 - def handle_ramsensor_updated (rs):
1029 print 'USED RAM: %i MB' % rs.get_usedmem() 1030 print 'FREE RAM: %i MB' % rs.get_freemem()
1031 - def handle_netsensor_updated (ns):
1032 #print (ns.get_upload_speed(), ns.get_download_speed()) 1033 print 'UP/DOWN: %i/%i bytes/s' % (ns.get_upload_speed(), 1034 ns.get_download_speed())
1035 1036 # create sensors and connect callbacks to them 1037 cpu = CPUSensor() 1038 cpu.connect('sensor_updated', handle_cpusensor_updated) 1039 ram = MemorySensor(5000) 1040 ram.connect('sensor_updated', handle_ramsensor_updated) 1041 net = NetSensor(1500, 'eth0') 1042 net.connect('sensor_updated', handle_netsensor_updated) 1043 1044 # start mainloop 1045 mainloop = gobject.MainLoop() 1046 mainloop.run() 1047