diff --git a/README.md b/README.md index e6295711..b97d2626 100644 --- a/README.md +++ b/README.md @@ -319,6 +319,19 @@ The options for the `time` segment are: - `format`: Format string as used by strftime function, e.g. `%H:%M`. +The options for the `stdout` segment are: +- `command`: A list of arguments determining the command to run. +- `fg_color`: The foreground color of the segment when the command succeeded. +- `bg_color`: The background color of the segment when the command succeeded. +- `error_fg_color`: The foreground color of the segment when the command + returned a non-zero exit code. +- `error_bg_color`: The background color of the segment when the command + returned a non-zero exit code. +- `allow_error`: If true, the segment will be shown when the command returns a + non-zero exit code. +- `hide_empty`: If true, the segment will not be shown when the command outputs + an empty string or only whitespace. + ### Contributing new types of segments The `powerline_shell/segments` directory contains python scripts which are diff --git a/powerline_shell/segments/stdout.py b/powerline_shell/segments/stdout.py index 9286245e..a9368ce5 100644 --- a/powerline_shell/segments/stdout.py +++ b/powerline_shell/segments/stdout.py @@ -1,17 +1,50 @@ import subprocess -from ..utils import ThreadedSegment +from ..utils import ThreadedSegment, warn class Segment(ThreadedSegment): def run(self): - cmd = self.segment_def["command"] - self.output = subprocess.check_output(cmd).decode("utf-8").strip() - # TODO handle OSError - # TODO handle no command defined or malformed + cmd = self.segment_def.get("command", []) + + if len(cmd) == 0: + warn("no command specified") + self.output = None + return + + try: + self.output = subprocess.check_output(cmd).decode("utf-8").strip() + self.success = True + except subprocess.CalledProcessError as ex: + if self.segment_def.get("allow_error", True): + self.output = ex.output.decode("utf-8").strip() + else: + self.output = None + + self.success = False + + # TODO handle malformed command def add_to_powerline(self): self.join() - self.powerline.append( - " %s " % self.output, - self.segment_def.get("fg_color", self.powerline.theme.PATH_FG), - self.segment_def.get("bg_color", self.powerline.theme.PATH_BG)) + + if self.output is None: + return + + if self.success: + fg_color = self.segment_def.get("fg_color", self.powerline.theme.PATH_FG) + bg_color = self.segment_def.get("bg_color", self.powerline.theme.PATH_BG) + else: + fg_color = self.segment_def.get("error_fg_color", self.powerline.theme.CMD_FAILED_FG) + bg_color = self.segment_def.get("error_bg_color", self.powerline.theme.CMD_FAILED_BG) + + for i, line in enumerate(self.output.split("\n")): + line = line.strip() + if len(line) == 0 and self.segment_def.get("hide_empty", False): + continue + + if i > 0: + self.powerline.append("\n", + self.powerline.theme.RESET, + self.powerline.theme.RESET, + separator="") + self.powerline.append(" %s " % line, fg_color, bg_color)