Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
py3status modules
# -*- coding: utf-8 -*-
#
# custom compiled modules for py3status
#
# ----------------------------------------------------------------- #
# Notes:
# 1. netdata will check 'eth0' interface by default. You can
# change it by changing 'self.net_interface' variable in 'GetData'
# class.
# 2. Colors are depended on strict specification in traffic/netspeed methods.
# You can change them by manipulating conditions.
from __future__ import division # python2 compatibility
import subprocess
import math
import re
from time import time, strftime
from syslog import syslog, LOG_ERR, LOG_INFO, LOG_WARNING
# Method 'netSpeed' will use this variables to calculate downloaded
# bytes in last second. Initializing this variables globally is
# necessary since we can't use __init__ method in Py3Status class.
old_transmitted, old_received = 0, 0
class GetData:
"""
Get system status
"""
def __init__(self):
# You can change it to another interface.
# It'll be used for grabbing net interface data.
self.net_interface = 'wlp5s0'
def execCMD(self, cmd, arg):
"""Take a system command and its argument, then return the result.
Arguments:
- `cmd`: system command.
- `arg`: argument.
"""
result = subprocess.check_output([cmd, arg])
return result
def get_uevent_data(self,path):
lines = subprocess.check_output(['cat',path]).decode('utf-8').splitlines()
def sp(line):
p = line.split('=')
yield p[0]
yield p[1]
return dict(map(sp,lines))
def netBytes(self):
"""Execute 'cat /proc/net/dev', find the interface line (Default
'eth0') and grab received/transmitted bytes.
"""
net_data = self.execCMD('cat', '/proc/net/dev').decode('utf-8').split()
interface_index = net_data.index(self.net_interface + ':')
received_bytes = int(net_data[interface_index + 1])
transmitted_bytes = int(net_data[interface_index + 9])
return received_bytes, transmitted_bytes
def cpu(self):
"""Get the cpu usage data from /proc/stat :
cpu 2255 34 2290 22625563 6290 127 456 0 0
- user: normal processes executing in user mode
- nice: niced processes executing in user mode
- system: processes executing in kernel mode
- idle: twiddling thumbs
- iowait: waiting for I/O to complete
- irq: servicing interrupts
- softirq: servicing softirqs
- steal: involuntary wait
- guest: running a normal guest
- guest_nice: running a niced guest
These numbers identify the amount of time the CPU has spent performing
different kinds of work. Time units are in USER_HZ (typically hundredths of a
second)
"""
with open('/proc/stat', 'r') as fd:
line = fd.readline()
cpu_data = line.split()
total_cpu_time = sum(map(int, cpu_data[1:]))
cpu_idle_time = int(cpu_data[4])
#return the cpu total&idle time
return total_cpu_time, cpu_idle_time
class Py3status:
"""
System status in i3bar
"""
def __init__(self):
self.data = GetData()
self.cpu_total = 0
self.cpu_idle = 0
def cpuInfo(self, json, i3status_config):
"""calculate the CPU status and return it.
"""
response = {'full_text': '', 'name': 'cpu_usage'}
cpu_total, cpu_idle = self.data.cpu()
used_cpu_percent = 1 - float(cpu_idle-self.cpu_idle)/float(cpu_total-self.cpu_total)
self.cpu_total = cpu_total
self.cpu_idle = cpu_idle
if used_cpu_percent <= 40/100.0:
response['color'] = i3status_config['color_good']
elif used_cpu_percent <= 75/100.0:
response['color'] = i3status_config['color_degraded']
else:
response['color'] = i3status_config['color_bad']
response['full_text'] = "CPU %.1f%%" % (used_cpu_percent*100)
#cache the status for 10 seconds
response['cached_until'] = time() + 1
return (1, response)
def netSpeed(self, json, i3status_config):
"""Calculate network speed ('eth0' interface) and return it. You can
change the interface using 'self.net_interface' variable in
'GetData' class.
"""
response = {'full_text': '', 'name': 'net_speed'}
global old_received
global old_transmitted
received_bytes, transmitted_bytes = self.data.netBytes()
dl_speed = (received_bytes - old_received) / 1024.
up_speed = (transmitted_bytes - old_transmitted) / 1024.
if dl_speed > 700:
response['color'] = i3status_config['color_bad']
elif dl_speed > 200:
response['color'] = i3status_config['color_degraded']
else:
response['color'] = i3status_config['color_good']
response['full_text'] = "{:5.1f}{:4.1f}"\
.format(dl_speed, up_speed)
response['cached_until'] = time()
old_received, old_transmitted = received_bytes, transmitted_bytes
return (0, response)
def battery_level(self, i3status_output_json, i3status_config):
response = {'name': 'battery-level'}
txt = ""
adapter = self.data.get_uevent_data('/sys/class/power_supply/ADP1/uevent')
data = self.data.get_uevent_data('/sys/class/power_supply/BAT0/uevent')
# percentage of the design level
charge = float(data['POWER_SUPPLY_CHARGE_NOW'])
perc = 100.0*charge/float(data['POWER_SUPPLY_CHARGE_FULL_DESIGN'])
txt += '%.1f%% ' % perc
current = float(data['POWER_SUPPLY_CURRENT_NOW'])
# colors
response['color'] = i3status_config['color_good']
if perc < 30:
response['color'] = i3status_config['color_degraded']
if perc < 10:
response['color'] = i3status_config['color_bad']
# charging state
online = "1" == adapter['POWER_SUPPLY_ONLINE']
if online:
txt += ""
if online and current > 0:
response['color'] = "#FCE94F"
txt += ""
# remaining time
if current > 0 and not online:
hours = charge/current
mins = (hours - int(hours))*60
txt += "%i:%.2i" % (int(hours),int(mins))
response['full_text'] = "BAT " + txt
response['cached_until'] = time() + 5
return (40, response)
def clock(self, i3status_output_json, i3status_config):
return (50, {'name': 'battery-level',
'cached_until': time(),
'color': '#FFFFFF',
'full_text': strftime('%F %T') })
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.