ipapp.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  1. # encoding: utf-8
  2. """
  3. The :class:`~traitlets.config.application.Application` object for the command
  4. line :command:`ipython` program.
  5. """
  6. # Copyright (c) IPython Development Team.
  7. # Distributed under the terms of the Modified BSD License.
  8. import logging
  9. import os
  10. import sys
  11. import warnings
  12. from traitlets.config.loader import Config
  13. from traitlets.config.application import boolean_flag, catch_config_error
  14. from IPython.core import release
  15. from IPython.core import usage
  16. from IPython.core.completer import IPCompleter
  17. from IPython.core.crashhandler import CrashHandler
  18. from IPython.core.formatters import PlainTextFormatter
  19. from IPython.core.history import HistoryManager
  20. from IPython.core.application import (
  21. ProfileDir, BaseIPythonApplication, base_flags, base_aliases
  22. )
  23. from IPython.core.magic import MagicsManager
  24. from IPython.core.magics import (
  25. ScriptMagics, LoggingMagics
  26. )
  27. from IPython.core.shellapp import (
  28. InteractiveShellApp, shell_flags, shell_aliases
  29. )
  30. from IPython.extensions.storemagic import StoreMagics
  31. from .interactiveshell import TerminalInteractiveShell
  32. from IPython.paths import get_ipython_dir
  33. from traitlets import (
  34. Bool, List, default, observe, Type
  35. )
  36. #-----------------------------------------------------------------------------
  37. # Globals, utilities and helpers
  38. #-----------------------------------------------------------------------------
  39. _examples = """
  40. ipython --matplotlib # enable matplotlib integration
  41. ipython --matplotlib=qt # enable matplotlib integration with qt4 backend
  42. ipython --log-level=DEBUG # set logging to DEBUG
  43. ipython --profile=foo # start with profile foo
  44. ipython profile create foo # create profile foo w/ default config files
  45. ipython help profile # show the help for the profile subcmd
  46. ipython locate # print the path to the IPython directory
  47. ipython locate profile foo # print the path to the directory for profile `foo`
  48. """
  49. #-----------------------------------------------------------------------------
  50. # Crash handler for this application
  51. #-----------------------------------------------------------------------------
  52. class IPAppCrashHandler(CrashHandler):
  53. """sys.excepthook for IPython itself, leaves a detailed report on disk."""
  54. def __init__(self, app):
  55. contact_name = release.author
  56. contact_email = release.author_email
  57. bug_tracker = 'https://github.com/ipython/ipython/issues'
  58. super(IPAppCrashHandler,self).__init__(
  59. app, contact_name, contact_email, bug_tracker
  60. )
  61. def make_report(self,traceback):
  62. """Return a string containing a crash report."""
  63. sec_sep = self.section_sep
  64. # Start with parent report
  65. report = [super(IPAppCrashHandler, self).make_report(traceback)]
  66. # Add interactive-specific info we may have
  67. rpt_add = report.append
  68. try:
  69. rpt_add(sec_sep+"History of session input:")
  70. for line in self.app.shell.user_ns['_ih']:
  71. rpt_add(line)
  72. rpt_add('\n*** Last line of input (may not be in above history):\n')
  73. rpt_add(self.app.shell._last_input_line+'\n')
  74. except:
  75. pass
  76. return ''.join(report)
  77. #-----------------------------------------------------------------------------
  78. # Aliases and Flags
  79. #-----------------------------------------------------------------------------
  80. flags = dict(base_flags)
  81. flags.update(shell_flags)
  82. frontend_flags = {}
  83. addflag = lambda *args: frontend_flags.update(boolean_flag(*args))
  84. addflag('autoedit-syntax', 'TerminalInteractiveShell.autoedit_syntax',
  85. 'Turn on auto editing of files with syntax errors.',
  86. 'Turn off auto editing of files with syntax errors.'
  87. )
  88. addflag('simple-prompt', 'TerminalInteractiveShell.simple_prompt',
  89. "Force simple minimal prompt using `raw_input`",
  90. "Use a rich interactive prompt with prompt_toolkit",
  91. )
  92. addflag('banner', 'TerminalIPythonApp.display_banner',
  93. "Display a banner upon starting IPython.",
  94. "Don't display a banner upon starting IPython."
  95. )
  96. addflag('confirm-exit', 'TerminalInteractiveShell.confirm_exit',
  97. """Set to confirm when you try to exit IPython with an EOF (Control-D
  98. in Unix, Control-Z/Enter in Windows). By typing 'exit' or 'quit',
  99. you can force a direct exit without any confirmation.""",
  100. "Don't prompt the user when exiting."
  101. )
  102. addflag(
  103. "tip",
  104. "TerminalInteractiveShell.enable_tip",
  105. """Shows a tip when IPython starts.""",
  106. "Don't show tip when IPython starts.",
  107. )
  108. addflag('term-title', 'TerminalInteractiveShell.term_title',
  109. "Enable auto setting the terminal title.",
  110. "Disable auto setting the terminal title."
  111. )
  112. classic_config = Config()
  113. classic_config.InteractiveShell.cache_size = 0
  114. classic_config.PlainTextFormatter.pprint = False
  115. classic_config.TerminalInteractiveShell.prompts_class = (
  116. "IPython.terminal.prompts.ClassicPrompts"
  117. )
  118. classic_config.InteractiveShell.separate_in = ""
  119. classic_config.InteractiveShell.separate_out = ""
  120. classic_config.InteractiveShell.separate_out2 = ""
  121. classic_config.InteractiveShell.colors = "nocolor"
  122. classic_config.InteractiveShell.xmode = "Plain"
  123. frontend_flags['classic']=(
  124. classic_config,
  125. "Gives IPython a similar feel to the classic Python prompt."
  126. )
  127. # # log doesn't make so much sense this way anymore
  128. # paa('--log','-l',
  129. # action='store_true', dest='InteractiveShell.logstart',
  130. # help="Start logging to the default log file (./ipython_log.py).")
  131. #
  132. # # quick is harder to implement
  133. frontend_flags['quick']=(
  134. {'TerminalIPythonApp' : {'quick' : True}},
  135. "Enable quick startup with no config files."
  136. )
  137. frontend_flags['i'] = (
  138. {'TerminalIPythonApp' : {'force_interact' : True}},
  139. """If running code from the command line, become interactive afterwards.
  140. It is often useful to follow this with `--` to treat remaining flags as
  141. script arguments.
  142. """
  143. )
  144. flags.update(frontend_flags)
  145. aliases = dict(base_aliases)
  146. aliases.update(shell_aliases) # type: ignore[arg-type]
  147. #-----------------------------------------------------------------------------
  148. # Main classes and functions
  149. #-----------------------------------------------------------------------------
  150. class LocateIPythonApp(BaseIPythonApplication):
  151. description = """print the path to the IPython dir"""
  152. subcommands = dict(
  153. profile=('IPython.core.profileapp.ProfileLocate',
  154. "print the path to an IPython profile directory",
  155. ),
  156. )
  157. def start(self):
  158. if self.subapp is not None:
  159. return self.subapp.start()
  160. else:
  161. print(self.ipython_dir)
  162. class TerminalIPythonApp(BaseIPythonApplication, InteractiveShellApp):
  163. name = "ipython"
  164. description = usage.cl_usage
  165. crash_handler_class = IPAppCrashHandler # typing: ignore[assignment]
  166. examples = _examples
  167. flags = flags
  168. aliases = aliases
  169. classes = List()
  170. interactive_shell_class = Type(
  171. klass=object, # use default_value otherwise which only allow subclasses.
  172. default_value=TerminalInteractiveShell,
  173. help="Class to use to instantiate the TerminalInteractiveShell object. Useful for custom Frontends"
  174. ).tag(config=True)
  175. @default('classes')
  176. def _classes_default(self):
  177. """This has to be in a method, for TerminalIPythonApp to be available."""
  178. return [
  179. InteractiveShellApp, # ShellApp comes before TerminalApp, because
  180. self.__class__, # it will also affect subclasses (e.g. QtConsole)
  181. TerminalInteractiveShell,
  182. HistoryManager,
  183. MagicsManager,
  184. ProfileDir,
  185. PlainTextFormatter,
  186. IPCompleter,
  187. ScriptMagics,
  188. LoggingMagics,
  189. StoreMagics,
  190. ]
  191. subcommands = dict(
  192. profile = ("IPython.core.profileapp.ProfileApp",
  193. "Create and manage IPython profiles."
  194. ),
  195. kernel = ("ipykernel.kernelapp.IPKernelApp",
  196. "Start a kernel without an attached frontend."
  197. ),
  198. locate=('IPython.terminal.ipapp.LocateIPythonApp',
  199. LocateIPythonApp.description
  200. ),
  201. history=('IPython.core.historyapp.HistoryApp',
  202. "Manage the IPython history database."
  203. ),
  204. )
  205. # *do* autocreate requested profile, but don't create the config file.
  206. auto_create = Bool(True).tag(config=True)
  207. # configurables
  208. quick = Bool(False,
  209. help="""Start IPython quickly by skipping the loading of config files."""
  210. ).tag(config=True)
  211. @observe('quick')
  212. def _quick_changed(self, change):
  213. if change['new']:
  214. self.load_config_file = lambda *a, **kw: None
  215. display_banner = Bool(True,
  216. help="Whether to display a banner upon starting IPython."
  217. ).tag(config=True)
  218. # if there is code of files to run from the cmd line, don't interact
  219. # unless the --i flag (App.force_interact) is true.
  220. force_interact = Bool(False,
  221. help="""If a command or file is given via the command-line,
  222. e.g. 'ipython foo.py', start an interactive shell after executing the
  223. file or command."""
  224. ).tag(config=True)
  225. @observe('force_interact')
  226. def _force_interact_changed(self, change):
  227. if change['new']:
  228. self.interact = True
  229. @observe('file_to_run', 'code_to_run', 'module_to_run')
  230. def _file_to_run_changed(self, change):
  231. new = change['new']
  232. if new:
  233. self.something_to_run = True
  234. if new and not self.force_interact:
  235. self.interact = False
  236. # internal, not-configurable
  237. something_to_run=Bool(False)
  238. @catch_config_error
  239. def initialize(self, argv=None):
  240. """Do actions after construct, but before starting the app."""
  241. super(TerminalIPythonApp, self).initialize(argv)
  242. if self.subapp is not None:
  243. # don't bother initializing further, starting subapp
  244. return
  245. # print(self.extra_args)
  246. if self.extra_args and not self.something_to_run:
  247. self.file_to_run = self.extra_args[0]
  248. self.init_path()
  249. # create the shell
  250. self.init_shell()
  251. # and draw the banner
  252. self.init_banner()
  253. # Now a variety of things that happen after the banner is printed.
  254. self.init_gui_pylab()
  255. self.init_extensions()
  256. self.init_code()
  257. def init_shell(self):
  258. """initialize the InteractiveShell instance"""
  259. # Create an InteractiveShell instance.
  260. # shell.display_banner should always be False for the terminal
  261. # based app, because we call shell.show_banner() by hand below
  262. # so the banner shows *before* all extension loading stuff.
  263. self.shell = self.interactive_shell_class.instance(parent=self,
  264. profile_dir=self.profile_dir,
  265. ipython_dir=self.ipython_dir, user_ns=self.user_ns)
  266. self.shell.configurables.append(self)
  267. def init_banner(self):
  268. """optionally display the banner"""
  269. if self.display_banner and self.interact:
  270. self.shell.show_banner()
  271. # Make sure there is a space below the banner.
  272. if self.log_level <= logging.INFO: print()
  273. def _pylab_changed(self, name, old, new):
  274. """Replace --pylab='inline' with --pylab='auto'"""
  275. if new == 'inline':
  276. warnings.warn("'inline' not available as pylab backend, "
  277. "using 'auto' instead.")
  278. self.pylab = 'auto'
  279. def start(self):
  280. if self.subapp is not None:
  281. return self.subapp.start()
  282. # perform any prexec steps:
  283. if self.interact:
  284. self.log.debug("Starting IPython's mainloop...")
  285. self.shell.mainloop()
  286. else:
  287. self.log.debug("IPython not interactive...")
  288. self.shell.restore_term_title()
  289. if not self.shell.last_execution_succeeded:
  290. sys.exit(1)
  291. def load_default_config(ipython_dir=None):
  292. """Load the default config file from the default ipython_dir.
  293. This is useful for embedded shells.
  294. """
  295. if ipython_dir is None:
  296. ipython_dir = get_ipython_dir()
  297. profile_dir = os.path.join(ipython_dir, 'profile_default')
  298. app = TerminalIPythonApp()
  299. app.config_file_paths.append(profile_dir)
  300. app.load_config_file()
  301. return app.config
  302. launch_new_instance = TerminalIPythonApp.launch_instance