compat.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. import sys
  2. if sys.version_info < (3,):
  3. def isbasestring(s):
  4. return isinstance(s, basestring)
  5. def open_utf8(filename, mode):
  6. return open(filename, mode)
  7. def byte_to_str(x):
  8. return str(ord(x))
  9. import cStringIO
  10. def StringIO():
  11. return cStringIO.StringIO()
  12. def encode_utf8(x):
  13. return x
  14. def decode_utf8(x):
  15. return x
  16. def iteritems(d):
  17. return d.iteritems()
  18. def itervalues(d):
  19. return d.itervalues()
  20. def escape_string(s):
  21. if isinstance(s, unicode):
  22. s = s.encode('ascii')
  23. result = ''
  24. for c in s:
  25. if not (32 <= ord(c) < 127) or c in ('\\', '"'):
  26. result += '\\%03o' % ord(c)
  27. else:
  28. result += c
  29. return result
  30. else:
  31. def isbasestring(s):
  32. return isinstance(s, (str, bytes))
  33. def open_utf8(filename, mode):
  34. return open(filename, mode, encoding="utf-8")
  35. def byte_to_str(x):
  36. return str(x)
  37. import io
  38. def StringIO():
  39. return io.StringIO()
  40. import codecs
  41. def encode_utf8(x):
  42. return codecs.utf_8_encode(x)[0]
  43. def decode_utf8(x):
  44. return codecs.utf_8_decode(x)[0]
  45. def iteritems(d):
  46. return iter(d.items())
  47. def itervalues(d):
  48. return iter(d.values())
  49. def charcode_to_c_escapes(c):
  50. rev_result = []
  51. while c >= 256:
  52. c, low = (c // 256, c % 256)
  53. rev_result.append('\\%03o' % low)
  54. rev_result.append('\\%03o' % c)
  55. return ''.join(reversed(rev_result))
  56. def escape_string(s):
  57. result = ''
  58. if isinstance(s, str):
  59. s = s.encode('utf-8')
  60. for c in s:
  61. if not(32 <= c < 127) or c in (ord('\\'), ord('"')):
  62. result += charcode_to_c_escapes(c)
  63. else:
  64. result += chr(c)
  65. return result