From 0ae5a430e4f92ee7bf9e458cf584a0a12fd5c25a Mon Sep 17 00:00:00 2001 From: mikeos Date: Mon, 30 Sep 2013 04:36:57 +0400 Subject: refactoring --- coding.py | 44 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 coding.py (limited to 'coding.py') diff --git a/coding.py b/coding.py new file mode 100644 index 0000000..ffae410 --- /dev/null +++ b/coding.py @@ -0,0 +1,44 @@ +import sys + +if sys.version_info.major == 2: + def is_python_v2(): + return True + + def to_unicode(buf): + if type(buf) is unicode: + return buf + return buf.decode("utf-8") + + def to_bytes(buf): + if type(buf) is unicode: + return buf.encode("utf-8") + return buf + + class Encoded: + def __init__(self, stream): + self.stream = stream + + def write(self, msg): + if type(msg) is unicode: + self.stream.write(msg.encode("utf-8")) + else: + self.stream.write(msg) + + def __getattr__(self, attr): + return getattr(self.stream, attr) + + sys.stdout = Encoded(sys.stdout) + sys.stderr = Encoded(sys.stderr) +else: + def is_python_v2(): + return False + + def to_unicode(buf): + if type(buf) is bytes: + return buf.decode("utf-8") + return buf + + def to_bytes(buf): + if type(buf) is bytes: + return buf + return bytes(buf, "utf-8") -- cgit v1.2.3-70-g09d2