def toggle_connection(self): if self.connected: command = self.vpn_down_command else: command = self.vpn_up_command run_through_shell(command % {'vpn_name': self.vpn_name}, enable_shell=True)
def rfkill_switch(self): run_through_shell([ "rfkill", "unblock" if self.data["soft_bool"] else "block", str(self.data["index"]) if self.rfkill_override_command_name is None else self.rfkill_override_command_name, ])
def set_lock(self, unlock=False): if unlock: command = "enable" else: command = "disable" run_through_shell(f"xinput {command} {self._device_id}") open(self.lock_file, mode="w").close()
def updates(self): cache_dir = "/tmp/update-cache-" + os.getenv("USER") if not os.path.exists(cache_dir): os.mkdir(cache_dir) command = "apt-get update -o Dir::State::Lists=" + cache_dir run_through_shell(command.split()) command = "apt-get upgrade -s -o Dir::State::Lists=" + cache_dir apt = run_through_shell(command.split()) out = apt.out.splitlines() out = [line[5:] for line in out if line.startswith("Inst ")] return len(out), out
def updates(self): cache_dir = "/tmp/update-cache-" + os.getenv("USER") if not os.path.exists(cache_dir): os.mkdir(cache_dir) command = "apt-get update -o Dir::State::Lists=" + cache_dir run_through_shell(command.split()) command = "apt-get upgrade -s -o Dir::State::Lists=" + cache_dir apt = run_through_shell(command.split()) update_count = 0 for line in apt.out.split("\n"): if line.startswith("Inst"): update_count += 1 return update_count
def updates(self): command = ["yaourt", "-Qua"] checkupdates = run_through_shell(command) out = checkupdates.out if (self.aur_only): out = [line for line in out if line.startswith("aur")] return out.count("\n"), out
def change_brightness(self): process = Popen(["xbacklight"], stdout=PIPE) output, error = process.communicate() process.wait() current = round(float(output[:-1])) if current == 100.0: setback = 15 elif current == 15.0: setback = 30 elif current == 30.0: setback = 50 else: setback = 100 run_through_shell(["xbacklight", "-set", str(setback)])
def on_click(self, button): """ Maps a click event (include mousewheel events) with its associated callback. It then triggers the callback depending on the nature (ie type) of the callback variable: 1. if null callback, do nothing 2. if it's a python function () 3. if it's the name of a method of the current module (string) To setup the callbacks, you can set the settings 'on_leftclick', 'on_rightclick', 'on_upscroll', 'on_downscroll'. For instance, you can test with: :: status.register("clock", format=[ ("Format 0",'Europe/London'), ("%a %-d Format 1",'Europe/Dublin'), "%a %-d %b %X format 2", ("%a %-d %b %X format 3", 'Europe/Paris'), ], on_leftclick= ["urxvtc"] , # launch urxvtc on left click on_rightclick= ["scroll_format", 2] , # update format by steps of 2 on_upscroll= [print, "hello world"] , # call python function print log_level=logging.DEBUG, ) """ def split_callback_and_args(cb): if isinstance(cb, list): return cb[0], cb[1:] else: return cb, [] cb = None if button == 1: # Left mouse button cb = self.on_leftclick elif button == 3: # Right mouse button cb = self.on_rightclick elif button == 4: # mouse wheel up cb = self.on_upscroll elif button == 5: # mouse wheel down cb = self.on_downscroll else: self.logger.info("Button '%d' not handled yet." % (button)) return if not cb: self.logger.info("no cb attached") return else: cb, args = split_callback_and_args(cb) self.logger.debug("cb=%s args=%s" % (cb, args)) if callable(cb): return cb(self) elif hasattr(self, cb): return getattr(self, cb)(*args) else: return run_through_shell(cb, *args)
def updates(self): command = ["yaourt", "-Qua"] checkupdates = run_through_shell(command) out = checkupdates.out if(self.aur_only): out = [line for line in out if line.startswith("aur")] return out.count("\n"), out
def updates(self): command = ["yaourt", "-Qua"] checkupdates = run_through_shell(command) out = checkupdates.out if (self.aur_only): out = "".join([line for line in out.splitlines(True)]) return out.count("\n"), out
def findDeviceNumber(self): command = 'solaar show' retvalue, out, stderr = run_through_shell(command, enable_shell=True) for line in out.split('\n'): if line.count(self.nameOfDevice) > 0 and line.count(':') > 0: numberOfDevice = line.split(':')[0] return numberOfDevice raise DeviceNotFound()
def updates(self): if (self.aur_only): command = ["yay", "-Qua"] else: command = ["yay", "-Qu"] checkupdates = run_through_shell(command) out = checkupdates.out return out.count("\n"), out
def run(self): self.status = run_through_shell("xset -q | grep -q 'DPMS is Enabled'", True).rc == 0 self.output = { "full_text": self.format.format(status='on' if self.status else 'off'), "color": self.color if self.status else self.color_disabled }
def darker(self): # if self.has_xbacklight: # pr = float(run_through_shell(["xbacklight", "-get"]).out) # pr = pr * 0.1 # if pr<1.0: # pr = 1 # run_through_shell(["xbacklight", "-"+str(pr), "-time", "0"]) pr = run_through_shell(["/etc/acpi/actions/bl_down.sh", ""]) return pr
def updates(self): command = "pkcon get-updates -p" pk = run_through_shell(command.split()) out = pk.out.splitlines(True) resultStrings = ("Security", "Bug fix", "Enhancement") out = "".join([line for line in out[out.index("Results:\n") + 1:] if line.startswith(resultStrings)]) return out.count("\n"), out
def updates(self): command = ["dnf", "check-update"] dnf = run_through_shell(command) update_count = 0 if dnf.rc == 100: lines = dnf.out.splitlines()[2:] lines = [l for l in lines if len(split("\s{2,}", l.rstrip())) == 3] update_count = len(lines) return update_count
def findBatteryStatus(self, numberOfDevice): command = 'solaar-cli show -v %s' % (numberOfDevice) retvalue, out, stderr = run_through_shell(command, enable_shell=True) for line in out.split('\n'): if line.count('Battery') > 0: if line.count(':') > 0: batterystatus = line.split(':')[1].strip().strip(",") return(0, batterystatus) else: return(1, 0) return(1, 0)
def findBatteryStatus(self, numberOfDevice): command = 'solaar show %s' % (numberOfDevice) retvalue, out, stderr = run_through_shell(command, enable_shell=True) for line in out.split('\n'): if line.count('Battery') > 0: if line.count(':') > 0: batterystatus = line.split(':')[1].strip().strip(",") return batterystatus elif line.count('offline'): raise NoBatteryStatus('offline') else: raise NoBatteryStatus('unknown') raise NoBatteryStatus('unknown/error')
def _device_id(self): command = run_through_shell("xinput list") rval = "" if command.rc == 0: for line in command.out.splitlines(): match = self.find_regex.match(line) if match: rval = match.groupdict().get("yubid", "") break return rval
def run(self): self.status = run_through_shell("xset -q | grep -q 'DPMS is Enabled'", True).rc == 0 if self.status: self.output = { "full_text": self.format.format(status="off"), "color": self.color } else: self.output = { "full_text": self.format_disabled.format(status="off"), "color": self.color_disabled }
def updates(self): command = ["dnf", "check-update"] dnf = run_through_shell(command) if dnf.err: return "?", dnf.err raw = dnf.out update_count = 0 if dnf.rc == 100: lines = raw.splitlines()[2:] lines = [l for l in lines if len(split("\s+", l.rstrip())) == 3] update_count = len(lines) notif_body = sub(r"(\S+)\s+(\S+)\s+\S+\s*\n", r"\1: \2\n", raw) return update_count, notif_body
def run(self): retvalue, out, stderr = run_through_shell(self.command, enable_shell=True) if retvalue != 0: self.logger.error(stderr if stderr else "Unknown error") if out: out.replace("\n", " ").strip() elif stderr: out = stderr self.output = { "full_text": out if out else "Command `%s` returned %d" % (self.command, retvalue), "color": self.color if retvalue == 0 else self.error_color }
def run(self): retvalue, out, stderr = run_through_shell(self.command, enable_shell=True) if retvalue != 0: self.logger.error(stderr if stderr else "Unknown error") if out: out = out.replace("\n", " ").strip() elif stderr: out = stderr self.output = { "full_text": self.format.format(output=out) if out else "Command `%s` returned %d" % (self.command, retvalue), "color": self.color if retvalue == 0 else self.error_color }
def run(self): command_result = run_through_shell(self.status_command % {'vpn_name': self.vpn_name}, enable_shell=True) self.connected = True if command_result.out.strip() else False if self.connected: color, status = self.color_up, self.status_up else: color, status = self.color_down, self.status_down vpn_name = self.vpn_name label = self.label self.data = locals() self.output = { "full_text": self.format.format(**locals()), 'color': color, }
def run(self): command_result = run_through_shell(self.status_command % {'vpn_name': self.vpn_name}, enable_shell=True) output = command_result.out.strip() if output == 'active': color = self.colour_up status = '▲' else: color = self.colour_down status = '▼' vpn_name = self.vpn_name label = self.label self.output = { "full_text": self.format.format(**locals()), 'color': color, }
def device_status(self): rval = "notfound" if not self._device_id: return rval result = run_through_shell(f"xinput list-props {self._device_id}") if result.rc == 0: match = self.status_regex.match(result.out.splitlines()[1]) if match and "status" in match.groupdict(): status = int(match.groupdict()["status"]) if status: rval = "unlocked" else: rval = "locked" return rval
def run(self): retvalue, out, stderr = run_through_shell(self.command, enable_shell=True) if retvalue != 0: self.logger.error(stderr if stderr else "Unknown error") if out: out = out.replace("\n", " ").strip() elif stderr: out = stderr full_text = self.format.format(output=out).strip() if not full_text and not self.ignore_empty_stdout: full_text = "Command `%s` returned %d" % (self.command, retvalue) self.output = { "full_text": full_text, "color": self.color if retvalue == 0 else self.error_color }
def run(self): command_result = run_through_shell(self.status_command % {'vpn_name': self.vpn_name}, enable_shell=True) output = command_result.out.strip() if output: color = self.color_up status = self.status_up format = self.format_up else: color = self.color_down status = self.status_down format = self.format_down vpn_name = self.vpn_name label = self.label self.data = locals() self.output = { "full_text": format.format(**locals()), 'color': color, }
def run(self): retvalue, out, stderr = run_through_shell(self.command, enable_shell=True) if retvalue != 0: self.logger.error(stderr if stderr else "Unknown error") if out: out = out.replace("\n", " ").strip() elif stderr: out = stderr if self.blank_on_empty_stdout and not out and not stderr: full_text = "" else: full_text = self.format.format(output=out).strip() if not full_text and not self.ignore_empty_stdout: full_text = "Command `%s` returned %d" % (self.command, retvalue) self.output = { "full_text": full_text, "color": self.color if retvalue == 0 else self.error_color }
def toggle_dpms(self): if self.status: run_through_shell("xset -dpms s off", True) else: run_through_shell("xset +dpms s on", True)
def updates(self): command = ["checkupdates"] checkupdates = run_through_shell(command) return checkupdates.out.count("\n"), checkupdates.out
def lighter(self): if self.has_xbacklight: run_through_shell(["xbacklight", "-inc", str(self.step_size)])
def darker(self): if self.has_xbacklight: run_through_shell(["xbacklight", "-dec", str(self.step_size)])
def enable_dpms(self): if self.status: run_through_shell("xset -dpms s off", True) else: run_through_shell("xset +dpms s on", True) run_through_shell("xset s 120 10", True)
def open_client(self): if self.email_client: retcode, _, stderr = run_through_shell(self.email_client) if retcode != 0 and stderr: self.logger.error(stderr)
def _cmus_command(self, command): cmdline = 'cmus-remote --{command}'.format(command=command) return run_through_shell(cmdline, enable_shell=True)
def backlight_down(): run_through_shell(["xbacklight", "-dec", 10])
def updates(self): command = ["auracle", "sync"] auracle = run_through_shell(command) return auracle.out.count('\n'), auracle.out
def run(self): urgent = False color = self.color batteries = [] for path in self.paths: if self.battery_ident == 'ALL' or path.find(self.battery_ident) >= 0: try: batteries.append(Battery.create(path)) except FileNotFoundError: pass if not batteries: format_dict = {'battery_ident': self.battery_ident} self.output = { "full_text": formatp(self.not_present_text, **format_dict), "color": self.not_present_color, } return if self.no_text_full: if self.battery_status(batteries) == "Full": self.output = { "full_text": "" } return fdict = { "battery_ident": self.battery_ident, "no_of_batteries": len(batteries), "percentage": self.percentage(batteries), "percentage_design": self.percentage(batteries, design=True), "consumption": self.consumption(batteries), "remaining": TimeWrapper(0, "%E%h:%M"), "bar": make_bar(self.percentage(batteries)), "bar_design": make_bar(self.percentage(batteries, design=True)), } status = self.battery_status(batteries) if status in ["Charging", "Discharging"]: remaining = self.remaining(batteries) fdict["remaining"] = TimeWrapper(remaining * 60, "%E%h:%M") if status == "Discharging": fdict["status"] = "DIS" if self.percentage(batteries) <= self.alert_percentage: urgent = True color = self.critical_color else: fdict["status"] = "CHR" color = self.charging_color elif status == 'Depleted': fdict["status"] = "DPL" color = self.critical_color else: fdict["status"] = "FULL" color = self.full_color if self.critical_level_command and fdict["status"] == "DIS" and fdict["percentage"] <= self.critical_level_percentage: run_through_shell(self.critical_level_command, enable_shell=True) if self.alert and fdict["status"] == "DIS" and fdict["percentage"] <= self.alert_percentage: title, body = formatp(self.alert_format_title, **fdict), formatp(self.alert_format_body, **fdict) if not self.notification: self.notification = DesktopNotification( title=title, body=body, icon="battery-caution", urgency=2, timeout=self.alert_timeout, ) self.notification.display() else: self.notification.update(title=title, body=body) fdict["status"] = self.status[fdict["status"]] self.data = fdict self.output = { "full_text": formatp(self.format, **fdict), "instance": self.battery_ident, "urgent": urgent, "color": color, }
def updates(self): command = ["cower", "-u"] cower = run_through_shell(command) return cower.out.count('\n'), cower.out
def test_program_failure(self): success, out, err = run_through_shell("thisshouldtriggeranerror") self.assertFalse(success)
def test_shell_correct_output(self): # ShellTest test # http://python.readthedocs.org/en/latest/library/unittest.html retcode, out, err = run_through_shell("echo '%s'" % (self.valid_output), enable_shell=True) self.assertTrue(retcode == 0) self.assertEqual(out.strip(), self.valid_output)
def run(self): urgent = False color = self.color batteries = [] for path in self.paths: if self.battery_ident == 'ALL' or path.find( self.battery_ident) >= 0: try: batteries.append(Battery.create(path)) except FileNotFoundError: pass if not batteries: format_dict = {'battery_ident': self.battery_ident} self.output = { "full_text": formatp(self.not_present_text, **format_dict), "color": self.not_present_color, } return if self.no_text_full: if self.battery_status(batteries) == "Full": self.output = {"full_text": ""} return fdict = { "battery_ident": self.battery_ident, "no_of_batteries": len(batteries), "percentage": self.percentage(batteries), "percentage_design": self.percentage(batteries, design=True), "consumption": self.consumption(batteries), "remaining": TimeWrapper(0, "%E%h:%M"), "bar": make_bar(self.percentage(batteries)), "bar_design": make_bar(self.percentage(batteries, design=True)), } status = self.battery_status(batteries) if status in ["Charging", "Discharging"]: remaining = self.remaining(batteries) fdict["remaining"] = TimeWrapper(remaining * 60, "%E%h:%M") if status == "Discharging": fdict["status"] = "DIS" if self.percentage(batteries) <= self.alert_percentage: urgent = True color = self.critical_color else: fdict["status"] = "CHR" color = self.charging_color elif status == 'Depleted': fdict["status"] = "DPL" color = self.critical_color else: fdict["status"] = "FULL" color = self.full_color if self.critical_level_command and fdict["status"] == "DIS" and fdict[ "percentage"] <= self.critical_level_percentage: run_through_shell(self.critical_level_command, enable_shell=True) if self.alert and fdict["status"] == "DIS" and fdict[ "percentage"] <= self.alert_percentage: DesktopNotification( title=formatp(self.alert_format_title, **fdict), body=formatp(self.alert_format_body, **fdict), icon="battery-caution", urgency=2, timeout=60, ).display() fdict["status"] = self.status[fdict["status"]] self.data = fdict self.output = { "full_text": formatp(self.format, **fdict), "instance": self.battery_ident, "urgent": urgent, "color": color, }
def on_click(self, button): """ Maps a click event (include mousewheel events) with its associated callback. It then triggers the callback depending on the nature (ie type) of the callback variable: 1. if null callback, do nothing 2. if it's a python function () 3. if it's the name of a method of the current module (string) To setup the callbacks, you can set the settings 'on_leftclick', 'on_rightclick', 'on_upscroll', 'on_downscroll'. For instance, you can test with: :: status.register("clock", format=[ ("Format 0",'Europe/London'), ("%a %-d Format 1",'Europe/Dublin'), "%a %-d %b %X format 2", ("%a %-d %b %X format 3", 'Europe/Paris'), ], on_leftclick= ["urxvtc"] , # launch urxvtc on left click on_rightclick= ["scroll_format", 2] , # update format by steps of 2 on_upscroll= [print, "hello world"] , # call python function print log_level=logging.DEBUG, ) """ def split_callback_and_args(cb): if isinstance(cb, list): return cb[0], cb[1:] else: return cb, [] cb = None if button == 1: # Left mouse button cb = self.on_leftclick elif button == 3: # Right mouse button cb = self.on_rightclick elif button == 4: # mouse wheel up cb = self.on_upscroll elif button == 5: # mouse wheel down cb = self.on_downscroll else: self.logger.info("Button '%d' not handled yet." % (button)) return False if not cb: self.logger.info("no cb attached") return False else: cb, args = split_callback_and_args(cb) self.logger.debug("cb=%s args=%s" % (cb, args)) if callable(cb): cb(self) elif hasattr(self, cb): if cb is not "run": getattr(self, cb)(*args) else: run_through_shell(cb, *args) return True
def run(self): urgent = False color = self.color batteries = [] for path in self.paths: if self.battery_ident == 'ALL' or path.find( self.battery_ident) >= 0: try: batteries.append(Battery.create(path)) except FileNotFoundError: pass if not batteries: format_dict = {'battery_ident': self.battery_ident} self.output = { "full_text": formatp(self.not_present_text, **format_dict), "color": self.not_present_color, } return if self.no_text_full: if self.battery_status(batteries) == "Full": self.output = {"full_text": ""} return fdict = { "battery_ident": self.battery_ident, "no_of_batteries": len(batteries), "percentage": self.percentage(batteries), "percentage_design": self.percentage(batteries, design=True), "consumption": self.consumption(batteries), "remaining": TimeWrapper(0, "%E%h:%M"), "glyph": make_glyph(self.percentage(batteries), self.glyphs), "bar": make_bar(self.percentage(batteries)), "bar_design": make_bar(self.percentage(batteries, design=True)), "vertical_bar": make_vertical_bar(self.percentage(batteries)), "vertical_bar_design": make_vertical_bar(self.percentage(batteries, design=True)), } status = self.battery_status(batteries) if status in ["Charging", "Discharging"]: remaining = self.remaining(batteries) fdict["remaining"] = TimeWrapper(remaining * 60, "%E%h:%M") if status == "Discharging": fdict["status"] = "DIS" if self.percentage(batteries) <= self.alert_percentage: urgent = True color = self.critical_color else: fdict["status"] = "CHR" color = self.charging_color elif status == 'Depleted': fdict["status"] = "DPL" color = self.critical_color else: fdict["status"] = "FULL" color = self.full_color if self.critical_level_command and fdict["status"] == "DIS" and fdict[ "percentage"] <= self.critical_level_percentage: run_through_shell(self.critical_level_command, enable_shell=True) self.alert_if_low_battery(fdict) if self.levels and fdict['status'] == 'DIS': self.levels.setdefault(0, self.status.get('DPL', 'DPL')) self.levels.setdefault(100, self.status.get('FULL', 'FULL')) keys = sorted(self.levels.keys()) index = bisect.bisect_left(keys, int(fdict['percentage'])) fdict["status"] = self.levels[keys[index]] else: fdict["status"] = self.status[fdict["status"]] self.data = fdict self.output = { "full_text": formatp(self.format, **fdict), "instance": self.battery_ident, "urgent": urgent, "color": color, }
status.register("pulseaudio", color_muted=colors["red"], color_unmuted=colors["green"], format=" {volume}", hints=create_hints(), on_leftclick="switch_mute", on_rightclick="change_sink", on_doubleleftclick="pavucontrol", ) status.register("shell", color=colors["bright"], command="""echo " $(gpg-connect-agent 'keyinfo --list' '/bye' | grep -e '^S KEYINFO .* 1 P ' -c)" """, hints=create_hints(), interval=10, on_leftclick=lambda mod: run_through_shell(["killall", "-s", "HUP", "gpg-agent"]), ) # default_family = netifaces.AF_INET # default_gateways = netifaces.gateways().get("default", {}) # if default_family in default_gateways: # default_interface = default_gateways[default_family][1] # else: # default_interface = "lo" status.register("network", color_down=colors["red"], color_up=colors["green"], divisor=1024**2, end_color=colors["red"], format_down=" {interface}",