##// END OF EJS Templates
update '-pylab' deprecation message to new pattern.
MinRK -
Show More
@@ -1,363 +1,363 b''
1 1 #!/usr/bin/env python
2 2 # encoding: utf-8
3 3 """
4 4 The :class:`~IPython.core.application.Application` object for the command
5 5 line :command:`ipython` program.
6 6
7 7 Authors
8 8 -------
9 9
10 10 * Brian Granger
11 11 * Fernando Perez
12 12 * Min Ragan-Kelley
13 13 """
14 14
15 15 #-----------------------------------------------------------------------------
16 16 # Copyright (C) 2008-2010 The IPython Development Team
17 17 #
18 18 # Distributed under the terms of the BSD License. The full license is in
19 19 # the file COPYING, distributed as part of this software.
20 20 #-----------------------------------------------------------------------------
21 21
22 22 #-----------------------------------------------------------------------------
23 23 # Imports
24 24 #-----------------------------------------------------------------------------
25 25
26 26 from __future__ import absolute_import
27 27
28 28 import logging
29 29 import os
30 30 import sys
31 31
32 32 from IPython.config.loader import (
33 33 Config, PyFileConfigLoader
34 34 )
35 35 from IPython.config.application import boolean_flag
36 36 from IPython.core import release
37 37 from IPython.core import usage
38 38 from IPython.core.crashhandler import CrashHandler
39 39 from IPython.core.formatters import PlainTextFormatter
40 40 from IPython.core.application import (
41 41 ProfileDir, BaseIPythonApplication, base_flags, base_aliases
42 42 )
43 43 from IPython.core.shellapp import (
44 44 InteractiveShellApp, shell_flags, shell_aliases
45 45 )
46 46 from IPython.frontend.terminal.interactiveshell import TerminalInteractiveShell
47 47 from IPython.lib import inputhook
48 48 from IPython.utils import warn
49 49 from IPython.utils.path import get_ipython_dir, check_for_old_config
50 50 from IPython.utils.traitlets import (
51 51 Bool, Dict, CaselessStrEnum
52 52 )
53 53
54 54 #-----------------------------------------------------------------------------
55 55 # Globals, utilities and helpers
56 56 #-----------------------------------------------------------------------------
57 57
58 58 #: The default config file name for this application.
59 59 default_config_file_name = u'ipython_config.py'
60 60
61 61
62 62 #-----------------------------------------------------------------------------
63 63 # Crash handler for this application
64 64 #-----------------------------------------------------------------------------
65 65
66 66 class IPAppCrashHandler(CrashHandler):
67 67 """sys.excepthook for IPython itself, leaves a detailed report on disk."""
68 68
69 69 def __init__(self, app):
70 70 contact_name = release.authors['Fernando'][0]
71 71 contact_email = release.authors['Fernando'][1]
72 72 bug_tracker = 'http://github.com/ipython/ipython/issues'
73 73 super(IPAppCrashHandler,self).__init__(
74 74 app, contact_name, contact_email, bug_tracker
75 75 )
76 76
77 77 def make_report(self,traceback):
78 78 """Return a string containing a crash report."""
79 79
80 80 sec_sep = self.section_sep
81 81 # Start with parent report
82 82 report = [super(IPAppCrashHandler, self).make_report(traceback)]
83 83 # Add interactive-specific info we may have
84 84 rpt_add = report.append
85 85 try:
86 86 rpt_add(sec_sep+"History of session input:")
87 87 for line in self.app.shell.user_ns['_ih']:
88 88 rpt_add(line)
89 89 rpt_add('\n*** Last line of input (may not be in above history):\n')
90 90 rpt_add(self.app.shell._last_input_line+'\n')
91 91 except:
92 92 pass
93 93
94 94 return ''.join(report)
95 95
96 96 #-----------------------------------------------------------------------------
97 97 # Aliases and Flags
98 98 #-----------------------------------------------------------------------------
99 99 flags = dict(base_flags)
100 100 flags.update(shell_flags)
101 101 addflag = lambda *args: flags.update(boolean_flag(*args))
102 102 addflag('autoedit-syntax', 'TerminalInteractiveShell.autoedit_syntax',
103 103 'Turn on auto editing of files with syntax errors.',
104 104 'Turn off auto editing of files with syntax errors.'
105 105 )
106 106 addflag('banner', 'TerminalIPythonApp.display_banner',
107 107 "Display a banner upon starting IPython.",
108 108 "Don't display a banner upon starting IPython."
109 109 )
110 110 addflag('confirm-exit', 'TerminalInteractiveShell.confirm_exit',
111 111 """Set to confirm when you try to exit IPython with an EOF (Control-D
112 112 in Unix, Control-Z/Enter in Windows). By typing 'exit' or 'quit',
113 113 you can force a direct exit without any confirmation.""",
114 114 "Don't prompt the user when exiting."
115 115 )
116 116 addflag('term-title', 'TerminalInteractiveShell.term_title',
117 117 "Enable auto setting the terminal title.",
118 118 "Disable auto setting the terminal title."
119 119 )
120 120 classic_config = Config()
121 121 classic_config.InteractiveShell.cache_size = 0
122 122 classic_config.PlainTextFormatter.pprint = False
123 123 classic_config.InteractiveShell.prompt_in1 = '>>> '
124 124 classic_config.InteractiveShell.prompt_in2 = '... '
125 125 classic_config.InteractiveShell.prompt_out = ''
126 126 classic_config.InteractiveShell.separate_in = ''
127 127 classic_config.InteractiveShell.separate_out = ''
128 128 classic_config.InteractiveShell.separate_out2 = ''
129 129 classic_config.InteractiveShell.colors = 'NoColor'
130 130 classic_config.InteractiveShell.xmode = 'Plain'
131 131
132 132 flags['classic']=(
133 133 classic_config,
134 134 "Gives IPython a similar feel to the classic Python prompt."
135 135 )
136 136 # # log doesn't make so much sense this way anymore
137 137 # paa('--log','-l',
138 138 # action='store_true', dest='InteractiveShell.logstart',
139 139 # help="Start logging to the default log file (./ipython_log.py).")
140 140 #
141 141 # # quick is harder to implement
142 142 flags['quick']=(
143 143 {'TerminalIPythonApp' : {'quick' : True}},
144 144 "Enable quick startup with no config files."
145 145 )
146 146
147 147 flags['i'] = (
148 148 {'TerminalIPythonApp' : {'force_interact' : True}},
149 149 "If running code from the command line, become interactive afterwards."
150 150 )
151 151 flags['pylab'] = (
152 152 {'TerminalIPythonApp' : {'pylab' : 'auto'}},
153 153 """Pre-load matplotlib and numpy for interactive use with
154 154 the default matplotlib backend."""
155 155 )
156 156
157 157 aliases = dict(base_aliases)
158 158 aliases.update(shell_aliases)
159 159
160 160 # it's possible we don't want short aliases for *all* of these:
161 161 aliases.update(dict(
162 162 gui='TerminalIPythonApp.gui',
163 163 pylab='TerminalIPythonApp.pylab',
164 164 ))
165 165
166 166 #-----------------------------------------------------------------------------
167 167 # Main classes and functions
168 168 #-----------------------------------------------------------------------------
169 169
170 170 class TerminalIPythonApp(BaseIPythonApplication, InteractiveShellApp):
171 171 name = u'ipython'
172 172 description = usage.cl_usage
173 173 default_config_file_name = default_config_file_name
174 174 crash_handler_class = IPAppCrashHandler
175 175
176 176 flags = Dict(flags)
177 177 aliases = Dict(aliases)
178 178 classes = [InteractiveShellApp, TerminalInteractiveShell, ProfileDir, PlainTextFormatter]
179 179 subcommands = Dict(dict(
180 180 qtconsole=('IPython.frontend.qt.console.qtconsoleapp.IPythonQtConsoleApp',
181 181 """Launch the IPython Qt Console."""
182 182 ),
183 183 profile = ("IPython.core.profileapp.ProfileApp",
184 184 "Create and manage IPython profiles.")
185 185 ))
186 186
187 187 # *do* autocreate requested profile, but don't create the config file.
188 188 auto_create=Bool(True)
189 189 # configurables
190 190 ignore_old_config=Bool(False, config=True,
191 191 help="Suppress warning messages about legacy config files"
192 192 )
193 193 quick = Bool(False, config=True,
194 194 help="""Start IPython quickly by skipping the loading of config files."""
195 195 )
196 196 def _quick_changed(self, name, old, new):
197 197 if new:
198 198 self.load_config_file = lambda *a, **kw: None
199 199 self.ignore_old_config=True
200 200
201 201 gui = CaselessStrEnum(('qt','wx','gtk'), config=True,
202 202 help="Enable GUI event loop integration ('qt', 'wx', 'gtk')."
203 203 )
204 204 pylab = CaselessStrEnum(['tk', 'qt', 'wx', 'gtk', 'osx', 'auto'],
205 205 config=True,
206 206 help="""Pre-load matplotlib and numpy for interactive use,
207 207 selecting a particular matplotlib backend and loop integration.
208 208 """
209 209 )
210 210 display_banner = Bool(True, config=True,
211 211 help="Whether to display a banner upon starting IPython."
212 212 )
213 213
214 214 # if there is code of files to run from the cmd line, don't interact
215 215 # unless the --i flag (App.force_interact) is true.
216 216 force_interact = Bool(False, config=True,
217 217 help="""If a command or file is given via the command-line,
218 218 e.g. 'ipython foo.py"""
219 219 )
220 220 def _force_interact_changed(self, name, old, new):
221 221 if new:
222 222 self.interact = True
223 223
224 224 def _file_to_run_changed(self, name, old, new):
225 225 if new and not self.force_interact:
226 226 self.interact = False
227 227 _code_to_run_changed = _file_to_run_changed
228 228
229 229 # internal, not-configurable
230 230 interact=Bool(True)
231 231
232 232
233 233 def parse_command_line(self, argv=None):
234 234 """override to allow old '-pylab' flag with deprecation warning"""
235 235 argv = sys.argv[1:] if argv is None else argv
236 236
237 237 try:
238 238 idx = argv.index('-pylab')
239 239 except ValueError:
240 240 # `-pylab` not given, proceed as normal
241 241 pass
242 242 else:
243 243 # deprecated `-pylab` given,
244 244 # warn and transform into current syntax
245 245 argv = list(argv) # copy, don't clobber
246 246 warn.warn("`-pylab` flag has been deprecated.\n"
247 " Use `--pylab` instead, or `pylab=foo` to specify a backend.")
247 " Use `--pylab` instead, or `--pylab=foo` to specify a backend.")
248 248 sub = '--pylab'
249 249 if len(argv) > idx+1:
250 250 # check for gui arg, as in '-pylab qt'
251 251 gui = argv[idx+1]
252 252 if gui in ('wx', 'qt', 'qt4', 'gtk', 'auto'):
253 sub = 'pylab='+gui
253 sub = '--pylab='+gui
254 254 argv.pop(idx+1)
255 255 argv[idx] = sub
256 256
257 257 return super(TerminalIPythonApp, self).parse_command_line(argv)
258 258
259 259 def initialize(self, argv=None):
260 260 """Do actions after construct, but before starting the app."""
261 261 super(TerminalIPythonApp, self).initialize(argv)
262 262 if self.subapp is not None:
263 263 # don't bother initializing further, starting subapp
264 264 return
265 265 if not self.ignore_old_config:
266 266 check_for_old_config(self.ipython_dir)
267 267 # print self.extra_args
268 268 if self.extra_args:
269 269 self.file_to_run = self.extra_args[0]
270 270 # create the shell
271 271 self.init_shell()
272 272 # and draw the banner
273 273 self.init_banner()
274 274 # Now a variety of things that happen after the banner is printed.
275 275 self.init_gui_pylab()
276 276 self.init_extensions()
277 277 self.init_code()
278 278
279 279 def init_shell(self):
280 280 """initialize the InteractiveShell instance"""
281 281 # I am a little hesitant to put these into InteractiveShell itself.
282 282 # But that might be the place for them
283 283 sys.path.insert(0, '')
284 284
285 285 # Create an InteractiveShell instance.
286 286 # shell.display_banner should always be False for the terminal
287 287 # based app, because we call shell.show_banner() by hand below
288 288 # so the banner shows *before* all extension loading stuff.
289 289 self.shell = TerminalInteractiveShell.instance(config=self.config,
290 290 display_banner=False, profile_dir=self.profile_dir,
291 291 ipython_dir=self.ipython_dir)
292 292
293 293 def init_banner(self):
294 294 """optionally display the banner"""
295 295 if self.display_banner and self.interact:
296 296 self.shell.show_banner()
297 297 # Make sure there is a space below the banner.
298 298 if self.log_level <= logging.INFO: print
299 299
300 300
301 301 def init_gui_pylab(self):
302 302 """Enable GUI event loop integration, taking pylab into account."""
303 303 gui = self.gui
304 304
305 305 # Using `pylab` will also require gui activation, though which toolkit
306 306 # to use may be chosen automatically based on mpl configuration.
307 307 if self.pylab:
308 308 activate = self.shell.enable_pylab
309 309 if self.pylab == 'auto':
310 310 gui = None
311 311 else:
312 312 gui = self.pylab
313 313 else:
314 314 # Enable only GUI integration, no pylab
315 315 activate = inputhook.enable_gui
316 316
317 317 if gui or self.pylab:
318 318 try:
319 319 self.log.info("Enabling GUI event loop integration, "
320 320 "toolkit=%s, pylab=%s" % (gui, self.pylab) )
321 321 activate(gui)
322 322 except:
323 323 self.log.warn("Error in enabling GUI event loop integration:")
324 324 self.shell.showtraceback()
325 325
326 326 def start(self):
327 327 if self.subapp is not None:
328 328 return self.subapp.start()
329 329 # perform any prexec steps:
330 330 if self.interact:
331 331 self.log.debug("Starting IPython's mainloop...")
332 332 self.shell.mainloop()
333 333 else:
334 334 self.log.debug("IPython not interactive...")
335 335
336 336
337 337 def load_default_config(ipython_dir=None):
338 338 """Load the default config file from the default ipython_dir.
339 339
340 340 This is useful for embedded shells.
341 341 """
342 342 if ipython_dir is None:
343 343 ipython_dir = get_ipython_dir()
344 344 profile_dir = os.path.join(ipython_dir, 'profile_default')
345 345 cl = PyFileConfigLoader(default_config_file_name, profile_dir)
346 346 try:
347 347 config = cl.load_config()
348 348 except IOError:
349 349 # no config found
350 350 config = Config()
351 351 return config
352 352
353 353
354 354 def launch_new_instance():
355 355 """Create and run a full blown IPython instance"""
356 356 app = TerminalIPythonApp.instance()
357 357 app.initialize()
358 358 app.start()
359 359
360 360
361 361 if __name__ == '__main__':
362 362 launch_new_instance()
363 363
General Comments 0
You need to be logged in to leave comments. Login now