import subprocess from i3pystatus import IntervalModule class Ping(IntervalModule): interval = 2 settings = ( ("host", "host to ping"), ("format", "format string"), ("format_down", "format down string"), ("format_pause", "format pause string"), ("color", "color"), ("color_down", "color down"), ("color_pause", "color pause") ) active = True color = "#FFFFFF" color_down = "#FF0000" color_pause = "#FF4500" format = "{ping} ms" format_down = "{ping} ms" format_pause = "{ping} ms" host = "8.8.8.8" on_leftclick = "switch_state" def ping_host(self): p = subprocess.Popen(["ping", "-c1", "-w%d" % self.interval, self.host], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) out, _ = p.communicate() if p.returncode == 0: return out.decode().split("\n")[1].split("time=")[1].split()[0] else: return "" def run(self): if not self.active: self.output = { "full_text": self.format_pause.format(ping=0), "color": self.color_pause } return ping = self.ping_host() if not ping: self.output = { "full_text": self.format_down, "color": self.color_down } return ping = float(ping) self.output = { "full_text": self.format.format(ping=ping), "color": self.color } def switch_state(self): self.active = not self.active