summaryrefslogtreecommitdiff
path: root/utils.py
blob: ffae410847ac08476c29cbba0c0bc11f25d7b611 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
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")