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