ipapp.py 14 KB

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