/wxgeometrie/sympy/interactive/session.py

https://github.com/Grahack/geophar · Python · 172 lines · 125 code · 36 blank · 11 comment · 35 complexity · 063be200da31f1321b2e29c22ef7e436 MD5 · raw file

  1. """Tools for setting up interactive sessions. """
  2. from sympy.interactive.printing import init_printing
  3. preexec_source = """\
  4. from __future__ import division
  5. from sympy import *
  6. x, y, z, t = symbols('x y z t')
  7. k, m, n = symbols('k m n', integer=True)
  8. f, g, h = symbols('f g h', cls=Function)
  9. """
  10. verbose_message = """\
  11. These commands were executed:
  12. %(source)s
  13. Documentation can be found at http://www.sympy.org
  14. """
  15. no_ipython = """\
  16. Couldn't locate IPython. Having IPython installed is greatly recommended.
  17. See http://ipython.scipy.org for more details. If you use Debian/Ubuntu,
  18. just install the 'ipython' package and start isympy again.
  19. """
  20. def _make_message(ipython=True, quiet=False, source=None):
  21. """Create a banner for an interactive session. """
  22. from sympy import __version__ as sympy_version
  23. from sympy.polys.domains import GROUND_TYPES
  24. from sympy.utilities.misc import ARCH
  25. import sys
  26. import os
  27. python_version = "%d.%d.%d" % sys.version_info[:3]
  28. if ipython:
  29. shell_name = "IPython"
  30. else:
  31. shell_name = "Python"
  32. info = ['ground types: %s' % GROUND_TYPES]
  33. cache = os.getenv('SYMPY_USE_CACHE')
  34. if cache is not None and cache.lower() == 'no':
  35. info.append('cache: off')
  36. args = shell_name, sympy_version, python_version, ARCH, ', '.join(info)
  37. message = "%s console for SymPy %s (Python %s-%s) (%s)\n" % args
  38. if not quiet:
  39. if source is None:
  40. source = preexec_source
  41. _source = ""
  42. for line in source.split('\n')[:-1]:
  43. if not line:
  44. _source += '\n'
  45. else:
  46. _source += '>>> ' + line + '\n'
  47. message += '\n' + verbose_message % {'source': _source}
  48. return message
  49. def _init_ipython_session(argv=[]):
  50. """Construct new IPython session. """
  51. import IPython
  52. if IPython.__version__ >= '0.11':
  53. from IPython.frontend.terminal import ipapp
  54. # use an app to parse the command line, and init config
  55. app = ipapp.TerminalIPythonApp()
  56. # don't draw IPython banner during initialization:
  57. app.display_banner = False
  58. app.initialize(argv)
  59. return app.shell
  60. else:
  61. from IPython.Shell import make_IPython
  62. return make_IPython(argv)
  63. def _init_python_session():
  64. """Construct new Python session. """
  65. from code import InteractiveConsole
  66. class SymPyConsole(InteractiveConsole):
  67. """An interactive console with readline support. """
  68. def __init__(self):
  69. InteractiveConsole.__init__(self)
  70. try:
  71. import readline
  72. except ImportError:
  73. pass
  74. else:
  75. import os
  76. import atexit
  77. readline.parse_and_bind('tab: complete')
  78. if hasattr(readline, 'read_history_file'):
  79. history = os.path.expanduser('~/.sympy-history')
  80. try:
  81. readline.read_history_file(history)
  82. except IOError:
  83. pass
  84. atexit.register(readline.write_history_file, history)
  85. return SymPyConsole()
  86. def init_session(ipython=None, pretty_print=True, order=None,
  87. use_unicode=None, quiet=False, argv=[]):
  88. """Initialize an embedded IPython or Python session. """
  89. import sys
  90. in_ipython = False
  91. if ipython is False:
  92. ip = _init_python_session()
  93. mainloop = ip.interact
  94. else:
  95. try:
  96. import IPython
  97. except ImportError:
  98. if ipython is not True:
  99. print no_ipython
  100. ip = _init_python_session()
  101. mainloop = ip.interact
  102. else:
  103. raise RuntimeError("IPython is not available on this system")
  104. else:
  105. ipython = True
  106. if IPython.__version__ >= '0.11':
  107. try:
  108. ip = get_ipython()
  109. except NameError:
  110. ip = None
  111. else:
  112. ip = IPython.ipapi.get()
  113. if ip:
  114. ip = ip.IP
  115. if ip is not None:
  116. in_ipython = True
  117. else:
  118. ip = _init_ipython_session(argv)
  119. if IPython.__version__ >= '0.11':
  120. # runsource is gone, use run_cell instead, which doesn't
  121. # take a symbol arg. The second arg is `store_history`,
  122. # and False means don't add the line to IPython's history.
  123. ip.runsource = lambda src, symbol='exec': ip.run_cell(src, False)
  124. mainloop = ip.mainloop
  125. else:
  126. mainloop = ip.interact
  127. _preexec_source = preexec_source
  128. ip.runsource(_preexec_source, symbol='exec')
  129. init_printing(pretty_print=pretty_print, order=order, use_unicode=use_unicode, ip=ip)
  130. message = _make_message(ipython, quiet, _preexec_source)
  131. if not in_ipython:
  132. mainloop(message)
  133. sys.exit('Exiting ...')
  134. else:
  135. ip.write(message)
  136. ip.set_hook('shutdown_hook', lambda ip: ip.write("Exiting ...\n"))