shellapp.py 19 KB

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