Guest User

Untitled

a guest
Dec 13th, 2017
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 4.49 KB | None | 0 0
  1. #!/usr/bin/env python
  2.  
  3. from threading import Thread,Lock,Event,Timer
  4. import os
  5. import sys
  6. import signal
  7. import subprocess
  8. import math
  9. import psutil
  10. import re
  11. import time
  12.  
  13. mutex = Lock()
  14. thread_data = []
  15.  
  16. class UpdaterThread(Thread):
  17. def __init__(self, id, sleep, callback):
  18. Thread.__init__(self)
  19. self.stopped = Event()
  20. self.id = id
  21. self.sleeptime = sleep
  22. self.callback = callback
  23.  
  24. def stop(self):
  25. self.stopped.set()
  26.  
  27. def run(self):
  28. thread_data[self.id] = self.callback()
  29. with mutex:
  30. update()
  31. while not self.stopped.is_set():
  32. flagged = self.stopped.wait(
  33. self.sleeptime
  34. )
  35. if not flagged:
  36. thread_data[self.id] = self.callback()
  37. with mutex:
  38. update()
  39.  
  40. def update():
  41. subprocess.call([
  42. "xsetroot",
  43. "-name",
  44. " | ".join(thread_data)
  45. ])
  46.  
  47. def start(conf):
  48. threads = []
  49. for i in range(len(conf)):
  50. thread_data.append("...")
  51. t = UpdaterThread(
  52. i,
  53. conf[i]['sleep'],
  54. conf[i]['callback']
  55. )
  56. t.setDaemon(True)
  57. threads.append(t)
  58. for t in threads:
  59. t.start()
  60. try:
  61. signal.pause()
  62. except (KeyboardInterrupt, SystemExit):
  63. print("stopping threads")
  64. for t in threads:
  65. t.stop()
  66. for t in threads:
  67. t.join()
  68. print("bye!")
  69. return 0
  70.  
  71. #### vvv configuration vvv ####
  72.  
  73. def datetime():
  74. return "".join([' ',time.strftime("%m-%d-%y - %H:%M:%S"),' '])
  75.  
  76. def wifi():
  77. dev = "wlp2s0"
  78. wifi_info = open("/proc/net/wireless").read()
  79. signal_strength = 0
  80. try:
  81. essid = re.sub(
  82. r'^.*"([^"]*).*"',
  83. r'\1',
  84. str(subprocess.check_output(
  85. ["iwgetid"],
  86. shell=False
  87. ).strip()))
  88. except:
  89. essid = "(x)"
  90. try:
  91. signal_strength = int(int(re.findall(r'{}:\s*\S*\s*(\d*)'.format(dev), wifi_info)[0])/70.0*100)
  92. except:
  93. signal_strength = 0
  94. output = ['wi: ']
  95. output.append('({}) '.format(essid))
  96. output.append('{}'.format(percent(signal_strength)))
  97. return "".join(output)
  98.  
  99. def battery():
  100. acpath = "/sys/class/power_supply/AC0"
  101. batpath = "/sys/class/power_supply/BAT0"
  102. ac_online = int(open(acpath+'/online','r').read().strip())
  103. max = int(open(batpath+'/energy_full','r').read().strip())
  104. cur = int(open(batpath+'/energy_now','r').read().strip())
  105. pct = int(100*float(cur)/float(max))
  106. output = ['bat: ']
  107. output.append("{}".format(percent(pct)))
  108. output.append("(")
  109. if ac_online:
  110. if pct == 100:
  111. output.append("+")
  112. else:
  113. output.append("~")
  114. else:
  115. output.append("-")
  116. output.append(")")
  117. return "".join(output)
  118.  
  119. def cpu():
  120. cpus = psutil.cpu_percent(interval=.5, percpu=True)
  121.  
  122. mhz = re.search(
  123. "cpu MHz\s*:\s*(\S*)",
  124. open('/proc/cpuinfo','r'
  125. ).read()).groups()[0].split('.')[0]
  126.  
  127. output = [' cpu: '];
  128. output.append('{}Mz'.format(mhz))
  129. output.append('(')
  130. cpu_data = " ".join(map(lambda x: percent(int(x)), cpus))
  131. output.append(cpu_data)
  132. # for c in cpus:
  133. # output.append('{}'.format(percent(int(c))))
  134. # #output.append("{0: >3}% ".format(int(c)))
  135. output.append(')')
  136. return "".join(output)
  137.  
  138. def mem():
  139. minfo = psutil.virtual_memory()
  140. output = ['mem:']
  141. output.append("{0: >3}%".format(int(minfo.percent)))
  142. return "".join(output)
  143.  
  144. def vol():
  145. mixerinfo = subprocess. \
  146. check_output(['amixer', 'get', 'Master'], shell=False). \
  147. decode('utf-8'). \
  148. split('\n')[-2]
  149. master_vol = int(re.search(r'\[(\d*)%\]', mixerinfo).groups()[0])
  150. muted = re.search(r'\[(on|off)\]', mixerinfo).groups()[0]
  151. output = ['vol: ']
  152. output.append("{}".format(percent(master_vol)))
  153. if muted == 'off':
  154. output.append('M')
  155. return "".join(output)
  156.  
  157. def percent(pct=0):
  158. return f"{pct}%"
  159.  
  160. if __name__ == '__main__':
  161. conf = [
  162. {
  163. "sleep":2,
  164. "callback":cpu,
  165. },
  166. {
  167. "sleep":10,
  168. "callback":mem,
  169. },
  170. {
  171. "sleep":3,
  172. "callback":wifi,
  173. },
  174. {
  175. "sleep":1,
  176. "callback":vol,
  177. },
  178. {
  179. "sleep":10,
  180. "callback":battery,
  181. },
  182. {
  183. "sleep":1,
  184. "callback":datetime,
  185. },
  186. ]
  187. sys.exit(start(conf))
Add Comment
Please, Sign In to add comment