ipapp.py
357 lines
| 12.6 KiB
| text/x-python
|
PythonLexer
|
r2202 | #!/usr/bin/env python | ||
# encoding: utf-8 | ||||
""" | ||||
|
r4023 | The :class:`~IPython.core.application.Application` object for the command | ||
|
r2301 | line :command:`ipython` program. | ||
|
r2202 | |||
|
r2427 | Authors | ||
------- | ||||
|
r2202 | |||
* Brian Granger | ||||
* Fernando Perez | ||||
|
r3963 | * Min Ragan-Kelley | ||
|
r2202 | """ | ||
#----------------------------------------------------------------------------- | ||||
|
r2427 | # Copyright (C) 2008-2010 The IPython Development Team | ||
|
r2202 | # | ||
# Distributed under the terms of the BSD License. The full license is in | ||||
# the file COPYING, distributed as part of this software. | ||||
#----------------------------------------------------------------------------- | ||||
#----------------------------------------------------------------------------- | ||||
# Imports | ||||
#----------------------------------------------------------------------------- | ||||
|
r2506 | |||
|
r2427 | from __future__ import absolute_import | ||
|
r2202 | |||
|
r2252 | import logging | ||
|
r2203 | import os | ||
import sys | ||||
|
r3963 | from IPython.config.loader import ( | ||
Config, PyFileConfigLoader | ||||
) | ||||
from IPython.config.application import boolean_flag | ||||
|
r2506 | from IPython.core import release | ||
|
r3963 | from IPython.core import usage | ||
|
r2506 | from IPython.core.crashhandler import CrashHandler | ||
|
r3963 | from IPython.core.formatters import PlainTextFormatter | ||
|
r4023 | from IPython.core.application import ( | ||
|
r3963 | ProfileDir, BaseIPythonApplication, base_flags, base_aliases | ||
|
r2245 | ) | ||
|
r3968 | from IPython.core.shellapp import ( | ||
InteractiveShellApp, shell_flags, shell_aliases | ||||
) | ||||
|
r3963 | from IPython.frontend.terminal.interactiveshell import TerminalInteractiveShell | ||
|
r2264 | from IPython.lib import inputhook | ||
|
r3968 | from IPython.utils.path import get_ipython_dir, check_for_old_config | ||
|
r3963 | from IPython.utils.traitlets import ( | ||
|
r3968 | Bool, Dict, CaselessStrEnum | ||
|
r3963 | ) | ||
|
r2203 | |||
#----------------------------------------------------------------------------- | ||||
|
r2427 | # Globals, utilities and helpers | ||
|
r2203 | #----------------------------------------------------------------------------- | ||
|
r2501 | #: The default config file name for this application. | ||
|
r2427 | default_config_file_name = u'ipython_config.py' | ||
|
r2203 | |||
|
r2501 | |||
|
r2427 | #----------------------------------------------------------------------------- | ||
|
r2506 | # Crash handler for this application | ||
#----------------------------------------------------------------------------- | ||||
_message_template = """\ | ||||
Oops, $self.app_name crashed. We do our best to make it stable, but... | ||||
A crash report was automatically generated with the following information: | ||||
- A verbatim copy of the crash traceback. | ||||
- A copy of your input history during this session. | ||||
- Data on your current $self.app_name configuration. | ||||
It was left in the file named: | ||||
\t'$self.crash_report_fname' | ||||
If you can email this file to the developers, the information in it will help | ||||
them in understanding and correcting the problem. | ||||
You can mail it to: $self.contact_name at $self.contact_email | ||||
with the subject '$self.app_name Crash Report'. | ||||
If you want to do it now, the following command will work (under Unix): | ||||
mail -s '$self.app_name Crash Report' $self.contact_email < $self.crash_report_fname | ||||
To ensure accurate tracking of this issue, please file a report about it at: | ||||
$self.bug_tracker | ||||
""" | ||||
class IPAppCrashHandler(CrashHandler): | ||||
"""sys.excepthook for IPython itself, leaves a detailed report on disk.""" | ||||
message_template = _message_template | ||||
def __init__(self, app): | ||||
contact_name = release.authors['Fernando'][0] | ||||
contact_email = release.authors['Fernando'][1] | ||||
|
r3201 | bug_tracker = 'http://github.com/ipython/ipython/issues' | ||
|
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) | ||||
|
r3963 | #----------------------------------------------------------------------------- | ||
# Aliases and Flags | ||||
#----------------------------------------------------------------------------- | ||||
flags = dict(base_flags) | ||||
|
r3968 | flags.update(shell_flags) | ||
|
r3963 | addflag = lambda *args: flags.update(boolean_flag(*args)) | ||
addflag('autoedit-syntax', 'TerminalInteractiveShell.autoedit_syntax', | ||||
'Turn on auto editing of files with syntax errors.', | ||||
'Turn off auto editing of files with syntax errors.' | ||||
) | ||||
|
r3968 | addflag('banner', 'TerminalIPythonApp.display_banner', | ||
|
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 | ||||
|
r3967 | in Unix, Control-Z/Enter in Windows). By typing 'exit' or 'quit', | ||
you can force a direct exit without any confirmation.""", | ||||
|
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 | ||||
classic_config.InteractiveShell.prompt_in1 = '>>> ' | ||||
classic_config.InteractiveShell.prompt_in2 = '... ' | ||||
classic_config.InteractiveShell.prompt_out = '' | ||||
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' | ||||
flags['classic']=( | ||||
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 | ||||
flags['quick']=( | ||||
|
r3968 | {'TerminalIPythonApp' : {'quick' : True}}, | ||
|
r3963 | "Enable quick startup with no config files." | ||
) | ||||
flags['i'] = ( | ||||
|
r3968 | {'TerminalIPythonApp' : {'force_interact' : True}}, | ||
|
r3963 | "If running code from the command line, become interactive afterwards." | ||
) | ||||
flags['pylab'] = ( | ||||
|
r3968 | {'TerminalIPythonApp' : {'pylab' : 'auto'}}, | ||
|
r3963 | """Pre-load matplotlib and numpy for interactive use with | ||
the default matplotlib backend.""" | ||||
) | ||||
aliases = dict(base_aliases) | ||||
|
r3968 | aliases.update(shell_aliases) | ||
|
r3963 | |||
# it's possible we don't want short aliases for *all* of these: | ||||
aliases.update(dict( | ||||
|
r3968 | gui='TerminalIPythonApp.gui', | ||
pylab='TerminalIPythonApp.pylab', | ||||
|
r3963 | )) | ||
|
r2506 | |||
#----------------------------------------------------------------------------- | ||||
|
r2427 | # Main classes and functions | ||
#----------------------------------------------------------------------------- | ||||
|
r2245 | |||
|
r3968 | class TerminalIPythonApp(BaseIPythonApplication, InteractiveShellApp): | ||
|
r2328 | name = u'ipython' | ||
|
r3963 | description = usage.cl_usage | ||
|
r2511 | default_config_file_name = default_config_file_name | ||
|
r2506 | crash_handler_class = IPAppCrashHandler | ||
|
r3982 | |||
|
r3963 | flags = Dict(flags) | ||
aliases = Dict(aliases) | ||||
|
r3968 | classes = [InteractiveShellApp, TerminalInteractiveShell, ProfileDir, PlainTextFormatter] | ||
|
r3982 | subcommands = Dict(dict( | ||
|
r4022 | qtconsole=('IPython.frontend.qt.console.qtconsoleapp.IPythonQtConsoleApp', | ||
"""Launch the IPython Qt Console.""" | ||||
|
r4024 | ), | ||
profile = ("IPython.core.profileapp.ProfileApp", | ||||
"Create and manage IPython profiles.") | ||||
|
r3982 | )) | ||
|
r4025 | # *do* autocreate requested profile, but don't create the config file. | ||
|
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 | ||||
gui = CaselessStrEnum(('qt','wx','gtk'), config=True, | ||||
help="Enable GUI event loop integration ('qt', 'wx', 'gtk')." | ||||
) | ||||
pylab = CaselessStrEnum(['tk', 'qt', 'wx', 'gtk', 'osx', 'auto'], | ||||
config=True, | ||||
help="""Pre-load matplotlib and numpy for interactive use, | ||||
selecting a particular matplotlib backend and loop integration. | ||||
""" | ||||
) | ||||
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 | ||||
|
r3968 | |||
|
r3963 | def _file_to_run_changed(self, name, old, new): | ||
if new and not self.force_interact: | ||||
self.interact = False | ||||
_code_to_run_changed = _file_to_run_changed | ||||
# internal, not-configurable | ||||
interact=Bool(True) | ||||
def initialize(self, argv=None): | ||||
"""Do actions after construct, but before starting the app.""" | ||||
|
r3968 | super(TerminalIPythonApp, self).initialize(argv) | ||
|
r3982 | if self.subapp is not None: | ||
# don't bother initializing further, starting subapp | ||||
return | ||||
|
r3963 | if not self.ignore_old_config: | ||
check_for_old_config(self.ipython_dir) | ||||
# print self.extra_args | ||||
if self.extra_args: | ||||
self.file_to_run = self.extra_args[0] | ||||
# 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""" | ||||
|
r2203 | # I am a little hesitant to put these into InteractiveShell itself. | ||
# But that might be the place for them | ||||
sys.path.insert(0, '') | ||||
|
r2252 | |||
|
r2731 | # Create an InteractiveShell instance. | ||
|
r2252 | # shell.display_banner should always be False for the terminal | ||
# based app, because we call shell.show_banner() by hand below | ||||
# so the banner shows *before* all extension loading stuff. | ||||
|
r3963 | self.shell = TerminalInteractiveShell.instance(config=self.config, | ||
display_banner=False, profile_dir=self.profile_dir, | ||||
ipython_dir=self.ipython_dir) | ||||
|
r2252 | |||
|
r3963 | def init_banner(self): | ||
"""optionally display the banner""" | ||||
if self.display_banner and self.interact: | ||||
self.shell.show_banner() | ||||
|
r2252 | # Make sure there is a space below the banner. | ||
if self.log_level <= logging.INFO: print | ||||
|
r2363 | |||
|
r3963 | def init_gui_pylab(self): | ||
|
r2363 | """Enable GUI event loop integration, taking pylab into account.""" | ||
|
r3963 | gui = self.gui | ||
|
r2363 | |||
|
r3963 | # Using `pylab` will also require gui activation, though which toolkit | ||
|
r2388 | # to use may be chosen automatically based on mpl configuration. | ||
|
r3963 | if self.pylab: | ||
|
r2363 | activate = self.shell.enable_pylab | ||
|
r3963 | if self.pylab == 'auto': | ||
|
r2388 | gui = None | ||
else: | ||||
|
r3963 | gui = self.pylab | ||
|
r2363 | else: | ||
# Enable only GUI integration, no pylab | ||||
activate = inputhook.enable_gui | ||||
|
r3963 | if gui or self.pylab: | ||
|
r2363 | try: | ||
|
r2388 | self.log.info("Enabling GUI event loop integration, " | ||
|
r3963 | "toolkit=%s, pylab=%s" % (gui, self.pylab) ) | ||
|
r2363 | activate(gui) | ||
except: | ||||
self.log.warn("Error in enabling GUI event loop integration:") | ||||
self.shell.showtraceback() | ||||
|
r2252 | |||
|
r3963 | def start(self): | ||
|
r3982 | if self.subapp is not None: | ||
return self.subapp.start() | ||||
|
r3963 | # perform any prexec steps: | ||
if self.interact: | ||||
|
r2253 | self.log.debug("Starting IPython's mainloop...") | ||
self.shell.mainloop() | ||||
|
r2391 | else: | ||
|
r3963 | self.log.debug("IPython not interactive...") | ||
|
r2202 | |||
|
r2363 | |||
|
r2322 | def load_default_config(ipython_dir=None): | ||
"""Load the default config file from the default ipython_dir. | ||||
|
r2245 | |||
This is useful for embedded shells. | ||||
""" | ||||
|
r2322 | if ipython_dir is None: | ||
ipython_dir = get_ipython_dir() | ||||
|
r3963 | profile_dir = os.path.join(ipython_dir, 'profile_default') | ||
cl = PyFileConfigLoader(default_config_file_name, profile_dir) | ||||
|
r2245 | config = cl.load_config() | ||
return config | ||||
|
r2269 | def launch_new_instance(): | ||
|
r2296 | """Create and run a full blown IPython instance""" | ||
|
r3969 | app = TerminalIPythonApp.instance() | ||
|
r3963 | app.initialize() | ||
|
r2269 | app.start() | ||
|
r2501 | |||
|
r2507 | |||
if __name__ == '__main__': | ||||
launch_new_instance() | ||||
|
r4021 | |||