ipapp.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  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('term-title', 'TerminalInteractiveShell.term_title',
  103. "Enable auto setting the terminal title.",
  104. "Disable auto setting the terminal title."
  105. )
  106. classic_config = Config()
  107. classic_config.InteractiveShell.cache_size = 0
  108. classic_config.PlainTextFormatter.pprint = False
  109. classic_config.TerminalInteractiveShell.prompts_class='IPython.terminal.prompts.ClassicPrompts'
  110. classic_config.InteractiveShell.separate_in = ''
  111. classic_config.InteractiveShell.separate_out = ''
  112. classic_config.InteractiveShell.separate_out2 = ''
  113. classic_config.InteractiveShell.colors = 'NoColor'
  114. classic_config.InteractiveShell.xmode = 'Plain'
  115. frontend_flags['classic']=(
  116. classic_config,
  117. "Gives IPython a similar feel to the classic Python prompt."
  118. )
  119. # # log doesn't make so much sense this way anymore
  120. # paa('--log','-l',
  121. # action='store_true', dest='InteractiveShell.logstart',
  122. # help="Start logging to the default log file (./ipython_log.py).")
  123. #
  124. # # quick is harder to implement
  125. frontend_flags['quick']=(
  126. {'TerminalIPythonApp' : {'quick' : True}},
  127. "Enable quick startup with no config files."
  128. )
  129. frontend_flags['i'] = (
  130. {'TerminalIPythonApp' : {'force_interact' : True}},
  131. """If running code from the command line, become interactive afterwards.
  132. It is often useful to follow this with `--` to treat remaining flags as
  133. script arguments.
  134. """
  135. )
  136. flags.update(frontend_flags)
  137. aliases = dict(base_aliases)
  138. aliases.update(shell_aliases) # type: ignore[arg-type]
  139. #-----------------------------------------------------------------------------
  140. # Main classes and functions
  141. #-----------------------------------------------------------------------------
  142. class LocateIPythonApp(BaseIPythonApplication):
  143. description = """print the path to the IPython dir"""
  144. subcommands = dict(
  145. profile=('IPython.core.profileapp.ProfileLocate',
  146. "print the path to an IPython profile directory",
  147. ),
  148. )
  149. def start(self):
  150. if self.subapp is not None:
  151. return self.subapp.start()
  152. else:
  153. print(self.ipython_dir)
  154. class TerminalIPythonApp(BaseIPythonApplication, InteractiveShellApp):
  155. name = "ipython"
  156. description = usage.cl_usage
  157. crash_handler_class = IPAppCrashHandler # typing: ignore[assignment]
  158. examples = _examples
  159. flags = flags
  160. aliases = aliases
  161. classes = List()
  162. interactive_shell_class = Type(
  163. klass=object, # use default_value otherwise which only allow subclasses.
  164. default_value=TerminalInteractiveShell,
  165. help="Class to use to instantiate the TerminalInteractiveShell object. Useful for custom Frontends"
  166. ).tag(config=True)
  167. @default('classes')
  168. def _classes_default(self):
  169. """This has to be in a method, for TerminalIPythonApp to be available."""
  170. return [
  171. InteractiveShellApp, # ShellApp comes before TerminalApp, because
  172. self.__class__, # it will also affect subclasses (e.g. QtConsole)
  173. TerminalInteractiveShell,
  174. HistoryManager,
  175. MagicsManager,
  176. ProfileDir,
  177. PlainTextFormatter,
  178. IPCompleter,
  179. ScriptMagics,
  180. LoggingMagics,
  181. StoreMagics,
  182. ]
  183. subcommands = dict(
  184. profile = ("IPython.core.profileapp.ProfileApp",
  185. "Create and manage IPython profiles."
  186. ),
  187. kernel = ("ipykernel.kernelapp.IPKernelApp",
  188. "Start a kernel without an attached frontend."
  189. ),
  190. locate=('IPython.terminal.ipapp.LocateIPythonApp',
  191. LocateIPythonApp.description
  192. ),
  193. history=('IPython.core.historyapp.HistoryApp',
  194. "Manage the IPython history database."
  195. ),
  196. )
  197. # *do* autocreate requested profile, but don't create the config file.
  198. auto_create = Bool(True).tag(config=True)
  199. # configurables
  200. quick = Bool(False,
  201. help="""Start IPython quickly by skipping the loading of config files."""
  202. ).tag(config=True)
  203. @observe('quick')
  204. def _quick_changed(self, change):
  205. if change['new']:
  206. self.load_config_file = lambda *a, **kw: None
  207. display_banner = Bool(True,
  208. help="Whether to display a banner upon starting IPython."
  209. ).tag(config=True)
  210. # if there is code of files to run from the cmd line, don't interact
  211. # unless the --i flag (App.force_interact) is true.
  212. force_interact = Bool(False,
  213. help="""If a command or file is given via the command-line,
  214. e.g. 'ipython foo.py', start an interactive shell after executing the
  215. file or command."""
  216. ).tag(config=True)
  217. @observe('force_interact')
  218. def _force_interact_changed(self, change):
  219. if change['new']:
  220. self.interact = True
  221. @observe('file_to_run', 'code_to_run', 'module_to_run')
  222. def _file_to_run_changed(self, change):
  223. new = change['new']
  224. if new:
  225. self.something_to_run = True
  226. if new and not self.force_interact:
  227. self.interact = False
  228. # internal, not-configurable
  229. something_to_run=Bool(False)
  230. @catch_config_error
  231. def initialize(self, argv=None):
  232. """Do actions after construct, but before starting the app."""
  233. super(TerminalIPythonApp, self).initialize(argv)
  234. if self.subapp is not None:
  235. # don't bother initializing further, starting subapp
  236. return
  237. # print(self.extra_args)
  238. if self.extra_args and not self.something_to_run:
  239. self.file_to_run = self.extra_args[0]
  240. self.init_path()
  241. # create the shell
  242. self.init_shell()
  243. # and draw the banner
  244. self.init_banner()
  245. # Now a variety of things that happen after the banner is printed.
  246. self.init_gui_pylab()
  247. self.init_extensions()
  248. self.init_code()
  249. def init_shell(self):
  250. """initialize the InteractiveShell instance"""
  251. # Create an InteractiveShell instance.
  252. # shell.display_banner should always be False for the terminal
  253. # based app, because we call shell.show_banner() by hand below
  254. # so the banner shows *before* all extension loading stuff.
  255. self.shell = self.interactive_shell_class.instance(parent=self,
  256. profile_dir=self.profile_dir,
  257. ipython_dir=self.ipython_dir, user_ns=self.user_ns)
  258. self.shell.configurables.append(self)
  259. def init_banner(self):
  260. """optionally display the banner"""
  261. if self.display_banner and self.interact:
  262. self.shell.show_banner()
  263. # Make sure there is a space below the banner.
  264. if self.log_level <= logging.INFO: print()
  265. def _pylab_changed(self, name, old, new):
  266. """Replace --pylab='inline' with --pylab='auto'"""
  267. if new == 'inline':
  268. warnings.warn("'inline' not available as pylab backend, "
  269. "using 'auto' instead.")
  270. self.pylab = 'auto'
  271. def start(self):
  272. if self.subapp is not None:
  273. return self.subapp.start()
  274. # perform any prexec steps:
  275. if self.interact:
  276. self.log.debug("Starting IPython's mainloop...")
  277. self.shell.mainloop()
  278. else:
  279. self.log.debug("IPython not interactive...")
  280. self.shell.restore_term_title()
  281. if not self.shell.last_execution_succeeded:
  282. sys.exit(1)
  283. def load_default_config(ipython_dir=None):
  284. """Load the default config file from the default ipython_dir.
  285. This is useful for embedded shells.
  286. """
  287. if ipython_dir is None:
  288. ipython_dir = get_ipython_dir()
  289. profile_dir = os.path.join(ipython_dir, 'profile_default')
  290. app = TerminalIPythonApp()
  291. app.config_file_paths.append(profile_dir)
  292. app.load_config_file()
  293. return app.config
  294. launch_new_instance = TerminalIPythonApp.launch_instance