From dfb1e394214d8d308e842952f92fbbe5c41c7607 Mon Sep 17 00:00:00 2001 From: Tobias Witek Date: Sat, 16 Sep 2017 12:22:20 +0200 Subject: [PATCH] [core + modules/cmus] Have another go at fixing unicode issues Override sys.stdout and sys.stderr in an attempt to enforce utf-8 encoding. Probably this will cause all kinds of weird issues down the line, but at least, it seems to solve the immediate issue. fixes #176 --- bumblebee-status | 25 +++++++++++++++++++++++++ bumblebee/modules/cmus.py | 5 ----- 2 files changed, 25 insertions(+), 5 deletions(-) diff --git a/bumblebee-status b/bumblebee-status index f28dc7c..41e8636 100755 --- a/bumblebee-status +++ b/bumblebee-status @@ -10,6 +10,28 @@ import bumblebee.output import bumblebee.input import bumblebee.modules.error +# taken from +# https://stackoverflow.com/a/42146082 +# seems an excellent solution to me +class SmartStdout: + def __init__(self, encoding=None, org_stdout=None): + if org_stdout is None: + org_stdout = getattr(sys.stdout, 'org_stdout', sys.stdout) + self.org_stdout = org_stdout + self.encoding = encoding or getattr(org_stdout, 'encoding', None) or 'utf-8' + + def write(self, s): + self.org_stdout.write(s.encode(self.encoding, 'backslashreplace')) + + def __getattr__(self, name): + return getattr(self.org_stdout, name) + +def set_defaultencoding_globally(encoding='utf-8'): + assert sys.getdefaultencoding() in ('ascii', 'mbcs', encoding) + import imp + _sys_org = imp.load_dynamic('_sys_org', 'sys') + _sys_org.setdefaultencoding(encoding) + def main(): config = bumblebee.config.Config(sys.argv[1:]) @@ -63,6 +85,9 @@ def main(): time.sleep(1) if __name__ == "__main__": + if sys.stdout.isatty(): + sys.stdout = sys.stderr = SmartStdout() + set_defaultencoding_globally('utf-8') main() # vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4 diff --git a/bumblebee/modules/cmus.py b/bumblebee/modules/cmus.py index 62fbfaf..2db4c0c 100644 --- a/bumblebee/modules/cmus.py +++ b/bumblebee/modules/cmus.py @@ -1,5 +1,4 @@ # pylint: disable=C0111,R0903 -# -*- coding: utf-8 -*- """Displays information about the current song in cmus. @@ -69,10 +68,6 @@ class Module(bumblebee.engine.Module): return returns.get(widget.name, self._status) def _eval_line(self, line): - # not a typo, use decode detection to see whether we are - # dealing with Python2 or Python3 - if hasattr(line, "decode"): - line = line.encode("utf-8", "replace") name, key, value = (line.split(" ", 2) + [None, None])[:3] if name == "status":