ipapp.py
393 lines
| 14.1 KiB
| text/x-python
|
PythonLexer
Brian Granger
|
r2202 | #!/usr/bin/env python | ||
# encoding: utf-8 | ||||
""" | ||||
MinRK
|
r4023 | The :class:`~IPython.core.application.Application` object for the command | ||
Brian Granger
|
r2301 | line :command:`ipython` program. | ||
Brian Granger
|
r2202 | |||
Fernando Perez
|
r2427 | Authors | ||
------- | ||||
Brian Granger
|
r2202 | |||
* Brian Granger | ||||
* Fernando Perez | ||||
MinRK
|
r3963 | * Min Ragan-Kelley | ||
Brian Granger
|
r2202 | """ | ||
#----------------------------------------------------------------------------- | ||||
Matthias BUSSONNIER
|
r5390 | # Copyright (C) 2008-2011 The IPython Development Team | ||
Brian Granger
|
r2202 | # | ||
# Distributed under the terms of the BSD License. The full license is in | ||||
# the file COPYING, distributed as part of this software. | ||||
#----------------------------------------------------------------------------- | ||||
#----------------------------------------------------------------------------- | ||||
# Imports | ||||
#----------------------------------------------------------------------------- | ||||
Brian Granger
|
r2506 | |||
Fernando Perez
|
r2427 | from __future__ import absolute_import | ||
Brian Granger
|
r2202 | |||
Brian Granger
|
r2252 | import logging | ||
Brian Granger
|
r2203 | import os | ||
import sys | ||||
MinRK
|
r3963 | from IPython.config.loader import ( | ||
MinRK
|
r4909 | Config, PyFileConfigLoader, ConfigFileNotFound | ||
MinRK
|
r3963 | ) | ||
MinRK
|
r5214 | from IPython.config.application import boolean_flag, catch_config_error | ||
Brian Granger
|
r2506 | from IPython.core import release | ||
MinRK
|
r3963 | from IPython.core import usage | ||
MinRK
|
r5231 | from IPython.core.completer import IPCompleter | ||
Brian Granger
|
r2506 | from IPython.core.crashhandler import CrashHandler | ||
MinRK
|
r3963 | from IPython.core.formatters import PlainTextFormatter | ||
MinRK
|
r6823 | from IPython.core.history import HistoryManager | ||
MinRK
|
r5548 | from IPython.core.prompts import PromptManager | ||
MinRK
|
r4023 | from IPython.core.application import ( | ||
MinRK
|
r3963 | ProfileDir, BaseIPythonApplication, base_flags, base_aliases | ||
Brian Granger
|
r2245 | ) | ||
MinRK
|
r7417 | from IPython.core.magics import ScriptMagics | ||
MinRK
|
r3968 | from IPython.core.shellapp import ( | ||
InteractiveShellApp, shell_flags, shell_aliases | ||||
) | ||||
MinRK
|
r3963 | from IPython.frontend.terminal.interactiveshell import TerminalInteractiveShell | ||
Brian Granger
|
r2264 | from IPython.lib import inputhook | ||
MinRK
|
r4104 | from IPython.utils import warn | ||
MinRK
|
r3968 | from IPython.utils.path import get_ipython_dir, check_for_old_config | ||
MinRK
|
r3963 | from IPython.utils.traitlets import ( | ||
MinRK
|
r4462 | Bool, List, Dict, CaselessStrEnum | ||
MinRK
|
r3963 | ) | ||
Brian Granger
|
r2203 | |||
#----------------------------------------------------------------------------- | ||||
Fernando Perez
|
r2427 | # Globals, utilities and helpers | ||
Brian Granger
|
r2203 | #----------------------------------------------------------------------------- | ||
Brian Granger
|
r2501 | #: The default config file name for this application. | ||
Fernando Perez
|
r2427 | default_config_file_name = u'ipython_config.py' | ||
Brian Granger
|
r2203 | |||
Brian Granger
|
r4216 | _examples = """ | ||
ipython --pylab # start in pylab mode | ||||
ipython --pylab=qt # start in pylab mode with the qt4 backend | ||||
Brian E. Granger
|
r4219 | ipython --log-level=DEBUG # set logging to DEBUG | ||
Brian Granger
|
r4216 | ipython --profile=foo # start with profile foo | ||
Brian E. Granger
|
r4218 | |||
Brian Granger
|
r4216 | ipython qtconsole # start the qtconsole GUI application | ||
MinRK
|
r6167 | ipython help qtconsole # show the help for the qtconsole subcmd | ||
Brian E. Granger
|
r4218 | |||
Paul Ivanov
|
r5607 | ipython console # start the terminal-based console application | ||
MinRK
|
r6167 | ipython help console # show the help for the console subcmd | ||
Paul Ivanov
|
r5607 | |||
MinRK
|
r6167 | ipython notebook # start the IPython notebook | ||
ipython help notebook # show the help for the notebook subcmd | ||||
MinRK
|
r6169 | |||
ipython profile create foo # create profile foo w/ default config files | ||||
ipython help profile # show the help for the profile subcmd | ||||
MinRK
|
r6901 | |||
ipython locate # print the path to the IPython directory | ||||
ipython locate profile foo # print the path to the directory for profile `foo` | ||||
Brian Granger
|
r4216 | """ | ||
Brian Granger
|
r2501 | |||
Fernando Perez
|
r2427 | #----------------------------------------------------------------------------- | ||
Brian Granger
|
r2506 | # Crash handler for this application | ||
#----------------------------------------------------------------------------- | ||||
class IPAppCrashHandler(CrashHandler): | ||||
"""sys.excepthook for IPython itself, leaves a detailed report on disk.""" | ||||
def __init__(self, app): | ||||
contact_name = release.authors['Fernando'][0] | ||||
MinRK
|
r5316 | contact_email = release.author_email | ||
bug_tracker = 'https://github.com/ipython/ipython/issues' | ||||
Brian Granger
|
r2506 | super(IPAppCrashHandler,self).__init__( | ||
app, contact_name, contact_email, bug_tracker | ||||
) | ||||
def make_report(self,traceback): | ||||
"""Return a string containing a crash report.""" | ||||
sec_sep = self.section_sep | ||||
# Start with parent report | ||||
report = [super(IPAppCrashHandler, self).make_report(traceback)] | ||||
# Add interactive-specific info we may have | ||||
rpt_add = report.append | ||||
try: | ||||
rpt_add(sec_sep+"History of session input:") | ||||
for line in self.app.shell.user_ns['_ih']: | ||||
rpt_add(line) | ||||
rpt_add('\n*** Last line of input (may not be in above history):\n') | ||||
rpt_add(self.app.shell._last_input_line+'\n') | ||||
except: | ||||
pass | ||||
return ''.join(report) | ||||
MinRK
|
r3963 | #----------------------------------------------------------------------------- | ||
# Aliases and Flags | ||||
#----------------------------------------------------------------------------- | ||||
flags = dict(base_flags) | ||||
MinRK
|
r3968 | flags.update(shell_flags) | ||
MinRK
|
r5610 | frontend_flags = {} | ||
addflag = lambda *args: frontend_flags.update(boolean_flag(*args)) | ||||
MinRK
|
r3963 | addflag('autoedit-syntax', 'TerminalInteractiveShell.autoedit_syntax', | ||
'Turn on auto editing of files with syntax errors.', | ||||
'Turn off auto editing of files with syntax errors.' | ||||
) | ||||
MinRK
|
r3968 | addflag('banner', 'TerminalIPythonApp.display_banner', | ||
MinRK
|
r3963 | "Display a banner upon starting IPython.", | ||
"Don't display a banner upon starting IPython." | ||||
) | ||||
addflag('confirm-exit', 'TerminalInteractiveShell.confirm_exit', | ||||
"""Set to confirm when you try to exit IPython with an EOF (Control-D | ||||
MinRK
|
r3967 | in Unix, Control-Z/Enter in Windows). By typing 'exit' or 'quit', | ||
you can force a direct exit without any confirmation.""", | ||||
MinRK
|
r3963 | "Don't prompt the user when exiting." | ||
) | ||||
addflag('term-title', 'TerminalInteractiveShell.term_title', | ||||
"Enable auto setting the terminal title.", | ||||
"Disable auto setting the terminal title." | ||||
) | ||||
classic_config = Config() | ||||
classic_config.InteractiveShell.cache_size = 0 | ||||
classic_config.PlainTextFormatter.pprint = False | ||||
MinRK
|
r5548 | classic_config.PromptManager.in_template = '>>> ' | ||
classic_config.PromptManager.in2_template = '... ' | ||||
classic_config.PromptManager.out_template = '' | ||||
MinRK
|
r3963 | classic_config.InteractiveShell.separate_in = '' | ||
classic_config.InteractiveShell.separate_out = '' | ||||
classic_config.InteractiveShell.separate_out2 = '' | ||||
classic_config.InteractiveShell.colors = 'NoColor' | ||||
classic_config.InteractiveShell.xmode = 'Plain' | ||||
MinRK
|
r5610 | frontend_flags['classic']=( | ||
MinRK
|
r3963 | classic_config, | ||
"Gives IPython a similar feel to the classic Python prompt." | ||||
) | ||||
# # log doesn't make so much sense this way anymore | ||||
# paa('--log','-l', | ||||
# action='store_true', dest='InteractiveShell.logstart', | ||||
# help="Start logging to the default log file (./ipython_log.py).") | ||||
# | ||||
# # quick is harder to implement | ||||
MinRK
|
r5610 | frontend_flags['quick']=( | ||
MinRK
|
r3968 | {'TerminalIPythonApp' : {'quick' : True}}, | ||
MinRK
|
r3963 | "Enable quick startup with no config files." | ||
) | ||||
MinRK
|
r5610 | frontend_flags['i'] = ( | ||
MinRK
|
r3968 | {'TerminalIPythonApp' : {'force_interact' : True}}, | ||
Fernando Perez
|
r4245 | """If running code from the command line, become interactive afterwards. | ||
Note: can also be given simply as '-i.'""" | ||||
MinRK
|
r3963 | ) | ||
MinRK
|
r5610 | flags.update(frontend_flags) | ||
MinRK
|
r3963 | |||
aliases = dict(base_aliases) | ||||
MinRK
|
r3968 | aliases.update(shell_aliases) | ||
MinRK
|
r3963 | |||
Brian Granger
|
r2506 | #----------------------------------------------------------------------------- | ||
Fernando Perez
|
r2427 | # Main classes and functions | ||
#----------------------------------------------------------------------------- | ||||
Brian Granger
|
r2245 | |||
MinRK
|
r6901 | |||
class LocateIPythonApp(BaseIPythonApplication): | ||||
description = """print the path to the IPython dir""" | ||||
subcommands = Dict(dict( | ||||
profile=('IPython.core.profileapp.ProfileLocate', | ||||
"print the path to an IPython profile directory", | ||||
), | ||||
)) | ||||
def start(self): | ||||
if self.subapp is not None: | ||||
return self.subapp.start() | ||||
else: | ||||
print self.ipython_dir | ||||
MinRK
|
r3968 | class TerminalIPythonApp(BaseIPythonApplication, InteractiveShellApp): | ||
Brian Granger
|
r2328 | name = u'ipython' | ||
MinRK
|
r3963 | description = usage.cl_usage | ||
Brian Granger
|
r2511 | default_config_file_name = default_config_file_name | ||
Brian Granger
|
r2506 | crash_handler_class = IPAppCrashHandler | ||
Brian Granger
|
r4216 | examples = _examples | ||
Brian Granger
|
r4215 | |||
MinRK
|
r3963 | flags = Dict(flags) | ||
aliases = Dict(aliases) | ||||
MinRK
|
r4462 | classes = List() | ||
def _classes_default(self): | ||||
"""This has to be in a method, for TerminalIPythonApp to be available.""" | ||||
return [ | ||||
InteractiveShellApp, # ShellApp comes before TerminalApp, because | ||||
self.__class__, # it will also affect subclasses (e.g. QtConsole) | ||||
TerminalInteractiveShell, | ||||
MinRK
|
r5548 | PromptManager, | ||
MinRK
|
r6823 | HistoryManager, | ||
MinRK
|
r4462 | ProfileDir, | ||
PlainTextFormatter, | ||||
MinRK
|
r5231 | IPCompleter, | ||
MinRK
|
r7417 | ScriptMagics, | ||
MinRK
|
r4462 | ] | ||
Bernardo B. Marques
|
r4872 | |||
MinRK
|
r3982 | subcommands = Dict(dict( | ||
MinRK
|
r4022 | qtconsole=('IPython.frontend.qt.console.qtconsoleapp.IPythonQtConsoleApp', | ||
"""Launch the IPython Qt Console.""" | ||||
MinRK
|
r4024 | ), | ||
Brian E. Granger
|
r5104 | notebook=('IPython.frontend.html.notebook.notebookapp.NotebookApp', | ||
Paul Ivanov
|
r5607 | """Launch the IPython HTML Notebook Server.""" | ||
Brian E. Granger
|
r4344 | ), | ||
MinRK
|
r4024 | profile = ("IPython.core.profileapp.ProfileApp", | ||
MinRK
|
r4501 | "Create and manage IPython profiles." | ||
), | ||||
kernel = ("IPython.zmq.ipkernel.IPKernelApp", | ||||
"Start a kernel without an attached frontend." | ||||
), | ||||
MinRK
|
r5611 | console=('IPython.frontend.terminal.console.app.ZMQTerminalIPythonApp', | ||
Paul Ivanov
|
r5607 | """Launch the IPython terminal-based Console.""" | ||
MinRK
|
r5600 | ), | ||
MinRK
|
r6901 | locate=('IPython.frontend.terminal.ipapp.LocateIPythonApp', | ||
LocateIPythonApp.description | ||||
), | ||||
MinRK
|
r3982 | )) | ||
Bernardo B. Marques
|
r4872 | |||
MinRK
|
r4025 | # *do* autocreate requested profile, but don't create the config file. | ||
MinRK
|
r3963 | auto_create=Bool(True) | ||
# configurables | ||||
ignore_old_config=Bool(False, config=True, | ||||
help="Suppress warning messages about legacy config files" | ||||
) | ||||
quick = Bool(False, config=True, | ||||
help="""Start IPython quickly by skipping the loading of config files.""" | ||||
) | ||||
def _quick_changed(self, name, old, new): | ||||
if new: | ||||
self.load_config_file = lambda *a, **kw: None | ||||
self.ignore_old_config=True | ||||
display_banner = Bool(True, config=True, | ||||
help="Whether to display a banner upon starting IPython." | ||||
) | ||||
# if there is code of files to run from the cmd line, don't interact | ||||
# unless the --i flag (App.force_interact) is true. | ||||
force_interact = Bool(False, config=True, | ||||
help="""If a command or file is given via the command-line, | ||||
e.g. 'ipython foo.py""" | ||||
) | ||||
def _force_interact_changed(self, name, old, new): | ||||
if new: | ||||
self.interact = True | ||||
Bernardo B. Marques
|
r4872 | |||
MinRK
|
r3963 | def _file_to_run_changed(self, name, old, new): | ||
Bradley M. Froehle
|
r6081 | if new: | ||
self.something_to_run = True | ||||
MinRK
|
r3963 | if new and not self.force_interact: | ||
self.interact = False | ||||
_code_to_run_changed = _file_to_run_changed | ||||
Bradley M. Froehle
|
r6069 | _module_to_run_changed = _file_to_run_changed | ||
MinRK
|
r3963 | |||
# internal, not-configurable | ||||
interact=Bool(True) | ||||
Bradley M. Froehle
|
r6081 | something_to_run=Bool(False) | ||
MinRK
|
r3963 | |||
MinRK
|
r4104 | def parse_command_line(self, argv=None): | ||
"""override to allow old '-pylab' flag with deprecation warning""" | ||||
Fernando Perez
|
r4245 | |||
MinRK
|
r4104 | argv = sys.argv[1:] if argv is None else argv | ||
Fernando Perez
|
r4245 | |||
if '-pylab' in argv: | ||||
MinRK
|
r4104 | # deprecated `-pylab` given, | ||
# warn and transform into current syntax | ||||
Fernando Perez
|
r4245 | argv = argv[:] # copy, don't clobber | ||
idx = argv.index('-pylab') | ||||
MinRK
|
r4104 | warn.warn("`-pylab` flag has been deprecated.\n" | ||
MinRK
|
r4190 | " Use `--pylab` instead, or `--pylab=foo` to specify a backend.") | ||
MinRK
|
r4104 | sub = '--pylab' | ||
if len(argv) > idx+1: | ||||
# check for gui arg, as in '-pylab qt' | ||||
gui = argv[idx+1] | ||||
if gui in ('wx', 'qt', 'qt4', 'gtk', 'auto'): | ||||
MinRK
|
r4190 | sub = '--pylab='+gui | ||
MinRK
|
r4104 | argv.pop(idx+1) | ||
argv[idx] = sub | ||||
Bernardo B. Marques
|
r4872 | |||
MinRK
|
r4104 | return super(TerminalIPythonApp, self).parse_command_line(argv) | ||
MinRK
|
r5172 | |||
MinRK
|
r5214 | @catch_config_error | ||
MinRK
|
r3963 | def initialize(self, argv=None): | ||
"""Do actions after construct, but before starting the app.""" | ||||
MinRK
|
r3968 | super(TerminalIPythonApp, self).initialize(argv) | ||
MinRK
|
r3982 | if self.subapp is not None: | ||
# don't bother initializing further, starting subapp | ||||
return | ||||
MinRK
|
r3963 | if not self.ignore_old_config: | ||
check_for_old_config(self.ipython_dir) | ||||
# print self.extra_args | ||||
Bradley M. Froehle
|
r6081 | if self.extra_args and not self.something_to_run: | ||
MinRK
|
r3963 | self.file_to_run = self.extra_args[0] | ||
Bradley M. Froehle
|
r6695 | self.init_path() | ||
MinRK
|
r3963 | # create the shell | ||
self.init_shell() | ||||
# and draw the banner | ||||
self.init_banner() | ||||
# Now a variety of things that happen after the banner is printed. | ||||
self.init_gui_pylab() | ||||
self.init_extensions() | ||||
self.init_code() | ||||
def init_shell(self): | ||||
"""initialize the InteractiveShell instance""" | ||||
Brian Granger
|
r2731 | # Create an InteractiveShell instance. | ||
Bernardo B. Marques
|
r4872 | # shell.display_banner should always be False for the terminal | ||
Brian Granger
|
r2252 | # based app, because we call shell.show_banner() by hand below | ||
# so the banner shows *before* all extension loading stuff. | ||||
MinRK
|
r3963 | self.shell = TerminalInteractiveShell.instance(config=self.config, | ||
display_banner=False, profile_dir=self.profile_dir, | ||||
ipython_dir=self.ipython_dir) | ||||
MinRK
|
r5315 | self.shell.configurables.append(self) | ||
Brian Granger
|
r2252 | |||
MinRK
|
r3963 | def init_banner(self): | ||
"""optionally display the banner""" | ||||
if self.display_banner and self.interact: | ||||
self.shell.show_banner() | ||||
Brian Granger
|
r2252 | # Make sure there is a space below the banner. | ||
if self.log_level <= logging.INFO: print | ||||
Bradley M. Froehle
|
r7096 | def _pylab_changed(self, name, old, new): | ||
"""Replace --pylab='inline' with --pylab='auto'""" | ||||
if new == 'inline': | ||||
warn.warn("'inline' not available as pylab backend, " | ||||
"using 'auto' instead.\n") | ||||
self.pylab = 'auto' | ||||
Brian Granger
|
r2252 | |||
MinRK
|
r3963 | def start(self): | ||
MinRK
|
r3982 | if self.subapp is not None: | ||
return self.subapp.start() | ||||
MinRK
|
r3963 | # perform any prexec steps: | ||
if self.interact: | ||||
Brian Granger
|
r2253 | self.log.debug("Starting IPython's mainloop...") | ||
self.shell.mainloop() | ||||
Fernando Perez
|
r2391 | else: | ||
MinRK
|
r3963 | self.log.debug("IPython not interactive...") | ||
Brian Granger
|
r2202 | |||
Fernando Perez
|
r2363 | |||
Brian Granger
|
r2322 | def load_default_config(ipython_dir=None): | ||
"""Load the default config file from the default ipython_dir. | ||||
Brian Granger
|
r2245 | |||
This is useful for embedded shells. | ||||
""" | ||||
Brian Granger
|
r2322 | if ipython_dir is None: | ||
ipython_dir = get_ipython_dir() | ||||
MinRK
|
r3963 | profile_dir = os.path.join(ipython_dir, 'profile_default') | ||
cl = PyFileConfigLoader(default_config_file_name, profile_dir) | ||||
MinRK
|
r4168 | try: | ||
config = cl.load_config() | ||||
MinRK
|
r4909 | except ConfigFileNotFound: | ||
MinRK
|
r4168 | # no config found | ||
config = Config() | ||||
Brian Granger
|
r2245 | return config | ||
Brian Granger
|
r2269 | def launch_new_instance(): | ||
Brian Granger
|
r2296 | """Create and run a full blown IPython instance""" | ||
MinRK
|
r3969 | app = TerminalIPythonApp.instance() | ||
MinRK
|
r3963 | app.initialize() | ||
Brian Granger
|
r2269 | app.start() | ||
Brian Granger
|
r2501 | |||
Brian Granger
|
r2507 | |||
if __name__ == '__main__': | ||||
launch_new_instance() | ||||