shellapp.py 16 KB

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