shellapp.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  1. # encoding: utf-8
  2. """
  3. A mixin for :class:`~IPython.core.application.Application` classes that
  4. launch InteractiveShell instances, load extensions, etc.
  5. """
  6. # Copyright (c) IPython Development Team.
  7. # Distributed under the terms of the Modified BSD License.
  8. from __future__ import absolute_import
  9. from __future__ import print_function
  10. import glob
  11. import os
  12. import sys
  13. from traitlets.config.application import boolean_flag
  14. from traitlets.config.configurable import Configurable
  15. from traitlets.config.loader import Config
  16. from IPython.core import pylabtools
  17. from IPython.utils import py3compat
  18. from IPython.utils.contexts import preserve_keys
  19. from IPython.utils.path import filefind
  20. from traitlets import (
  21. Unicode, Instance, List, Bool, CaselessStrEnum, observe,
  22. )
  23. from IPython.terminal import pt_inputhooks
  24. #-----------------------------------------------------------------------------
  25. # Aliases and Flags
  26. #-----------------------------------------------------------------------------
  27. gui_keys = tuple(sorted(pt_inputhooks.backends) + sorted(pt_inputhooks.aliases))
  28. backend_keys = sorted(pylabtools.backends.keys())
  29. backend_keys.insert(0, 'auto')
  30. shell_flags = {}
  31. addflag = lambda *args: shell_flags.update(boolean_flag(*args))
  32. addflag('autoindent', 'InteractiveShell.autoindent',
  33. 'Turn on autoindenting.', 'Turn off autoindenting.'
  34. )
  35. addflag('automagic', 'InteractiveShell.automagic',
  36. """Turn on the auto calling of magic commands. Type %%magic at the
  37. IPython prompt for more information.""",
  38. 'Turn off the auto calling of magic commands.'
  39. )
  40. addflag('pdb', 'InteractiveShell.pdb',
  41. "Enable auto calling the pdb debugger after every exception.",
  42. "Disable auto calling the pdb debugger after every exception."
  43. )
  44. addflag('pprint', 'PlainTextFormatter.pprint',
  45. "Enable auto pretty printing of results.",
  46. "Disable auto pretty printing of results."
  47. )
  48. addflag('color-info', 'InteractiveShell.color_info',
  49. """IPython can display information about objects via a set of functions,
  50. and optionally can use colors for this, syntax highlighting
  51. source code and various other elements. This is on by default, but can cause
  52. problems with some pagers. If you see such problems, you can disable the
  53. colours.""",
  54. "Disable using colors for info related things."
  55. )
  56. nosep_config = Config()
  57. nosep_config.InteractiveShell.separate_in = ''
  58. nosep_config.InteractiveShell.separate_out = ''
  59. nosep_config.InteractiveShell.separate_out2 = ''
  60. shell_flags['nosep']=(nosep_config, "Eliminate all spacing between prompts.")
  61. shell_flags['pylab'] = (
  62. {'InteractiveShellApp' : {'pylab' : 'auto'}},
  63. """Pre-load matplotlib and numpy for interactive use with
  64. the default matplotlib backend."""
  65. )
  66. shell_flags['matplotlib'] = (
  67. {'InteractiveShellApp' : {'matplotlib' : 'auto'}},
  68. """Configure matplotlib for interactive use with
  69. the default matplotlib backend."""
  70. )
  71. # it's possible we don't want short aliases for *all* of these:
  72. shell_aliases = dict(
  73. autocall='InteractiveShell.autocall',
  74. colors='InteractiveShell.colors',
  75. logfile='InteractiveShell.logfile',
  76. logappend='InteractiveShell.logappend',
  77. c='InteractiveShellApp.code_to_run',
  78. m='InteractiveShellApp.module_to_run',
  79. ext='InteractiveShellApp.extra_extension',
  80. gui='InteractiveShellApp.gui',
  81. pylab='InteractiveShellApp.pylab',
  82. matplotlib='InteractiveShellApp.matplotlib',
  83. )
  84. shell_aliases['cache-size'] = 'InteractiveShell.cache_size'
  85. #-----------------------------------------------------------------------------
  86. # Main classes and functions
  87. #-----------------------------------------------------------------------------
  88. class InteractiveShellApp(Configurable):
  89. """A Mixin for applications that start InteractiveShell instances.
  90. Provides configurables for loading extensions and executing files
  91. as part of configuring a Shell environment.
  92. The following methods should be called by the :meth:`initialize` method
  93. of the subclass:
  94. - :meth:`init_path`
  95. - :meth:`init_shell` (to be implemented by the subclass)
  96. - :meth:`init_gui_pylab`
  97. - :meth:`init_extensions`
  98. - :meth:`init_code`
  99. """
  100. extensions = List(Unicode(),
  101. help="A list of dotted module names of IPython extensions to load."
  102. ).tag(config=True)
  103. extra_extension = Unicode('',
  104. help="dotted module name of an IPython extension to load."
  105. ).tag(config=True)
  106. reraise_ipython_extension_failures = Bool(False,
  107. help="Reraise exceptions encountered loading IPython extensions?",
  108. ).tag(config=True)
  109. # Extensions that are always loaded (not configurable)
  110. default_extensions = List(Unicode(), [u'storemagic']).tag(config=False)
  111. hide_initial_ns = Bool(True,
  112. help="""Should variables loaded at startup (by startup files, exec_lines, etc.)
  113. be hidden from tools like %who?"""
  114. ).tag(config=True)
  115. exec_files = List(Unicode(),
  116. help="""List of files to run at IPython startup."""
  117. ).tag(config=True)
  118. exec_PYTHONSTARTUP = Bool(True,
  119. help="""Run the file referenced by the PYTHONSTARTUP environment
  120. variable at IPython startup."""
  121. ).tag(config=True)
  122. file_to_run = Unicode('',
  123. help="""A file to be run""").tag(config=True)
  124. exec_lines = List(Unicode(),
  125. help="""lines of code to run at IPython startup."""
  126. ).tag(config=True)
  127. code_to_run = Unicode('',
  128. help="Execute the given command string."
  129. ).tag(config=True)
  130. module_to_run = Unicode('',
  131. help="Run the module as a script."
  132. ).tag(config=True)
  133. gui = CaselessStrEnum(gui_keys, allow_none=True,
  134. help="Enable GUI event loop integration with any of {0}.".format(gui_keys)
  135. ).tag(config=True)
  136. matplotlib = CaselessStrEnum(backend_keys, allow_none=True,
  137. help="""Configure matplotlib for interactive use with
  138. the default matplotlib backend."""
  139. ).tag(config=True)
  140. pylab = CaselessStrEnum(backend_keys, allow_none=True,
  141. help="""Pre-load matplotlib and numpy for interactive use,
  142. selecting a particular matplotlib backend and loop integration.
  143. """
  144. ).tag(config=True)
  145. pylab_import_all = Bool(True,
  146. help="""If true, IPython will populate the user namespace with numpy, pylab, etc.
  147. and an ``import *`` is done from numpy and pylab, when using pylab mode.
  148. When False, pylab mode should not import any names into the user namespace.
  149. """
  150. ).tag(config=True)
  151. shell = Instance('IPython.core.interactiveshell.InteractiveShellABC',
  152. allow_none=True)
  153. # whether interact-loop should start
  154. interact = Bool(True)
  155. user_ns = Instance(dict, args=None, allow_none=True)
  156. @observe('user_ns')
  157. def _user_ns_changed(self, change):
  158. if self.shell is not None:
  159. self.shell.user_ns = change['new']
  160. self.shell.init_user_ns()
  161. def init_path(self):
  162. """Add current working directory, '', to sys.path"""
  163. if sys.path[0] != '':
  164. sys.path.insert(0, '')
  165. def init_shell(self):
  166. raise NotImplementedError("Override in subclasses")
  167. def init_gui_pylab(self):
  168. """Enable GUI event loop integration, taking pylab into account."""
  169. enable = False
  170. shell = self.shell
  171. if self.pylab:
  172. enable = lambda key: shell.enable_pylab(key, import_all=self.pylab_import_all)
  173. key = self.pylab
  174. elif self.matplotlib:
  175. enable = shell.enable_matplotlib
  176. key = self.matplotlib
  177. elif self.gui:
  178. enable = shell.enable_gui
  179. key = self.gui
  180. if not enable:
  181. return
  182. try:
  183. r = enable(key)
  184. except ImportError:
  185. self.log.warning("Eventloop or matplotlib integration failed. Is matplotlib installed?")
  186. self.shell.showtraceback()
  187. return
  188. except Exception:
  189. self.log.warning("GUI event loop or pylab initialization failed")
  190. self.shell.showtraceback()
  191. return
  192. if isinstance(r, tuple):
  193. gui, backend = r[:2]
  194. self.log.info("Enabling GUI event loop integration, "
  195. "eventloop=%s, matplotlib=%s", gui, backend)
  196. if key == "auto":
  197. print("Using matplotlib backend: %s" % backend)
  198. else:
  199. gui = r
  200. self.log.info("Enabling GUI event loop integration, "
  201. "eventloop=%s", gui)
  202. def init_extensions(self):
  203. """Load all IPython extensions in IPythonApp.extensions.
  204. This uses the :meth:`ExtensionManager.load_extensions` to load all
  205. the extensions listed in ``self.extensions``.
  206. """
  207. try:
  208. self.log.debug("Loading IPython extensions...")
  209. extensions = self.default_extensions + self.extensions
  210. if self.extra_extension:
  211. extensions.append(self.extra_extension)
  212. for ext in extensions:
  213. try:
  214. self.log.info("Loading IPython extension: %s" % ext)
  215. self.shell.extension_manager.load_extension(ext)
  216. except:
  217. if self.reraise_ipython_extension_failures:
  218. raise
  219. msg = ("Error in loading extension: {ext}\n"
  220. "Check your config files in {location}".format(
  221. ext=ext,
  222. location=self.profile_dir.location
  223. ))
  224. self.log.warning(msg, exc_info=True)
  225. except:
  226. if self.reraise_ipython_extension_failures:
  227. raise
  228. self.log.warning("Unknown error in loading extensions:", exc_info=True)
  229. def init_code(self):
  230. """run the pre-flight code, specified via exec_lines"""
  231. self._run_startup_files()
  232. self._run_exec_lines()
  233. self._run_exec_files()
  234. # Hide variables defined here from %who etc.
  235. if self.hide_initial_ns:
  236. self.shell.user_ns_hidden.update(self.shell.user_ns)
  237. # command-line execution (ipython -i script.py, ipython -m module)
  238. # should *not* be excluded from %whos
  239. self._run_cmd_line_code()
  240. self._run_module()
  241. # flush output, so itwon't be attached to the first cell
  242. sys.stdout.flush()
  243. sys.stderr.flush()
  244. def _run_exec_lines(self):
  245. """Run lines of code in IPythonApp.exec_lines in the user's namespace."""
  246. if not self.exec_lines:
  247. return
  248. try:
  249. self.log.debug("Running code from IPythonApp.exec_lines...")
  250. for line in self.exec_lines:
  251. try:
  252. self.log.info("Running code in user namespace: %s" %
  253. line)
  254. self.shell.run_cell(line, store_history=False)
  255. except:
  256. self.log.warning("Error in executing line in user "
  257. "namespace: %s" % line)
  258. self.shell.showtraceback()
  259. except:
  260. self.log.warning("Unknown error in handling IPythonApp.exec_lines:")
  261. self.shell.showtraceback()
  262. def _exec_file(self, fname, shell_futures=False):
  263. try:
  264. full_filename = filefind(fname, [u'.', self.ipython_dir])
  265. except IOError:
  266. self.log.warning("File not found: %r"%fname)
  267. return
  268. # Make sure that the running script gets a proper sys.argv as if it
  269. # were run from a system shell.
  270. save_argv = sys.argv
  271. sys.argv = [full_filename] + self.extra_args[1:]
  272. # protect sys.argv from potential unicode strings on Python 2:
  273. if not py3compat.PY3:
  274. sys.argv = [ py3compat.cast_bytes(a) for a in sys.argv ]
  275. try:
  276. if os.path.isfile(full_filename):
  277. self.log.info("Running file in user namespace: %s" %
  278. full_filename)
  279. # Ensure that __file__ is always defined to match Python
  280. # behavior.
  281. with preserve_keys(self.shell.user_ns, '__file__'):
  282. self.shell.user_ns['__file__'] = fname
  283. if full_filename.endswith('.ipy'):
  284. self.shell.safe_execfile_ipy(full_filename,
  285. shell_futures=shell_futures)
  286. else:
  287. # default to python, even without extension
  288. self.shell.safe_execfile(full_filename,
  289. self.shell.user_ns,
  290. shell_futures=shell_futures,
  291. raise_exceptions=True)
  292. finally:
  293. sys.argv = save_argv
  294. def _run_startup_files(self):
  295. """Run files from profile startup directory"""
  296. startup_dir = self.profile_dir.startup_dir
  297. startup_files = []
  298. if self.exec_PYTHONSTARTUP and os.environ.get('PYTHONSTARTUP', False) and \
  299. not (self.file_to_run or self.code_to_run or self.module_to_run):
  300. python_startup = os.environ['PYTHONSTARTUP']
  301. self.log.debug("Running PYTHONSTARTUP file %s...", python_startup)
  302. try:
  303. self._exec_file(python_startup)
  304. except:
  305. self.log.warning("Unknown error in handling PYTHONSTARTUP file %s:", python_startup)
  306. self.shell.showtraceback()
  307. startup_files += glob.glob(os.path.join(startup_dir, '*.py'))
  308. startup_files += glob.glob(os.path.join(startup_dir, '*.ipy'))
  309. if not startup_files:
  310. return
  311. self.log.debug("Running startup files from %s...", startup_dir)
  312. try:
  313. for fname in sorted(startup_files):
  314. self._exec_file(fname)
  315. except:
  316. self.log.warning("Unknown error in handling startup files:")
  317. self.shell.showtraceback()
  318. def _run_exec_files(self):
  319. """Run files from IPythonApp.exec_files"""
  320. if not self.exec_files:
  321. return
  322. self.log.debug("Running files in IPythonApp.exec_files...")
  323. try:
  324. for fname in self.exec_files:
  325. self._exec_file(fname)
  326. except:
  327. self.log.warning("Unknown error in handling IPythonApp.exec_files:")
  328. self.shell.showtraceback()
  329. def _run_cmd_line_code(self):
  330. """Run code or file specified at the command-line"""
  331. if self.code_to_run:
  332. line = self.code_to_run
  333. try:
  334. self.log.info("Running code given at command line (c=): %s" %
  335. line)
  336. self.shell.run_cell(line, store_history=False)
  337. except:
  338. self.log.warning("Error in executing line in user namespace: %s" %
  339. line)
  340. self.shell.showtraceback()
  341. if not self.interact:
  342. self.exit(1)
  343. # Like Python itself, ignore the second if the first of these is present
  344. elif self.file_to_run:
  345. fname = self.file_to_run
  346. if os.path.isdir(fname):
  347. fname = os.path.join(fname, "__main__.py")
  348. try:
  349. self._exec_file(fname, shell_futures=True)
  350. except:
  351. self.shell.showtraceback(tb_offset=4)
  352. if not self.interact:
  353. self.exit(1)
  354. def _run_module(self):
  355. """Run module specified at the command-line."""
  356. if self.module_to_run:
  357. # Make sure that the module gets a proper sys.argv as if it were
  358. # run using `python -m`.
  359. save_argv = sys.argv
  360. sys.argv = [sys.executable] + self.extra_args
  361. try:
  362. self.shell.safe_run_module(self.module_to_run,
  363. self.shell.user_ns)
  364. finally:
  365. sys.argv = save_argv