isympy.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  1. """
  2. Python shell for SymPy.
  3. This is just a normal Python shell (IPython shell if you have the
  4. IPython package installed), that executes the following commands for
  5. the user:
  6. >>> from __future__ import division
  7. >>> from sympy import *
  8. >>> x, y, z, t = symbols('x y z t')
  9. >>> k, m, n = symbols('k m n', integer=True)
  10. >>> f, g, h = symbols('f g h', cls=Function)
  11. >>> init_printing()
  12. So starting 'isympy' is equivalent to starting Python (or IPython) and
  13. executing the above commands by hand. It is intended for easy and quick
  14. experimentation with SymPy. isympy is a good way to use SymPy as an
  15. interactive calculator. If you have IPython and Matplotlib installed, then
  16. interactive plotting is enabled by default.
  17. COMMAND LINE OPTIONS
  18. --------------------
  19. -c CONSOLE, --console=CONSOLE
  20. Use the specified shell (Python or IPython) shell as the console
  21. backend instead of the default one (IPython if present, Python
  22. otherwise), e.g.:
  23. $isympy -c python
  24. CONSOLE must be one of 'ipython' or 'python'
  25. -p PRETTY, --pretty PRETTY
  26. Setup pretty-printing in SymPy. When pretty-printing is enabled,
  27. expressions can be printed with Unicode or ASCII. The default is
  28. to use pretty-printing (with Unicode if the terminal supports it).
  29. When this option is 'no', expressions will not be pretty-printed
  30. and ASCII will be used:
  31. $isympy -p no
  32. PRETTY must be one of 'unicode', 'ascii', or 'no'
  33. -t TYPES, --types=TYPES
  34. Setup the ground types for the polys. By default, gmpy ground types
  35. are used if gmpy2 or gmpy is installed, otherwise it falls back to python
  36. ground types, which are a little bit slower. You can manually
  37. choose python ground types even if gmpy is installed (e.g., for
  38. testing purposes):
  39. $isympy -t python
  40. TYPES must be one of 'gmpy', 'gmpy1' or 'python'
  41. Note that the ground type gmpy1 is primarily intended for testing; it
  42. forces the use of gmpy version 1 even if gmpy2 is available.
  43. This is the same as setting the environment variable
  44. SYMPY_GROUND_TYPES to the given ground type (e.g.,
  45. SYMPY_GROUND_TYPES='gmpy')
  46. The ground types can be determined interactively from the variable
  47. sympy.polys.domains.GROUND_TYPES.
  48. -o ORDER, --order ORDER
  49. Setup the ordering of terms for printing. The default is lex, which
  50. orders terms lexicographically (e.g., x**2 + x + 1). You can choose
  51. other orderings, such as rev-lex, which will use reverse
  52. lexicographic ordering (e.g., 1 + x + x**2):
  53. $isympy -o rev-lex
  54. ORDER must be one of 'lex', 'rev-lex', 'grlex', 'rev-grlex',
  55. 'grevlex', 'rev-grevlex', 'old', or 'none'.
  56. Note that for very large expressions, ORDER='none' may speed up
  57. printing considerably but the terms will have no canonical order.
  58. -q, --quiet
  59. Print only Python's and SymPy's versions to stdout at startup.
  60. -d, --doctest
  61. Use the same format that should be used for doctests. This is
  62. equivalent to -c python -p no.
  63. -C, --no-cache
  64. Disable the caching mechanism. Disabling the cache may slow certain
  65. operations down considerably. This is useful for testing the cache,
  66. or for benchmarking, as the cache can result in deceptive timings.
  67. This is equivalent to setting the environment variable
  68. SYMPY_USE_CACHE to 'no'.
  69. -a, --auto-symbols (requires at least IPython 0.11)
  70. Automatically create missing symbols. Normally, typing a name of a
  71. Symbol that has not been instantiated first would raise NameError,
  72. but with this option enabled, any undefined name will be
  73. automatically created as a Symbol.
  74. Note that this is intended only for interactive, calculator style
  75. usage. In a script that uses SymPy, Symbols should be instantiated
  76. at the top, so that it's clear what they are.
  77. This will not override any names that are already defined, which
  78. includes the single character letters represented by the mnemonic
  79. QCOSINE (see the "Gotchas and Pitfalls" document in the
  80. documentation). You can delete existing names by executing "del
  81. name". If a name is defined, typing "'name' in dir()" will return True.
  82. The Symbols that are created using this have default assumptions.
  83. If you want to place assumptions on symbols, you should create them
  84. using symbols() or var().
  85. Finally, this only works in the top level namespace. So, for
  86. example, if you define a function in isympy with an undefined
  87. Symbol, it will not work.
  88. See also the -i and -I options.
  89. -i, --int-to-Integer (requires at least IPython 0.11)
  90. Automatically wrap int literals with Integer. This makes it so that
  91. things like 1/2 will come out as Rational(1, 2), rather than 0.5. This
  92. works by preprocessing the source and wrapping all int literals with
  93. Integer. Note that this will not change the behavior of int literals
  94. assigned to variables, and it also won't change the behavior of functions
  95. that return int literals.
  96. If you want an int, you can wrap the literal in int(), e.g. int(3)/int(2)
  97. gives 1.5 (with division imported from __future__).
  98. -I, --interactive (requires at least IPython 0.11)
  99. This is equivalent to --auto-symbols --int-to-Integer. Future options
  100. designed for ease of interactive use may be added to this.
  101. -D, --debug
  102. Enable debugging output. This is the same as setting the
  103. environment variable SYMPY_DEBUG to 'True'. The debug status is set
  104. in the variable SYMPY_DEBUG within isympy.
  105. -- IPython options
  106. Additionally you can pass command line options directly to the IPython
  107. interpreter (the standard Python shell is not supported). However you
  108. need to add the '--' separator between two types of options, e.g the
  109. startup banner option and the colors option. You need to enter the
  110. options as required by the version of IPython that you are using, too:
  111. in IPython 0.11,
  112. $isympy -q -- --colors=NoColor
  113. or older versions of IPython,
  114. $isympy -q -- -colors NoColor
  115. See also isympy --help.
  116. """
  117. import os
  118. import sys
  119. # DO NOT IMPORT SYMPY HERE! Or the setting of the sympy environment variables
  120. # by the command line will break.
  121. def main() -> None:
  122. from argparse import ArgumentParser, RawDescriptionHelpFormatter
  123. VERSION = None
  124. if '--version' in sys.argv:
  125. # We cannot import sympy before this is run, because flags like -C and
  126. # -t set environment variables that must be set before SymPy is
  127. # imported. The only thing we need to import it for is to get the
  128. # version, which only matters with the --version flag.
  129. import sympy
  130. VERSION = sympy.__version__
  131. usage = 'isympy [options] -- [ipython options]'
  132. parser = ArgumentParser(
  133. usage=usage,
  134. description=__doc__,
  135. formatter_class=RawDescriptionHelpFormatter,
  136. )
  137. parser.add_argument('--version', action='version', version=VERSION)
  138. parser.add_argument(
  139. '-c', '--console',
  140. dest='console',
  141. action='store',
  142. default=None,
  143. choices=['ipython', 'python'],
  144. metavar='CONSOLE',
  145. help='select type of interactive session: ipython | python; defaults '
  146. 'to ipython if IPython is installed, otherwise python')
  147. parser.add_argument(
  148. '-p', '--pretty',
  149. dest='pretty',
  150. action='store',
  151. default=None,
  152. metavar='PRETTY',
  153. choices=['unicode', 'ascii', 'no'],
  154. help='setup pretty printing: unicode | ascii | no; defaults to '
  155. 'unicode printing if the terminal supports it, otherwise ascii')
  156. parser.add_argument(
  157. '-t', '--types',
  158. dest='types',
  159. action='store',
  160. default=None,
  161. metavar='TYPES',
  162. choices=['gmpy', 'gmpy1', 'python'],
  163. help='setup ground types: gmpy | gmpy1 | python; defaults to gmpy if gmpy2 '
  164. 'or gmpy is installed, otherwise python')
  165. parser.add_argument(
  166. '-o', '--order',
  167. dest='order',
  168. action='store',
  169. default=None,
  170. metavar='ORDER',
  171. choices=['lex', 'grlex', 'grevlex', 'rev-lex', 'rev-grlex', 'rev-grevlex', 'old', 'none'],
  172. help='setup ordering of terms: [rev-]lex | [rev-]grlex | [rev-]grevlex | old | none; defaults to lex')
  173. parser.add_argument(
  174. '-q', '--quiet',
  175. dest='quiet',
  176. action='store_true',
  177. default=False,
  178. help='print only version information at startup')
  179. parser.add_argument(
  180. '-d', '--doctest',
  181. dest='doctest',
  182. action='store_true',
  183. default=False,
  184. help='use the doctest format for output (you can just copy and paste it)')
  185. parser.add_argument(
  186. '-C', '--no-cache',
  187. dest='cache',
  188. action='store_false',
  189. default=True,
  190. help='disable caching mechanism')
  191. parser.add_argument(
  192. '-a', '--auto-symbols',
  193. dest='auto_symbols',
  194. action='store_true',
  195. default=False,
  196. help='automatically construct missing symbols')
  197. parser.add_argument(
  198. '-i', '--int-to-Integer',
  199. dest='auto_int_to_Integer',
  200. action='store_true',
  201. default=False,
  202. help="automatically wrap int literals with Integer")
  203. parser.add_argument(
  204. '-I', '--interactive',
  205. dest='interactive',
  206. action='store_true',
  207. default=False,
  208. help="equivalent to -a -i")
  209. parser.add_argument(
  210. '-D', '--debug',
  211. dest='debug',
  212. action='store_true',
  213. default=False,
  214. help='enable debugging output')
  215. (options, ipy_args) = parser.parse_known_args()
  216. if '--' in ipy_args:
  217. ipy_args.remove('--')
  218. if not options.cache:
  219. os.environ['SYMPY_USE_CACHE'] = 'no'
  220. if options.types:
  221. os.environ['SYMPY_GROUND_TYPES'] = options.types
  222. if options.debug:
  223. os.environ['SYMPY_DEBUG'] = str(options.debug)
  224. if options.doctest:
  225. options.pretty = 'no'
  226. options.console = 'python'
  227. session = options.console
  228. if session is not None:
  229. ipython = session == 'ipython'
  230. else:
  231. try:
  232. import IPython
  233. ipython = True
  234. except ImportError:
  235. if not options.quiet:
  236. from sympy.interactive.session import no_ipython
  237. print(no_ipython)
  238. ipython = False
  239. args = {
  240. 'pretty_print': True,
  241. 'use_unicode': None,
  242. 'use_latex': None,
  243. 'order': None,
  244. 'argv': ipy_args,
  245. }
  246. if options.pretty == 'unicode':
  247. args['use_unicode'] = True
  248. elif options.pretty == 'ascii':
  249. args['use_unicode'] = False
  250. elif options.pretty == 'no':
  251. args['pretty_print'] = False
  252. if options.order is not None:
  253. args['order'] = options.order
  254. args['quiet'] = options.quiet
  255. args['auto_symbols'] = options.auto_symbols or options.interactive
  256. args['auto_int_to_Integer'] = options.auto_int_to_Integer or options.interactive
  257. from sympy.interactive import init_session
  258. init_session(ipython, **args)
  259. if __name__ == "__main__":
  260. main()