console.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. from __future__ import print_function # PY2
  2. import __main__
  3. import code
  4. import sys
  5. from .info import PY2
  6. def print_banner(file=sys.stderr):
  7. print("Python {} on {}".format(sys.version, sys.platform), file=file)
  8. print('Type "help", "copyright", "credits" or "license" for more information.', file=file)
  9. # PY3 # class InteractiveConsole(code.InteractiveConsole):
  10. class InteractiveConsole(code.InteractiveConsole, object):
  11. # code.InteractiveConsole without banner
  12. # exits on EOF
  13. # also more robust treating of sys.ps1, sys.ps2
  14. # prints prompt into stderr rather than stdout
  15. # flushes sys.stderr and sys.stdout
  16. def __init__(self, locals=None, filename="<stdin>"):
  17. self.done = False
  18. # PY3 # super().__init__(locals, filename)
  19. super(InteractiveConsole, self).__init__(locals, filename)
  20. def raw_input(self, prompt=""):
  21. sys.stderr.write(prompt)
  22. if PY2:
  23. return raw_input()
  24. else:
  25. return input()
  26. def runcode(self, code):
  27. # PY3 # super().runcode(code)
  28. super(InteractiveConsole, self).runcode(code)
  29. sys.stderr.flush()
  30. sys.stdout.flush()
  31. def interact(self):
  32. #sys.ps1 = "~>> "
  33. #sys.ps2 = "~.. "
  34. try:
  35. sys.ps1
  36. except AttributeError:
  37. sys.ps1 = ">>> "
  38. try:
  39. sys.ps2
  40. except AttributeError:
  41. sys.ps2 = "... "
  42. more = 0
  43. while not self.done:
  44. try:
  45. if more:
  46. try:
  47. prompt = sys.ps2
  48. except AttributeError:
  49. prompt = ""
  50. else:
  51. try:
  52. prompt = sys.ps1
  53. except AttributeError:
  54. prompt = ""
  55. try:
  56. line = self.raw_input(prompt)
  57. except EOFError:
  58. self.on_EOF()
  59. else:
  60. more = self.push(line)
  61. except KeyboardInterrupt:
  62. self.write("\nKeyboardInterrupt\n")
  63. self.resetbuffer()
  64. more = 0
  65. def on_EOF(self):
  66. self.write("\n")
  67. # PY3 # raise SystemExit from None
  68. raise SystemExit
  69. running_console = None
  70. def enable():
  71. global running_console
  72. if running_console is not None:
  73. raise RuntimeError("interactive console already running")
  74. else:
  75. running_console = InteractiveConsole(__main__.__dict__)
  76. running_console.interact()
  77. def disable():
  78. global running_console
  79. if running_console is None:
  80. raise RuntimeError("interactive console is not running")
  81. else:
  82. running_console.done = True
  83. running_console = None