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