python2x3.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. # coding=utf-8
  2. #!/usr/bin/env python
  3. # pylint: disable=invalid-name
  4. # invalid-name: We define a few global-scope constants in lower case. Deal with it.
  5. '''Provides code and data to facilitate writing python code that runs on 2.x and 3.x, including pypy'''
  6. # I'm afraid pylint won't like this one...
  7. import sys
  8. def python_major():
  9. '''Return an integer corresponding to the major version # of the python interpreter we're running on'''
  10. # This originally used the platform module, but platform fails on IronPython; sys.version seems to work
  11. # on everything I've tried
  12. result = sys.version_info[0]
  13. return result
  14. if python_major() == 2:
  15. empty_bytes = ''
  16. null_byte = '\0'
  17. bytes_type = str
  18. def intlist_to_binary(intlist):
  19. '''Convert a list of integers to a binary string type'''
  20. return ''.join(chr(byte) for byte in intlist)
  21. def string_to_binary(string):
  22. '''Convert a text string to a binary string type'''
  23. return string
  24. def binary_to_intlist(binary):
  25. '''Convert a binary string to a list of integers'''
  26. return [ord(character) for character in binary]
  27. def binary_to_string(binary):
  28. '''Convert a binary string to a text string'''
  29. return binary
  30. elif python_major() == 3:
  31. empty_bytes = ''.encode('utf-8')
  32. null_byte = bytes([0])
  33. bytes_type = bytes
  34. def intlist_to_binary(intlist):
  35. '''Convert a list of integers to a binary string type'''
  36. return bytes(intlist)
  37. def string_to_binary(string):
  38. '''Convert a text string (or binary string type) to a binary string type'''
  39. if isinstance(string, str):
  40. return string.encode('latin-1')
  41. else:
  42. return string
  43. def binary_to_intlist(binary):
  44. '''Convert a binary string to a list of integers'''
  45. return binary
  46. def binary_to_string(binary):
  47. '''Convert a binary string to a text string'''
  48. return binary.decode('latin-1')
  49. else:
  50. sys.stderr.write('%s: Python < 2 or > 3 not (yet) supported\n' % sys.argv[0])
  51. sys.exit(1)