##// END OF EJS Templates
add `ipython install-nbextension` entrypoint
MinRK -
Show More
@@ -1,101 +1,176 b''
1 # coding: utf-8
1 # coding: utf-8
2 """Utilities for installing Javascript extensions for the notebook"""
2 """Utilities for installing Javascript extensions for the notebook"""
3
3
4 #-----------------------------------------------------------------------------
4 #-----------------------------------------------------------------------------
5 # Copyright (C) 2014 The IPython Development Team
5 # Copyright (C) 2014 The IPython Development Team
6 #
6 #
7 # Distributed under the terms of the BSD License. The full license is in
7 # Distributed under the terms of the BSD License. The full license is in
8 # the file COPYING, distributed as part of this software.
8 # the file COPYING, distributed as part of this software.
9 #-----------------------------------------------------------------------------
9 #-----------------------------------------------------------------------------
10
10
11 from __future__ import print_function
11 from __future__ import print_function
12
12
13 import os
13 import os
14 import shutil
14 import shutil
15 from os.path import basename, join as pjoin
15 from os.path import basename, join as pjoin
16
16
17 from IPython.utils.path import get_ipython_dir
17 from IPython.utils.path import get_ipython_dir
18 from IPython.utils.py3compat import string_types, cast_unicode_py2
18 from IPython.utils.py3compat import string_types, cast_unicode_py2
19
19
20
20
21 def _should_copy(src, dest, verbose=1):
21 def _should_copy(src, dest, verbose=1):
22 """should a file be copied?"""
22 """should a file be copied?"""
23 if not os.path.exists(dest):
23 if not os.path.exists(dest):
24 return True
24 return True
25 if os.stat(dest).st_mtime < os.stat(src).st_mtime:
25 if os.stat(dest).st_mtime < os.stat(src).st_mtime:
26 if verbose >= 2:
26 if verbose >= 2:
27 print("%s is out of date" % dest)
27 print("%s is out of date" % dest)
28 return True
28 return True
29 if verbose >= 2:
29 if verbose >= 2:
30 print("%s is up to date" % dest)
30 print("%s is up to date" % dest)
31 return False
31 return False
32
32
33
33
34 def _maybe_copy(src, dest, verbose=1):
34 def _maybe_copy(src, dest, verbose=1):
35 """copy a file if it needs updating"""
35 """copy a file if it needs updating"""
36 if _should_copy(src, dest, verbose):
36 if _should_copy(src, dest, verbose):
37 if verbose >= 1:
37 if verbose >= 1:
38 print("copying %s -> %s" % (src, dest))
38 print("copying %s -> %s" % (src, dest))
39 shutil.copy2(src, dest)
39 shutil.copy2(src, dest)
40
40
41
41
42 def install_nbextension(files, overwrite=False, ipython_dir=None, verbose=1):
42 def install_nbextension(files, overwrite=False, ipython_dir=None, verbose=1):
43 """Install a Javascript extension for the notebook
43 """Install a Javascript extension for the notebook
44
44
45 Stages files and/or directories into IPYTHONDIR/nbextensions.
45 Stages files and/or directories into IPYTHONDIR/nbextensions.
46 By default, this comparse modification time, and only stages files that need updating.
46 By default, this comparse modification time, and only stages files that need updating.
47 If `overwrite` is specified, matching files are purged before proceeding.
47 If `overwrite` is specified, matching files are purged before proceeding.
48
48
49 Parameters
49 Parameters
50 ----------
50 ----------
51
51
52 files : list(paths)
52 files : list(paths)
53 One or more paths to existing files or directories to install.
53 One or more paths to existing files or directories to install.
54 These will be installed with their base name, so '/path/to/foo'
54 These will be installed with their base name, so '/path/to/foo'
55 will install to 'nbextensions/foo'.
55 will install to 'nbextensions/foo'.
56 overwrite : bool [default: False]
56 overwrite : bool [default: False]
57 If True, always install the files, regardless of what may already be installed.
57 If True, always install the files, regardless of what may already be installed.
58 ipython_dir : str [optional]
58 ipython_dir : str [optional]
59 The path to an IPython directory, if the default value is not desired.
59 The path to an IPython directory, if the default value is not desired.
60 get_ipython_dir() is used by default.
60 get_ipython_dir() is used by default.
61 verbose : int [default: 1]
61 verbose : int [default: 1]
62 Set verbosity level. The default is 1, where file actions are printed.
62 Set verbosity level. The default is 1, where file actions are printed.
63 set verbose=2 for more output, or verbose=0 for silence.
63 set verbose=2 for more output, or verbose=0 for silence.
64 """
64 """
65
65
66 ipython_dir = ipython_dir or get_ipython_dir()
66 ipython_dir = ipython_dir or get_ipython_dir()
67 nbext = pjoin(ipython_dir, u'nbextensions')
67 nbext = pjoin(ipython_dir, u'nbextensions')
68 # make sure nbextensions dir exists
68 # make sure nbextensions dir exists
69 if not os.path.exists(nbext):
69 if not os.path.exists(nbext):
70 os.makedirs(nbext)
70 os.makedirs(nbext)
71
71
72 if isinstance(files, string_types):
72 if isinstance(files, string_types):
73 # one file given, turn it into a list
73 # one file given, turn it into a list
74 files = [files]
74 files = [files]
75
75
76 for path in map(cast_unicode_py2, files):
76 for path in map(cast_unicode_py2, files):
77 dest = pjoin(nbext, basename(path))
77 dest = pjoin(nbext, basename(path))
78 if overwrite and os.path.exists(dest):
78 if overwrite and os.path.exists(dest):
79 if verbose >= 1:
79 if verbose >= 1:
80 print("removing %s" % dest)
80 print("removing %s" % dest)
81 if os.path.isdir(dest):
81 if os.path.isdir(dest):
82 shutil.rmtree(dest)
82 shutil.rmtree(dest)
83 else:
83 else:
84 os.remove(dest)
84 os.remove(dest)
85
85
86 if os.path.isdir(path):
86 if os.path.isdir(path):
87 strip_prefix_len = len(path) - len(basename(path))
87 strip_prefix_len = len(path) - len(basename(path))
88 for parent, dirs, files in os.walk(path):
88 for parent, dirs, files in os.walk(path):
89 dest_dir = pjoin(nbext, parent[strip_prefix_len:])
89 dest_dir = pjoin(nbext, parent[strip_prefix_len:])
90 if not os.path.exists(dest_dir):
90 if not os.path.exists(dest_dir):
91 if verbose >= 2:
91 if verbose >= 2:
92 print("making directory %s" % dest_dir)
92 print("making directory %s" % dest_dir)
93 os.makedirs(dest_dir)
93 os.makedirs(dest_dir)
94 for file in files:
94 for file in files:
95 src = pjoin(parent, file)
95 src = pjoin(parent, file)
96 # print("%r, %r" % (dest_dir, file))
96 # print("%r, %r" % (dest_dir, file))
97 dest = pjoin(dest_dir, file)
97 dest = pjoin(dest_dir, file)
98 _maybe_copy(src, dest, verbose)
98 _maybe_copy(src, dest, verbose)
99 else:
99 else:
100 src = path
100 src = path
101 _maybe_copy(src, dest, verbose)
101 _maybe_copy(src, dest, verbose)
102
103 #----------------------------------------------------------------------
104 # install nbextension app
105 #----------------------------------------------------------------------
106
107 import logging
108 from IPython.utils.traitlets import Bool, Enum
109 from IPython.core.application import BaseIPythonApplication
110
111 flags = {
112 "overwrite" : ({
113 "NBExtensionApp" : {
114 "overwrite" : True,
115 }}, "Force overwrite of existing files"
116 ),
117 "debug" : ({
118 "NBExtensionApp" : {
119 "verbose" : 2,
120 }}, "Extra output"
121 ),
122 "quiet" : ({
123 "NBExtensionApp" : {
124 "verbose" : 0,
125 }}, "Minimal output"
126 ),
127 }
128 aliases = {
129 "ipython-dir" : "NBExtensionApp.ipython_dir"
130 }
131
132 class NBExtensionApp(BaseIPythonApplication):
133 """Entry point for installing notebook extensions"""
134
135 description = """Install IPython notebook extensions
136
137 Usage
138
139 ipython install-nbextension file [more files or folders]
140
141 This copies files and/or folders into the IPython nbextensions directory.
142 If the requested files are already up to date, no action is taken
143 unless --overwrite is specified.
144 """
145
146 examples = """
147 ipython install-nbextension /path/to/d3.js /path/to/myextension
148 """
149 aliases = aliases
150 flags = flags
151
152 overwrite = Bool(False, config=True, help="Force overwrite of existing files")
153 verbose = Enum((0,1,2), default_value=1, config=True,
154 help="Verbosity level"
155 )
156
157 def install_extensions(self):
158 install_nbextension(self.extra_args,
159 overwrite=self.overwrite,
160 verbose=self.verbose,
161 ipython_dir=self.ipython_dir,
162 )
163
164 def start(self):
165 if not self.extra_args:
166 nbext = pjoin(self.ipython_dir, u'nbextensions')
167 print("Notebook extensions in %s:" % nbext)
168 for ext in os.listdir(nbext):
169 print(u" %s" % ext)
170 else:
171 self.install_extensions()
172
173
174 if __name__ == '__main__':
175 NBExtensionApp.launch_instance()
176 No newline at end of file
@@ -1,391 +1,395 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 # encoding: utf-8
2 # encoding: utf-8
3 """
3 """
4 The :class:`~IPython.core.application.Application` object for the command
4 The :class:`~IPython.core.application.Application` object for the command
5 line :command:`ipython` program.
5 line :command:`ipython` program.
6
6
7 Authors
7 Authors
8 -------
8 -------
9
9
10 * Brian Granger
10 * Brian Granger
11 * Fernando Perez
11 * Fernando Perez
12 * Min Ragan-Kelley
12 * Min Ragan-Kelley
13 """
13 """
14
14
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16 # Copyright (C) 2008-2011 The IPython Development Team
16 # Copyright (C) 2008-2011 The IPython Development Team
17 #
17 #
18 # Distributed under the terms of the BSD License. The full license is in
18 # Distributed under the terms of the BSD License. The full license is in
19 # the file COPYING, distributed as part of this software.
19 # the file COPYING, distributed as part of this software.
20 #-----------------------------------------------------------------------------
20 #-----------------------------------------------------------------------------
21
21
22 #-----------------------------------------------------------------------------
22 #-----------------------------------------------------------------------------
23 # Imports
23 # Imports
24 #-----------------------------------------------------------------------------
24 #-----------------------------------------------------------------------------
25
25
26 from __future__ import absolute_import
26 from __future__ import absolute_import
27 from __future__ import print_function
27 from __future__ import print_function
28
28
29 import logging
29 import logging
30 import os
30 import os
31 import sys
31 import sys
32
32
33 from IPython.config.loader import (
33 from IPython.config.loader import (
34 Config, PyFileConfigLoader, ConfigFileNotFound
34 Config, PyFileConfigLoader, ConfigFileNotFound
35 )
35 )
36 from IPython.config.application import boolean_flag, catch_config_error, Application
36 from IPython.config.application import boolean_flag, catch_config_error, Application
37 from IPython.core import release
37 from IPython.core import release
38 from IPython.core import usage
38 from IPython.core import usage
39 from IPython.core.completer import IPCompleter
39 from IPython.core.completer import IPCompleter
40 from IPython.core.crashhandler import CrashHandler
40 from IPython.core.crashhandler import CrashHandler
41 from IPython.core.formatters import PlainTextFormatter
41 from IPython.core.formatters import PlainTextFormatter
42 from IPython.core.history import HistoryManager
42 from IPython.core.history import HistoryManager
43 from IPython.core.prompts import PromptManager
43 from IPython.core.prompts import PromptManager
44 from IPython.core.application import (
44 from IPython.core.application import (
45 ProfileDir, BaseIPythonApplication, base_flags, base_aliases
45 ProfileDir, BaseIPythonApplication, base_flags, base_aliases
46 )
46 )
47 from IPython.core.magics import ScriptMagics
47 from IPython.core.magics import ScriptMagics
48 from IPython.core.shellapp import (
48 from IPython.core.shellapp import (
49 InteractiveShellApp, shell_flags, shell_aliases
49 InteractiveShellApp, shell_flags, shell_aliases
50 )
50 )
51 from IPython.extensions.storemagic import StoreMagics
51 from IPython.extensions.storemagic import StoreMagics
52 from IPython.terminal.interactiveshell import TerminalInteractiveShell
52 from IPython.terminal.interactiveshell import TerminalInteractiveShell
53 from IPython.utils import warn
53 from IPython.utils import warn
54 from IPython.utils.path import get_ipython_dir, check_for_old_config
54 from IPython.utils.path import get_ipython_dir, check_for_old_config
55 from IPython.utils.traitlets import (
55 from IPython.utils.traitlets import (
56 Bool, List, Dict,
56 Bool, List, Dict,
57 )
57 )
58
58
59 #-----------------------------------------------------------------------------
59 #-----------------------------------------------------------------------------
60 # Globals, utilities and helpers
60 # Globals, utilities and helpers
61 #-----------------------------------------------------------------------------
61 #-----------------------------------------------------------------------------
62
62
63 _examples = """
63 _examples = """
64 ipython --matplotlib # enable matplotlib integration
64 ipython --matplotlib # enable matplotlib integration
65 ipython --matplotlib=qt # enable matplotlib integration with qt4 backend
65 ipython --matplotlib=qt # enable matplotlib integration with qt4 backend
66
66
67 ipython --log-level=DEBUG # set logging to DEBUG
67 ipython --log-level=DEBUG # set logging to DEBUG
68 ipython --profile=foo # start with profile foo
68 ipython --profile=foo # start with profile foo
69
69
70 ipython qtconsole # start the qtconsole GUI application
70 ipython qtconsole # start the qtconsole GUI application
71 ipython help qtconsole # show the help for the qtconsole subcmd
71 ipython help qtconsole # show the help for the qtconsole subcmd
72
72
73 ipython console # start the terminal-based console application
73 ipython console # start the terminal-based console application
74 ipython help console # show the help for the console subcmd
74 ipython help console # show the help for the console subcmd
75
75
76 ipython notebook # start the IPython notebook
76 ipython notebook # start the IPython notebook
77 ipython help notebook # show the help for the notebook subcmd
77 ipython help notebook # show the help for the notebook subcmd
78
78
79 ipython profile create foo # create profile foo w/ default config files
79 ipython profile create foo # create profile foo w/ default config files
80 ipython help profile # show the help for the profile subcmd
80 ipython help profile # show the help for the profile subcmd
81
81
82 ipython locate # print the path to the IPython directory
82 ipython locate # print the path to the IPython directory
83 ipython locate profile foo # print the path to the directory for profile `foo`
83 ipython locate profile foo # print the path to the directory for profile `foo`
84
84
85 ipython nbconvert # convert notebooks to/from other formats
85 ipython nbconvert # convert notebooks to/from other formats
86 """
86 """
87
87
88 #-----------------------------------------------------------------------------
88 #-----------------------------------------------------------------------------
89 # Crash handler for this application
89 # Crash handler for this application
90 #-----------------------------------------------------------------------------
90 #-----------------------------------------------------------------------------
91
91
92 class IPAppCrashHandler(CrashHandler):
92 class IPAppCrashHandler(CrashHandler):
93 """sys.excepthook for IPython itself, leaves a detailed report on disk."""
93 """sys.excepthook for IPython itself, leaves a detailed report on disk."""
94
94
95 def __init__(self, app):
95 def __init__(self, app):
96 contact_name = release.author
96 contact_name = release.author
97 contact_email = release.author_email
97 contact_email = release.author_email
98 bug_tracker = 'https://github.com/ipython/ipython/issues'
98 bug_tracker = 'https://github.com/ipython/ipython/issues'
99 super(IPAppCrashHandler,self).__init__(
99 super(IPAppCrashHandler,self).__init__(
100 app, contact_name, contact_email, bug_tracker
100 app, contact_name, contact_email, bug_tracker
101 )
101 )
102
102
103 def make_report(self,traceback):
103 def make_report(self,traceback):
104 """Return a string containing a crash report."""
104 """Return a string containing a crash report."""
105
105
106 sec_sep = self.section_sep
106 sec_sep = self.section_sep
107 # Start with parent report
107 # Start with parent report
108 report = [super(IPAppCrashHandler, self).make_report(traceback)]
108 report = [super(IPAppCrashHandler, self).make_report(traceback)]
109 # Add interactive-specific info we may have
109 # Add interactive-specific info we may have
110 rpt_add = report.append
110 rpt_add = report.append
111 try:
111 try:
112 rpt_add(sec_sep+"History of session input:")
112 rpt_add(sec_sep+"History of session input:")
113 for line in self.app.shell.user_ns['_ih']:
113 for line in self.app.shell.user_ns['_ih']:
114 rpt_add(line)
114 rpt_add(line)
115 rpt_add('\n*** Last line of input (may not be in above history):\n')
115 rpt_add('\n*** Last line of input (may not be in above history):\n')
116 rpt_add(self.app.shell._last_input_line+'\n')
116 rpt_add(self.app.shell._last_input_line+'\n')
117 except:
117 except:
118 pass
118 pass
119
119
120 return ''.join(report)
120 return ''.join(report)
121
121
122 #-----------------------------------------------------------------------------
122 #-----------------------------------------------------------------------------
123 # Aliases and Flags
123 # Aliases and Flags
124 #-----------------------------------------------------------------------------
124 #-----------------------------------------------------------------------------
125 flags = dict(base_flags)
125 flags = dict(base_flags)
126 flags.update(shell_flags)
126 flags.update(shell_flags)
127 frontend_flags = {}
127 frontend_flags = {}
128 addflag = lambda *args: frontend_flags.update(boolean_flag(*args))
128 addflag = lambda *args: frontend_flags.update(boolean_flag(*args))
129 addflag('autoedit-syntax', 'TerminalInteractiveShell.autoedit_syntax',
129 addflag('autoedit-syntax', 'TerminalInteractiveShell.autoedit_syntax',
130 'Turn on auto editing of files with syntax errors.',
130 'Turn on auto editing of files with syntax errors.',
131 'Turn off auto editing of files with syntax errors.'
131 'Turn off auto editing of files with syntax errors.'
132 )
132 )
133 addflag('banner', 'TerminalIPythonApp.display_banner',
133 addflag('banner', 'TerminalIPythonApp.display_banner',
134 "Display a banner upon starting IPython.",
134 "Display a banner upon starting IPython.",
135 "Don't display a banner upon starting IPython."
135 "Don't display a banner upon starting IPython."
136 )
136 )
137 addflag('confirm-exit', 'TerminalInteractiveShell.confirm_exit',
137 addflag('confirm-exit', 'TerminalInteractiveShell.confirm_exit',
138 """Set to confirm when you try to exit IPython with an EOF (Control-D
138 """Set to confirm when you try to exit IPython with an EOF (Control-D
139 in Unix, Control-Z/Enter in Windows). By typing 'exit' or 'quit',
139 in Unix, Control-Z/Enter in Windows). By typing 'exit' or 'quit',
140 you can force a direct exit without any confirmation.""",
140 you can force a direct exit without any confirmation.""",
141 "Don't prompt the user when exiting."
141 "Don't prompt the user when exiting."
142 )
142 )
143 addflag('term-title', 'TerminalInteractiveShell.term_title',
143 addflag('term-title', 'TerminalInteractiveShell.term_title',
144 "Enable auto setting the terminal title.",
144 "Enable auto setting the terminal title.",
145 "Disable auto setting the terminal title."
145 "Disable auto setting the terminal title."
146 )
146 )
147 classic_config = Config()
147 classic_config = Config()
148 classic_config.InteractiveShell.cache_size = 0
148 classic_config.InteractiveShell.cache_size = 0
149 classic_config.PlainTextFormatter.pprint = False
149 classic_config.PlainTextFormatter.pprint = False
150 classic_config.PromptManager.in_template = '>>> '
150 classic_config.PromptManager.in_template = '>>> '
151 classic_config.PromptManager.in2_template = '... '
151 classic_config.PromptManager.in2_template = '... '
152 classic_config.PromptManager.out_template = ''
152 classic_config.PromptManager.out_template = ''
153 classic_config.InteractiveShell.separate_in = ''
153 classic_config.InteractiveShell.separate_in = ''
154 classic_config.InteractiveShell.separate_out = ''
154 classic_config.InteractiveShell.separate_out = ''
155 classic_config.InteractiveShell.separate_out2 = ''
155 classic_config.InteractiveShell.separate_out2 = ''
156 classic_config.InteractiveShell.colors = 'NoColor'
156 classic_config.InteractiveShell.colors = 'NoColor'
157 classic_config.InteractiveShell.xmode = 'Plain'
157 classic_config.InteractiveShell.xmode = 'Plain'
158
158
159 frontend_flags['classic']=(
159 frontend_flags['classic']=(
160 classic_config,
160 classic_config,
161 "Gives IPython a similar feel to the classic Python prompt."
161 "Gives IPython a similar feel to the classic Python prompt."
162 )
162 )
163 # # log doesn't make so much sense this way anymore
163 # # log doesn't make so much sense this way anymore
164 # paa('--log','-l',
164 # paa('--log','-l',
165 # action='store_true', dest='InteractiveShell.logstart',
165 # action='store_true', dest='InteractiveShell.logstart',
166 # help="Start logging to the default log file (./ipython_log.py).")
166 # help="Start logging to the default log file (./ipython_log.py).")
167 #
167 #
168 # # quick is harder to implement
168 # # quick is harder to implement
169 frontend_flags['quick']=(
169 frontend_flags['quick']=(
170 {'TerminalIPythonApp' : {'quick' : True}},
170 {'TerminalIPythonApp' : {'quick' : True}},
171 "Enable quick startup with no config files."
171 "Enable quick startup with no config files."
172 )
172 )
173
173
174 frontend_flags['i'] = (
174 frontend_flags['i'] = (
175 {'TerminalIPythonApp' : {'force_interact' : True}},
175 {'TerminalIPythonApp' : {'force_interact' : True}},
176 """If running code from the command line, become interactive afterwards.
176 """If running code from the command line, become interactive afterwards.
177 Note: can also be given simply as '-i'."""
177 Note: can also be given simply as '-i'."""
178 )
178 )
179 flags.update(frontend_flags)
179 flags.update(frontend_flags)
180
180
181 aliases = dict(base_aliases)
181 aliases = dict(base_aliases)
182 aliases.update(shell_aliases)
182 aliases.update(shell_aliases)
183
183
184 #-----------------------------------------------------------------------------
184 #-----------------------------------------------------------------------------
185 # Main classes and functions
185 # Main classes and functions
186 #-----------------------------------------------------------------------------
186 #-----------------------------------------------------------------------------
187
187
188
188
189 class LocateIPythonApp(BaseIPythonApplication):
189 class LocateIPythonApp(BaseIPythonApplication):
190 description = """print the path to the IPython dir"""
190 description = """print the path to the IPython dir"""
191 subcommands = Dict(dict(
191 subcommands = Dict(dict(
192 profile=('IPython.core.profileapp.ProfileLocate',
192 profile=('IPython.core.profileapp.ProfileLocate',
193 "print the path to an IPython profile directory",
193 "print the path to an IPython profile directory",
194 ),
194 ),
195 ))
195 ))
196 def start(self):
196 def start(self):
197 if self.subapp is not None:
197 if self.subapp is not None:
198 return self.subapp.start()
198 return self.subapp.start()
199 else:
199 else:
200 print(self.ipython_dir)
200 print(self.ipython_dir)
201
201
202
202
203 class TerminalIPythonApp(BaseIPythonApplication, InteractiveShellApp):
203 class TerminalIPythonApp(BaseIPythonApplication, InteractiveShellApp):
204 name = u'ipython'
204 name = u'ipython'
205 description = usage.cl_usage
205 description = usage.cl_usage
206 crash_handler_class = IPAppCrashHandler
206 crash_handler_class = IPAppCrashHandler
207 examples = _examples
207 examples = _examples
208
208
209 flags = Dict(flags)
209 flags = Dict(flags)
210 aliases = Dict(aliases)
210 aliases = Dict(aliases)
211 classes = List()
211 classes = List()
212 def _classes_default(self):
212 def _classes_default(self):
213 """This has to be in a method, for TerminalIPythonApp to be available."""
213 """This has to be in a method, for TerminalIPythonApp to be available."""
214 return [
214 return [
215 InteractiveShellApp, # ShellApp comes before TerminalApp, because
215 InteractiveShellApp, # ShellApp comes before TerminalApp, because
216 self.__class__, # it will also affect subclasses (e.g. QtConsole)
216 self.__class__, # it will also affect subclasses (e.g. QtConsole)
217 TerminalInteractiveShell,
217 TerminalInteractiveShell,
218 PromptManager,
218 PromptManager,
219 HistoryManager,
219 HistoryManager,
220 ProfileDir,
220 ProfileDir,
221 PlainTextFormatter,
221 PlainTextFormatter,
222 IPCompleter,
222 IPCompleter,
223 ScriptMagics,
223 ScriptMagics,
224 StoreMagics,
224 StoreMagics,
225 ]
225 ]
226
226
227 subcommands = Dict(dict(
227 subcommands = dict(
228 qtconsole=('IPython.qt.console.qtconsoleapp.IPythonQtConsoleApp',
228 qtconsole=('IPython.qt.console.qtconsoleapp.IPythonQtConsoleApp',
229 """Launch the IPython Qt Console."""
229 """Launch the IPython Qt Console."""
230 ),
230 ),
231 notebook=('IPython.html.notebookapp.NotebookApp',
231 notebook=('IPython.html.notebookapp.NotebookApp',
232 """Launch the IPython HTML Notebook Server."""
232 """Launch the IPython HTML Notebook Server."""
233 ),
233 ),
234 profile = ("IPython.core.profileapp.ProfileApp",
234 profile = ("IPython.core.profileapp.ProfileApp",
235 "Create and manage IPython profiles."
235 "Create and manage IPython profiles."
236 ),
236 ),
237 kernel = ("IPython.kernel.zmq.kernelapp.IPKernelApp",
237 kernel = ("IPython.kernel.zmq.kernelapp.IPKernelApp",
238 "Start a kernel without an attached frontend."
238 "Start a kernel without an attached frontend."
239 ),
239 ),
240 console=('IPython.terminal.console.app.ZMQTerminalIPythonApp',
240 console=('IPython.terminal.console.app.ZMQTerminalIPythonApp',
241 """Launch the IPython terminal-based Console."""
241 """Launch the IPython terminal-based Console."""
242 ),
242 ),
243 locate=('IPython.terminal.ipapp.LocateIPythonApp',
243 locate=('IPython.terminal.ipapp.LocateIPythonApp',
244 LocateIPythonApp.description
244 LocateIPythonApp.description
245 ),
245 ),
246 history=('IPython.core.historyapp.HistoryApp',
246 history=('IPython.core.historyapp.HistoryApp',
247 "Manage the IPython history database."
247 "Manage the IPython history database."
248 ),
248 ),
249 nbconvert=('IPython.nbconvert.nbconvertapp.NbConvertApp',
249 nbconvert=('IPython.nbconvert.nbconvertapp.NbConvertApp',
250 "Convert notebooks to/from other formats."
250 "Convert notebooks to/from other formats."
251 ),
251 ),
252 trust=('IPython.nbformat.sign.TrustNotebookApp',
252 trust=('IPython.nbformat.sign.TrustNotebookApp',
253 "Sign notebooks to trust their potentially unsafe contents at load."
253 "Sign notebooks to trust their potentially unsafe contents at load."
254 ),
254 ),
255 ))
255 ))
256 subcommands['install-nbextension'] = (
257 "IPython.html.nbextensions.NBExtensionApp",
258 "Install IPython notebook extension files"
259 )
256
260
257 # *do* autocreate requested profile, but don't create the config file.
261 # *do* autocreate requested profile, but don't create the config file.
258 auto_create=Bool(True)
262 auto_create=Bool(True)
259 # configurables
263 # configurables
260 ignore_old_config=Bool(False, config=True,
264 ignore_old_config=Bool(False, config=True,
261 help="Suppress warning messages about legacy config files"
265 help="Suppress warning messages about legacy config files"
262 )
266 )
263 quick = Bool(False, config=True,
267 quick = Bool(False, config=True,
264 help="""Start IPython quickly by skipping the loading of config files."""
268 help="""Start IPython quickly by skipping the loading of config files."""
265 )
269 )
266 def _quick_changed(self, name, old, new):
270 def _quick_changed(self, name, old, new):
267 if new:
271 if new:
268 self.load_config_file = lambda *a, **kw: None
272 self.load_config_file = lambda *a, **kw: None
269 self.ignore_old_config=True
273 self.ignore_old_config=True
270
274
271 display_banner = Bool(True, config=True,
275 display_banner = Bool(True, config=True,
272 help="Whether to display a banner upon starting IPython."
276 help="Whether to display a banner upon starting IPython."
273 )
277 )
274
278
275 # if there is code of files to run from the cmd line, don't interact
279 # if there is code of files to run from the cmd line, don't interact
276 # unless the --i flag (App.force_interact) is true.
280 # unless the --i flag (App.force_interact) is true.
277 force_interact = Bool(False, config=True,
281 force_interact = Bool(False, config=True,
278 help="""If a command or file is given via the command-line,
282 help="""If a command or file is given via the command-line,
279 e.g. 'ipython foo.py', start an interactive shell after executing the
283 e.g. 'ipython foo.py', start an interactive shell after executing the
280 file or command."""
284 file or command."""
281 )
285 )
282 def _force_interact_changed(self, name, old, new):
286 def _force_interact_changed(self, name, old, new):
283 if new:
287 if new:
284 self.interact = True
288 self.interact = True
285
289
286 def _file_to_run_changed(self, name, old, new):
290 def _file_to_run_changed(self, name, old, new):
287 if new:
291 if new:
288 self.something_to_run = True
292 self.something_to_run = True
289 if new and not self.force_interact:
293 if new and not self.force_interact:
290 self.interact = False
294 self.interact = False
291 _code_to_run_changed = _file_to_run_changed
295 _code_to_run_changed = _file_to_run_changed
292 _module_to_run_changed = _file_to_run_changed
296 _module_to_run_changed = _file_to_run_changed
293
297
294 # internal, not-configurable
298 # internal, not-configurable
295 interact=Bool(True)
299 interact=Bool(True)
296 something_to_run=Bool(False)
300 something_to_run=Bool(False)
297
301
298 def parse_command_line(self, argv=None):
302 def parse_command_line(self, argv=None):
299 """override to allow old '-pylab' flag with deprecation warning"""
303 """override to allow old '-pylab' flag with deprecation warning"""
300
304
301 argv = sys.argv[1:] if argv is None else argv
305 argv = sys.argv[1:] if argv is None else argv
302
306
303 if '-pylab' in argv:
307 if '-pylab' in argv:
304 # deprecated `-pylab` given,
308 # deprecated `-pylab` given,
305 # warn and transform into current syntax
309 # warn and transform into current syntax
306 argv = argv[:] # copy, don't clobber
310 argv = argv[:] # copy, don't clobber
307 idx = argv.index('-pylab')
311 idx = argv.index('-pylab')
308 warn.warn("`-pylab` flag has been deprecated.\n"
312 warn.warn("`-pylab` flag has been deprecated.\n"
309 " Use `--matplotlib <backend>` and import pylab manually.")
313 " Use `--matplotlib <backend>` and import pylab manually.")
310 argv[idx] = '--pylab'
314 argv[idx] = '--pylab'
311
315
312 return super(TerminalIPythonApp, self).parse_command_line(argv)
316 return super(TerminalIPythonApp, self).parse_command_line(argv)
313
317
314 @catch_config_error
318 @catch_config_error
315 def initialize(self, argv=None):
319 def initialize(self, argv=None):
316 """Do actions after construct, but before starting the app."""
320 """Do actions after construct, but before starting the app."""
317 super(TerminalIPythonApp, self).initialize(argv)
321 super(TerminalIPythonApp, self).initialize(argv)
318 if self.subapp is not None:
322 if self.subapp is not None:
319 # don't bother initializing further, starting subapp
323 # don't bother initializing further, starting subapp
320 return
324 return
321 if not self.ignore_old_config:
325 if not self.ignore_old_config:
322 check_for_old_config(self.ipython_dir)
326 check_for_old_config(self.ipython_dir)
323 # print self.extra_args
327 # print self.extra_args
324 if self.extra_args and not self.something_to_run:
328 if self.extra_args and not self.something_to_run:
325 self.file_to_run = self.extra_args[0]
329 self.file_to_run = self.extra_args[0]
326 self.init_path()
330 self.init_path()
327 # create the shell
331 # create the shell
328 self.init_shell()
332 self.init_shell()
329 # and draw the banner
333 # and draw the banner
330 self.init_banner()
334 self.init_banner()
331 # Now a variety of things that happen after the banner is printed.
335 # Now a variety of things that happen after the banner is printed.
332 self.init_gui_pylab()
336 self.init_gui_pylab()
333 self.init_extensions()
337 self.init_extensions()
334 self.init_code()
338 self.init_code()
335
339
336 def init_shell(self):
340 def init_shell(self):
337 """initialize the InteractiveShell instance"""
341 """initialize the InteractiveShell instance"""
338 # Create an InteractiveShell instance.
342 # Create an InteractiveShell instance.
339 # shell.display_banner should always be False for the terminal
343 # shell.display_banner should always be False for the terminal
340 # based app, because we call shell.show_banner() by hand below
344 # based app, because we call shell.show_banner() by hand below
341 # so the banner shows *before* all extension loading stuff.
345 # so the banner shows *before* all extension loading stuff.
342 self.shell = TerminalInteractiveShell.instance(parent=self,
346 self.shell = TerminalInteractiveShell.instance(parent=self,
343 display_banner=False, profile_dir=self.profile_dir,
347 display_banner=False, profile_dir=self.profile_dir,
344 ipython_dir=self.ipython_dir, user_ns=self.user_ns)
348 ipython_dir=self.ipython_dir, user_ns=self.user_ns)
345 self.shell.configurables.append(self)
349 self.shell.configurables.append(self)
346
350
347 def init_banner(self):
351 def init_banner(self):
348 """optionally display the banner"""
352 """optionally display the banner"""
349 if self.display_banner and self.interact:
353 if self.display_banner and self.interact:
350 self.shell.show_banner()
354 self.shell.show_banner()
351 # Make sure there is a space below the banner.
355 # Make sure there is a space below the banner.
352 if self.log_level <= logging.INFO: print()
356 if self.log_level <= logging.INFO: print()
353
357
354 def _pylab_changed(self, name, old, new):
358 def _pylab_changed(self, name, old, new):
355 """Replace --pylab='inline' with --pylab='auto'"""
359 """Replace --pylab='inline' with --pylab='auto'"""
356 if new == 'inline':
360 if new == 'inline':
357 warn.warn("'inline' not available as pylab backend, "
361 warn.warn("'inline' not available as pylab backend, "
358 "using 'auto' instead.")
362 "using 'auto' instead.")
359 self.pylab = 'auto'
363 self.pylab = 'auto'
360
364
361 def start(self):
365 def start(self):
362 if self.subapp is not None:
366 if self.subapp is not None:
363 return self.subapp.start()
367 return self.subapp.start()
364 # perform any prexec steps:
368 # perform any prexec steps:
365 if self.interact:
369 if self.interact:
366 self.log.debug("Starting IPython's mainloop...")
370 self.log.debug("Starting IPython's mainloop...")
367 self.shell.mainloop()
371 self.shell.mainloop()
368 else:
372 else:
369 self.log.debug("IPython not interactive...")
373 self.log.debug("IPython not interactive...")
370
374
371 def load_default_config(ipython_dir=None):
375 def load_default_config(ipython_dir=None):
372 """Load the default config file from the default ipython_dir.
376 """Load the default config file from the default ipython_dir.
373
377
374 This is useful for embedded shells.
378 This is useful for embedded shells.
375 """
379 """
376 if ipython_dir is None:
380 if ipython_dir is None:
377 ipython_dir = get_ipython_dir()
381 ipython_dir = get_ipython_dir()
378
382
379 profile_dir = os.path.join(ipython_dir, 'profile_default')
383 profile_dir = os.path.join(ipython_dir, 'profile_default')
380
384
381 config = Config()
385 config = Config()
382 for cf in Application._load_config_files("ipython_config", path=profile_dir):
386 for cf in Application._load_config_files("ipython_config", path=profile_dir):
383 config.update(cf)
387 config.update(cf)
384
388
385 return config
389 return config
386
390
387 launch_new_instance = TerminalIPythonApp.launch_instance
391 launch_new_instance = TerminalIPythonApp.launch_instance
388
392
389
393
390 if __name__ == '__main__':
394 if __name__ == '__main__':
391 launch_new_instance()
395 launch_new_instance()
General Comments 0
You need to be logged in to leave comments. Login now