ipapp.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  1. #!/usr/bin/env python
  2. # encoding: utf-8
  3. """
  4. The :class:`~IPython.core.application.Application` object for the command
  5. line :command:`ipython` program.
  6. """
  7. # Copyright (c) IPython Development Team.
  8. # Distributed under the terms of the Modified BSD License.
  9. from __future__ import absolute_import
  10. from __future__ import print_function
  11. import logging
  12. import os
  13. import sys
  14. import warnings
  15. from traitlets.config.loader import Config
  16. from traitlets.config.application import boolean_flag, catch_config_error, Application
  17. from IPython.core import release
  18. from IPython.core import usage
  19. from IPython.core.completer import IPCompleter
  20. from IPython.core.crashhandler import CrashHandler
  21. from IPython.core.formatters import PlainTextFormatter
  22. from IPython.core.history import HistoryManager
  23. from IPython.core.application import (
  24. ProfileDir, BaseIPythonApplication, base_flags, base_aliases
  25. )
  26. from IPython.core.magics import ScriptMagics
  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, Dict, 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)
  139. #-----------------------------------------------------------------------------
  140. # Main classes and functions
  141. #-----------------------------------------------------------------------------
  142. class LocateIPythonApp(BaseIPythonApplication):
  143. description = """print the path to the IPython dir"""
  144. subcommands = Dict(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 = u'ipython'
  156. description = usage.cl_usage
  157. crash_handler_class = IPAppCrashHandler
  158. examples = _examples
  159. flags = Dict(flags)
  160. aliases = Dict(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. ProfileDir,
  176. PlainTextFormatter,
  177. IPCompleter,
  178. ScriptMagics,
  179. StoreMagics,
  180. ]
  181. deprecated_subcommands = dict(
  182. qtconsole=('qtconsole.qtconsoleapp.JupyterQtConsoleApp',
  183. """DEPRECATED, Will be removed in IPython 6.0 : Launch the Jupyter Qt Console."""
  184. ),
  185. notebook=('notebook.notebookapp.NotebookApp',
  186. """DEPRECATED, Will be removed in IPython 6.0 : Launch the Jupyter HTML Notebook Server."""
  187. ),
  188. console=('jupyter_console.app.ZMQTerminalIPythonApp',
  189. """DEPRECATED, Will be removed in IPython 6.0 : Launch the Jupyter terminal-based Console."""
  190. ),
  191. nbconvert=('nbconvert.nbconvertapp.NbConvertApp',
  192. "DEPRECATED, Will be removed in IPython 6.0 : Convert notebooks to/from other formats."
  193. ),
  194. trust=('nbformat.sign.TrustNotebookApp',
  195. "DEPRECATED, Will be removed in IPython 6.0 : Sign notebooks to trust their potentially unsafe contents at load."
  196. ),
  197. kernelspec=('jupyter_client.kernelspecapp.KernelSpecApp',
  198. "DEPRECATED, Will be removed in IPython 6.0 : Manage Jupyter kernel specifications."
  199. ),
  200. )
  201. subcommands = dict(
  202. profile = ("IPython.core.profileapp.ProfileApp",
  203. "Create and manage IPython profiles."
  204. ),
  205. kernel = ("ipykernel.kernelapp.IPKernelApp",
  206. "Start a kernel without an attached frontend."
  207. ),
  208. locate=('IPython.terminal.ipapp.LocateIPythonApp',
  209. LocateIPythonApp.description
  210. ),
  211. history=('IPython.core.historyapp.HistoryApp',
  212. "Manage the IPython history database."
  213. ),
  214. )
  215. deprecated_subcommands['install-nbextension'] = (
  216. "notebook.nbextensions.InstallNBExtensionApp",
  217. "DEPRECATED, Will be removed in IPython 6.0 : Install Jupyter notebook extension files"
  218. )
  219. subcommands.update(deprecated_subcommands)
  220. # *do* autocreate requested profile, but don't create the config file.
  221. auto_create=Bool(True)
  222. # configurables
  223. quick = Bool(False,
  224. help="""Start IPython quickly by skipping the loading of config files."""
  225. ).tag(config=True)
  226. @observe('quick')
  227. def _quick_changed(self, change):
  228. if change['new']:
  229. self.load_config_file = lambda *a, **kw: None
  230. display_banner = Bool(True,
  231. help="Whether to display a banner upon starting IPython."
  232. ).tag(config=True)
  233. # if there is code of files to run from the cmd line, don't interact
  234. # unless the --i flag (App.force_interact) is true.
  235. force_interact = Bool(False,
  236. help="""If a command or file is given via the command-line,
  237. e.g. 'ipython foo.py', start an interactive shell after executing the
  238. file or command."""
  239. ).tag(config=True)
  240. @observe('force_interact')
  241. def _force_interact_changed(self, change):
  242. if change['new']:
  243. self.interact = True
  244. @observe('file_to_run', 'code_to_run', 'module_to_run')
  245. def _file_to_run_changed(self, change):
  246. new = change['new']
  247. if new:
  248. self.something_to_run = True
  249. if new and not self.force_interact:
  250. self.interact = False
  251. # internal, not-configurable
  252. something_to_run=Bool(False)
  253. def parse_command_line(self, argv=None):
  254. """override to allow old '-pylab' flag with deprecation warning"""
  255. argv = sys.argv[1:] if argv is None else argv
  256. if '-pylab' in argv:
  257. # deprecated `-pylab` given,
  258. # warn and transform into current syntax
  259. argv = argv[:] # copy, don't clobber
  260. idx = argv.index('-pylab')
  261. warnings.warn("`-pylab` flag has been deprecated.\n"
  262. " Use `--matplotlib <backend>` and import pylab manually.")
  263. argv[idx] = '--pylab'
  264. return super(TerminalIPythonApp, self).parse_command_line(argv)
  265. @catch_config_error
  266. def initialize(self, argv=None):
  267. """Do actions after construct, but before starting the app."""
  268. super(TerminalIPythonApp, self).initialize(argv)
  269. if self.subapp is not None:
  270. # don't bother initializing further, starting subapp
  271. return
  272. # print self.extra_args
  273. if self.extra_args and not self.something_to_run:
  274. self.file_to_run = self.extra_args[0]
  275. self.init_path()
  276. # create the shell
  277. self.init_shell()
  278. # and draw the banner
  279. self.init_banner()
  280. # Now a variety of things that happen after the banner is printed.
  281. self.init_gui_pylab()
  282. self.init_extensions()
  283. self.init_code()
  284. def init_shell(self):
  285. """initialize the InteractiveShell instance"""
  286. # Create an InteractiveShell instance.
  287. # shell.display_banner should always be False for the terminal
  288. # based app, because we call shell.show_banner() by hand below
  289. # so the banner shows *before* all extension loading stuff.
  290. self.shell = self.interactive_shell_class.instance(parent=self,
  291. profile_dir=self.profile_dir,
  292. ipython_dir=self.ipython_dir, user_ns=self.user_ns)
  293. self.shell.configurables.append(self)
  294. def init_banner(self):
  295. """optionally display the banner"""
  296. if self.display_banner and self.interact:
  297. self.shell.show_banner()
  298. # Make sure there is a space below the banner.
  299. if self.log_level <= logging.INFO: print()
  300. def _pylab_changed(self, name, old, new):
  301. """Replace --pylab='inline' with --pylab='auto'"""
  302. if new == 'inline':
  303. warnings.warn("'inline' not available as pylab backend, "
  304. "using 'auto' instead.")
  305. self.pylab = 'auto'
  306. def start(self):
  307. if self.subapp is not None:
  308. return self.subapp.start()
  309. # perform any prexec steps:
  310. if self.interact:
  311. self.log.debug("Starting IPython's mainloop...")
  312. self.shell.mainloop()
  313. else:
  314. self.log.debug("IPython not interactive...")
  315. def load_default_config(ipython_dir=None):
  316. """Load the default config file from the default ipython_dir.
  317. This is useful for embedded shells.
  318. """
  319. if ipython_dir is None:
  320. ipython_dir = get_ipython_dir()
  321. profile_dir = os.path.join(ipython_dir, 'profile_default')
  322. app = TerminalIPythonApp()
  323. app.config_file_paths.append(profile_dir)
  324. app.load_config_file()
  325. return app.config
  326. launch_new_instance = TerminalIPythonApp.launch_instance
  327. if __name__ == '__main__':
  328. launch_new_instance()