Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/python
- import re, subprocess
- import gtk
- # Note: I've got two items where I use a 'fudge factor' on the numbers.
- # My purpose is to make the numbers easier for my mother when
- # she compares computer hardware. Sometimes stores are off by 1.5% in
- # how many inches a thing is, and it's better to give a guess for power
- # consumption rather than "well it depends on many factors..."
- def getCPUs():
- found = []
- cpuinfo = open('/proc/cpuinfo')
- cpunum = -1
- for line in cpuinfo.readlines():
- if '\t: ' not in line:
- continue
- key, val = re.split(r'\s+:\s+', line.strip(), 1)
- if key == 'processor':
- cpunum += 1
- found.append({})
- found[cpunum][key] = val
- cpuinfo.close()
- return found
- def prettyCPUs(found):
- answer = ''
- i = 0
- while i < len(found):
- answer += found[i]['model name']
- if 'lm' in found[i]['flags']:
- answer += ' (64-bit)'
- if 'cpu cores' in found[i]:
- j = int(found[i]['cpu cores'])
- if j == 2:
- answer += ' (dual-core)'
- elif j == 4:
- answer += ' (quad-core)'
- else:
- answer += ' (multi-core)'
- i = i + j - 1
- answer += "\n"
- i += 1
- while ' ' in answer:
- answer = answer.replace(' ', ' ')
- return answer.strip()
- def prettyDistro():
- dist = subprocess.check_output(['lsb_release', '-ir']).strip()
- dist = re.sub(r'(Distributor ID:\s+|Release:\s+)', '', dist).replace("\n", ' ')
- return dist
- def prettyKernel():
- kern = subprocess.check_output(['uname', '-srp']).strip()
- kern = re.sub(r'i.86\b', '(32-bit)', kern)
- kern = re.sub(r'x86_64', '(64-bit)', kern)
- return kern
- def getDiskSizes():
- res = subprocess.Popen(['df', '-BG', '-lPT'], stdout=subprocess.PIPE)
- found = []
- for line in res.stdout.readlines():
- if not line.startswith('/'):
- continue # not a local device
- dfi = line.split()
- found.append({'name': dfi[0], 'type': dfi[1], 'total': int(dfi[2][:-1]),
- 'inuse': int(dfi[3][:-1]), 'unused': int(dfi[4][:-1])})
- res.stdout.close()
- return found
- def prettyDiskSizes(found):
- answer = ''
- for part in found:
- newtype = part['type']
- if 'fat' in part['type'] or 'NTFS' == part['type']:
- newtype = 'Windows'
- if 'ext' in part['type']:
- newtype = 'Linux'
- warning = ''
- if (part['unused'] * 100 / part['total']) < 18:
- warning = '{low space}'
- answer += "%s (%s) Size: %dGB Remains: %dGB %s\n" % (part['name'], newtype, part['total'], part['unused'], warning)
- return answer.strip()
- def getMemInfo():
- meminfo = open('/proc/meminfo')
- found = {}
- for line in meminfo.readlines():
- if ': ' not in line:
- continue
- key, val = re.split(r'\s*:\s+', line.strip(), 1)
- if val.endswith('kB'):
- found[key] = int(val[:-3]) * 1024
- elif val.endswith('MB'):
- found[key] = int(val[:-3]) * 1024 * 1024
- else:
- found[key] = int(val)
- meminfo.close()
- return found
- def prettyMemInfo(found):
- answer = 'installed memory '
- meg = 1024 * 1024
- gig = meg * 1024
- if found['MemTotal'] > gig:
- answer = '%.1f GB' % (found['MemTotal'] * 10 / gig / 10.0)
- else:
- answer = '%.1f MB' % (found['MemTotal'] * 10 / meg / 10.0)
- if (found['SwapFree'] * 100 / found['SwapTotal']) < 50:
- answer += ' {could use more}'
- return answer
- def prettyVGAcard():
- res = subprocess.Popen(['lspci', '-mm'], stdout=subprocess.PIPE)
- answer = ''
- for line in res.stdout.readlines():
- found = re.search(r'"VGA compatible controller" "(.*?)" "(.*?)"', line)
- if found is not None:
- answer = found.group(1) + ' ' + found.group(2)
- break
- res.stdout.close()
- return answer
- def prettyScreensize():
- res = subprocess.Popen('xdpyinfo', stdout=subprocess.PIPE)
- answer = ''
- for line in res.stdout.readlines():
- match = re.search(r'\s*dimensions:\s*(\d+)x(\d+)', line)
- if match is not None:
- w, h = int(match.group(1)), int(match.group(2))
- answer = 'Desktop resolution: %dx%d' % (w, h)
- if (w * 10 / h) == 16:
- answer += " (16:9)"
- elif (w * 100 / h) == 133:
- answer += " (4:3)"
- match = re.search(r'(\d+)x(\d+)\s+millimeters', line)
- if match is not None:
- w, h = float(match.group(1)), float(match.group(2))
- diag = pow((pow(w, 2) + pow(h, 2)), 0.5)
- diag /= 23.5
- diag *= .91666 # fudge factor
- answer += " {%.1f\" diagonal?}" % diag
- break
- res.stdout.close()
- return answer.strip()
- def prettyScreenDiag():
- answer = "Get a measuring tape, measure from the lower-left corner\n"
- answer += "across to the upper-right corner, in inches ie. 15.7\" diagonal\n"
- return answer.strip()
- def prettyBattery():
- # this works on Ubuntu w/ GNOME, don't know about Kubuntu or Fedora or others
- res = subprocess.Popen(['upower', '-e'], stdout=subprocess.PIPE)
- bnames = []
- for line in res.stdout.readlines():
- if 'battery' in line:
- bnames.append(line.strip())
- res.stdout.close()
- answer = ''
- for batt in bnames:
- battery = {}
- res = subprocess.Popen(['upower', '-i', batt], stdout=subprocess.PIPE)
- for line in res.stdout.readlines():
- match = re.match(r'\s*(.*?):\s*(.*)', line.strip())
- if match is not None:
- k, v = match.group(1), match.group(2)
- if k in ('model', 'technology'):
- battery[k] = v
- elif k in ('energy-full', 'energy-full-design', 'energy-rate'):
- battery[k] = float(v[:-2].strip())
- answer += battery['model'] + ' ' + battery.get('technology', '')
- if battery.get('energy-rate', 0) < 7:
- battery['energy-rate'] = 12.0 # fudge factor, my laptop eats 17 watts
- # print "QUACK: %.1f / %.1f" % (battery['energy-full'], battery['energy-rate'])
- omnomnom = battery['energy-full'] / battery['energy-rate']
- answer += ' {approx %.1f hours}' % omnomnom
- if 'energy-full' in battery and 'energy-full-design' in battery:
- decay = ((battery['energy-full-design'] - battery['energy-full']) * 100) / battery['energy-full-design']
- if decay > 1:
- answer += ' (lost %d%% of max capacity)' % decay
- answer += "\n"
- return answer.strip()
- class StupidGTK:
- " Because GTK wants an entire class for the one object "
- def make_label(self):
- result = []
- result.append("<b>Processor</b>")
- result.append(prettyCPUs(getCPUs()))
- result.append("<b>Disk Drives</b>")
- result.append(prettyDiskSizes(getDiskSizes()))
- result.append("<b>Memory Size</b>")
- result.append(prettyMemInfo(getMemInfo()))
- result.append("<b>Linux version</b>")
- result.append(prettyDistro())
- result.append(prettyKernel())
- result.append("<b>Battery Life</b>")
- result.append(prettyBattery())
- result.append("<b>Video Cards</b>")
- result.append(prettyVGAcard())
- result.append("<b>Screen size</b>")
- result.append(prettyScreensize())
- result.append(prettyScreenDiag())
- return '\n'.join(result)
- def __init__(self):
- self.window1 = gtk.Window(gtk.WINDOW_TOPLEVEL)
- self.window1.set_border_width(10)
- self.window1.connect('destroy', lambda i: gtk.main_quit())
- self.window1.set_title("HW List for Mom")
- self.box1 = gtk.VBox(False, 7)
- self.label1 = gtk.Label()
- #self.label1.set_text(self.make_label())
- self.label1.set_markup(self.make_label())
- self.label1.set_selectable(True)
- self.box1.pack_start(self.label1, True, True, 0)
- self.button1 = gtk.Button("Okay")
- self.button1.connect_object('clicked', gtk.Widget.destroy, self.window1)
- self.box1.pack_end(self.button1, False, False, 0)
- self.window1.add(self.box1)
- self.window1.show_all() # gotta be a better way than just "all"
- def main(self):
- gtk.main()
- if __name__ == '__main__':
- WIND = StupidGTK()
- WIND.main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement