_pypy_interact.py 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. """Imported by app_main.py when PyPy needs to fire up the interactive console.
  2. """
  3. import sys
  4. import os
  5. irc_header = "And now for something completely different"
  6. def interactive_console(mainmodule=None, quiet=False):
  7. # set sys.{ps1,ps2} just before invoking the interactive interpreter. This
  8. # mimics what CPython does in pythonrun.c
  9. if not hasattr(sys, 'ps1'):
  10. sys.ps1 = '>>>> '
  11. if not hasattr(sys, 'ps2'):
  12. sys.ps2 = '.... '
  13. #
  14. if not quiet:
  15. try:
  16. from _pypy_irc_topic import some_topic
  17. text = "%s: ``%s''" % ( irc_header, some_topic())
  18. while len(text) >= 80:
  19. i = text[:80].rfind(' ')
  20. print(text[:i])
  21. text = text[i+1:]
  22. print(text)
  23. except ImportError:
  24. pass
  25. #
  26. run_interactive = run_simple_interactive_console
  27. try:
  28. if not os.isatty(sys.stdin.fileno()):
  29. # Bail out if stdin is not tty-like, as pyrepl wouldn't be happy
  30. # For example, with:
  31. # subprocess.Popen(['pypy', '-i'], stdin=subprocess.PIPE)
  32. raise ImportError
  33. from pyrepl.simple_interact import check
  34. if not check():
  35. raise ImportError
  36. from pyrepl.simple_interact import run_multiline_interactive_console
  37. run_interactive = run_multiline_interactive_console
  38. except ImportError:
  39. pass
  40. except SyntaxError:
  41. print("Warning: 'import pyrepl' failed with SyntaxError")
  42. run_interactive(mainmodule)
  43. def run_simple_interactive_console(mainmodule):
  44. import code
  45. if mainmodule is None:
  46. import __main__ as mainmodule
  47. console = code.InteractiveConsole(mainmodule.__dict__, filename='<stdin>')
  48. # some parts of code.py are copied here because it was impossible
  49. # to start an interactive console without printing at least one line
  50. # of banner. This was fixed in 3.4; but then from 3.6 it prints a
  51. # line when exiting. This can be disabled too---by passing an argument
  52. # that doesn't exist in <= 3.5. So, too much mess: just copy the code.
  53. more = 0
  54. while 1:
  55. try:
  56. if more:
  57. prompt = getattr(sys, 'ps2', '... ')
  58. else:
  59. prompt = getattr(sys, 'ps1', '>>> ')
  60. try:
  61. line = input(prompt)
  62. except EOFError:
  63. console.write("\n")
  64. break
  65. else:
  66. more = console.push(line)
  67. except KeyboardInterrupt:
  68. console.write("\nKeyboardInterrupt\n")
  69. console.resetbuffer()
  70. more = 0
  71. # ____________________________________________________________
  72. if __name__ == '__main__': # for testing
  73. if os.getenv('PYTHONSTARTUP'):
  74. exec(compile(open(os.getenv('PYTHONSTARTUP')).read(), os.getenv('PYTHONSTARTUP'), 'exec'))
  75. interactive_console()