misc.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. from __future__ import unicode_literals
  2. import inspect
  3. from future.utils import PY2, PY3, exec_
  4. if PY2:
  5. from collections import Mapping
  6. else:
  7. from collections.abc import Mapping
  8. if PY3:
  9. import builtins
  10. from collections.abc import Mapping
  11. def apply(f, *args, **kw):
  12. return f(*args, **kw)
  13. from past.builtins import str as oldstr
  14. def chr(i):
  15. """
  16. Return a byte-string of one character with ordinal i; 0 <= i <= 256
  17. """
  18. return oldstr(bytes((i,)))
  19. def cmp(x, y):
  20. """
  21. cmp(x, y) -> integer
  22. Return negative if x<y, zero if x==y, positive if x>y.
  23. """
  24. return (x > y) - (x < y)
  25. from sys import intern
  26. def oct(number):
  27. """oct(number) -> string
  28. Return the octal representation of an integer
  29. """
  30. return '0' + builtins.oct(number)[2:]
  31. raw_input = input
  32. from imp import reload
  33. unicode = str
  34. unichr = chr
  35. xrange = range
  36. else:
  37. import __builtin__
  38. from collections import Mapping
  39. apply = __builtin__.apply
  40. chr = __builtin__.chr
  41. cmp = __builtin__.cmp
  42. execfile = __builtin__.execfile
  43. intern = __builtin__.intern
  44. oct = __builtin__.oct
  45. raw_input = __builtin__.raw_input
  46. reload = __builtin__.reload
  47. unicode = __builtin__.unicode
  48. unichr = __builtin__.unichr
  49. xrange = __builtin__.xrange
  50. if PY3:
  51. def execfile(filename, myglobals=None, mylocals=None):
  52. """
  53. Read and execute a Python script from a file in the given namespaces.
  54. The globals and locals are dictionaries, defaulting to the current
  55. globals and locals. If only globals is given, locals defaults to it.
  56. """
  57. if myglobals is None:
  58. # There seems to be no alternative to frame hacking here.
  59. caller_frame = inspect.stack()[1]
  60. myglobals = caller_frame[0].f_globals
  61. mylocals = caller_frame[0].f_locals
  62. elif mylocals is None:
  63. # Only if myglobals is given do we set mylocals to it.
  64. mylocals = myglobals
  65. if not isinstance(myglobals, Mapping):
  66. raise TypeError('globals must be a mapping')
  67. if not isinstance(mylocals, Mapping):
  68. raise TypeError('locals must be a mapping')
  69. with open(filename, "rb") as fin:
  70. source = fin.read()
  71. code = compile(source, filename, "exec")
  72. exec_(code, myglobals, mylocals)
  73. if PY3:
  74. __all__ = ['apply', 'chr', 'cmp', 'execfile', 'intern', 'raw_input',
  75. 'reload', 'unichr', 'unicode', 'xrange']
  76. else:
  77. __all__ = []