shellapp.py 17 KB

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