shellapp.py 18 KB

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