Guest User

Untitled

a guest
Nov 15th, 2018
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.14 KB | None | 0 0
  1. #!/usr/bin/env python3
  2. """
  3. ioreg displays the I/O Kit registry. It shows the heirarchical registry structure as an inverted tree.
  4. This script lists the ioreg output to a tmp file and then finds the battery and keyboard percentages in
  5. a very brute force / un-inspired way.
  6.  
  7. It works for me though.
  8.  
  9. macOs Mojave
  10. Version 10.14.1
  11. iMac Pro 2017
  12.  
  13. MIT License Copyright 2018 T Griffin
  14. """
  15. import subprocess
  16. import sys
  17. import os
  18.  
  19. def myReplace(line):
  20. """
  21. Cleans a list of characters off the ioreg line with the
  22. battery percentages. Yes regex exists, I know.
  23. """
  24. chars = ['"','|',' ',',',"\n"]
  25. for c in chars:
  26. line = line.replace(c,'')
  27. return line
  28.  
  29. def printBatteryLifeBar(percent):
  30. battery = "🔋"
  31.  
  32. trim = percent % 10
  33.  
  34. percent -= trim
  35.  
  36. while percent > 0:
  37. print(battery, end = '')
  38. percent = percent - 10
  39.  
  40.  
  41. # Run ioreg command
  42. # Why dump to file? I had issues converting from a byte type to utf-8
  43. # losing line endings. I didn't want to spend any more time (minutes)
  44. # so I moved on.
  45. output = subprocess.getoutput("ioreg -l > /tmp/ioreg.out")
  46.  
  47. # Flags to turn on mouse battery life value, or keyboard
  48. mouse = False
  49. keyboard = False
  50.  
  51. # Dictionary of results
  52. batteryLife = {"mouse":None,"keyboard":None}
  53.  
  54. # Open temp file
  55. ioreg = open("/tmp/ioreg.out","r")
  56.  
  57. # Search for magic mouse and magic keyboard in file.
  58. # Find either, turn mouse or keyboard flag on and other off.
  59. # Next "batterypercent" value will be associated with device
  60. # with a flag that is on.
  61. for line in ioreg.readlines():
  62. if line.lower().find("magic mouse") > 0:
  63. mouse = True
  64. keyboard = False
  65. if line.lower().find("magic keyboard") > 0:
  66. mouse = False
  67. keyboard = True
  68. if line.lower().find("batterypercent") > 0:
  69. line = myReplace(line)
  70. key,val = line.split('=')
  71. if mouse:
  72. batteryLife['mouse'] = val
  73. elif keyboard:
  74. batteryLife['keyboard'] = val
  75.  
  76. print("🖱️ = ", end='')
  77. printBatteryLifeBar(int(batteryLife['mouse']))
  78. print(batteryLife['mouse']+"%")
  79. print("⌨️ = ", end='')
  80. printBatteryLifeBar(int(batteryLife['keyboard']))
  81. print(batteryLife['keyboard']+"%")
Add Comment
Please, Sign In to add comment