##// END OF EJS Templates
BUG: Make sure that PlainTextFormatter.pprint is given a real bool, not just 0 or 1.
Robert Kern -
Show More
@@ -1,664 +1,664 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 """
13 13
14 14 #-----------------------------------------------------------------------------
15 15 # Copyright (C) 2008-2010 The IPython Development Team
16 16 #
17 17 # Distributed under the terms of the BSD License. The full license is in
18 18 # the file COPYING, distributed as part of this software.
19 19 #-----------------------------------------------------------------------------
20 20
21 21 #-----------------------------------------------------------------------------
22 22 # Imports
23 23 #-----------------------------------------------------------------------------
24 24
25 25 from __future__ import absolute_import
26 26
27 27 import logging
28 28 import os
29 29 import sys
30 30
31 31 from IPython.core import release
32 32 from IPython.core.crashhandler import CrashHandler
33 33 from IPython.core.application import Application, BaseAppConfigLoader
34 34 from IPython.frontend.terminal.interactiveshell import TerminalInteractiveShell
35 35 from IPython.config.loader import (
36 36 Config,
37 37 PyFileConfigLoader
38 38 )
39 39 from IPython.lib import inputhook
40 40 from IPython.utils.path import filefind, get_ipython_dir
41 41 from IPython.core import usage
42 42
43 43 #-----------------------------------------------------------------------------
44 44 # Globals, utilities and helpers
45 45 #-----------------------------------------------------------------------------
46 46
47 47 #: The default config file name for this application.
48 48 default_config_file_name = u'ipython_config.py'
49 49
50 50
51 51 class IPAppConfigLoader(BaseAppConfigLoader):
52 52
53 53 def _add_arguments(self):
54 54 super(IPAppConfigLoader, self)._add_arguments()
55 55 paa = self.parser.add_argument
56 56 paa('-p',
57 57 '--profile', dest='Global.profile', type=unicode,
58 58 help=
59 59 """The string name of the ipython profile to be used. Assume that your
60 60 config file is ipython_config-<name>.py (looks in current dir first,
61 61 then in IPYTHON_DIR). This is a quick way to keep and load multiple
62 62 config files for different tasks, especially if include your basic one
63 63 in your more specialized ones. You can keep a basic
64 64 IPYTHON_DIR/ipython_config.py file and then have other 'profiles' which
65 65 include this one and load extra things for particular tasks.""",
66 66 metavar='Global.profile')
67 67 paa('--config-file',
68 68 dest='Global.config_file', type=unicode,
69 69 help=
70 70 """Set the config file name to override default. Normally IPython
71 71 loads ipython_config.py (from current directory) or
72 72 IPYTHON_DIR/ipython_config.py. If the loading of your config file
73 73 fails, IPython starts with a bare bones configuration (no modules
74 74 loaded at all).""",
75 75 metavar='Global.config_file')
76 76 paa('--autocall',
77 77 dest='InteractiveShell.autocall', type=int,
78 78 help=
79 79 """Make IPython automatically call any callable object even if you
80 80 didn't type explicit parentheses. For example, 'str 43' becomes
81 81 'str(43)' automatically. The value can be '0' to disable the feature,
82 82 '1' for 'smart' autocall, where it is not applied if there are no more
83 83 arguments on the line, and '2' for 'full' autocall, where all callable
84 84 objects are automatically called (even if no arguments are present).
85 85 The default is '1'.""",
86 86 metavar='InteractiveShell.autocall')
87 87 paa('--autoindent',
88 88 action='store_true', dest='InteractiveShell.autoindent',
89 89 help='Turn on autoindenting.')
90 90 paa('--no-autoindent',
91 91 action='store_false', dest='InteractiveShell.autoindent',
92 92 help='Turn off autoindenting.')
93 93 paa('--automagic',
94 94 action='store_true', dest='InteractiveShell.automagic',
95 95 help=
96 96 """Turn on the auto calling of magic commands. Type %%magic at the
97 97 IPython prompt for more information.""")
98 98 paa('--no-automagic',
99 99 action='store_false', dest='InteractiveShell.automagic',
100 100 help='Turn off the auto calling of magic commands.')
101 101 paa('--autoedit-syntax',
102 102 action='store_true', dest='TerminalInteractiveShell.autoedit_syntax',
103 103 help='Turn on auto editing of files with syntax errors.')
104 104 paa('--no-autoedit-syntax',
105 105 action='store_false', dest='TerminalInteractiveShell.autoedit_syntax',
106 106 help='Turn off auto editing of files with syntax errors.')
107 107 paa('--banner',
108 108 action='store_true', dest='Global.display_banner',
109 109 help='Display a banner upon starting IPython.')
110 110 paa('--no-banner',
111 111 action='store_false', dest='Global.display_banner',
112 112 help="Don't display a banner upon starting IPython.")
113 113 paa('--cache-size',
114 114 type=int, dest='InteractiveShell.cache_size',
115 115 help=
116 116 """Set the size of the output cache. The default is 1000, you can
117 117 change it permanently in your config file. Setting it to 0 completely
118 118 disables the caching system, and the minimum value accepted is 20 (if
119 119 you provide a value less than 20, it is reset to 0 and a warning is
120 120 issued). This limit is defined because otherwise you'll spend more
121 121 time re-flushing a too small cache than working""",
122 122 metavar='InteractiveShell.cache_size')
123 123 paa('--classic',
124 124 action='store_true', dest='Global.classic',
125 125 help="Gives IPython a similar feel to the classic Python prompt.")
126 126 paa('--colors',
127 127 type=str, dest='InteractiveShell.colors',
128 128 help="Set the color scheme (NoColor, Linux, and LightBG).",
129 129 metavar='InteractiveShell.colors')
130 130 paa('--color-info',
131 131 action='store_true', dest='InteractiveShell.color_info',
132 132 help=
133 133 """IPython can display information about objects via a set of func-
134 134 tions, and optionally can use colors for this, syntax highlighting
135 135 source code and various other elements. However, because this
136 136 information is passed through a pager (like 'less') and many pagers get
137 137 confused with color codes, this option is off by default. You can test
138 138 it and turn it on permanently in your ipython_config.py file if it
139 139 works for you. Test it and turn it on permanently if it works with
140 140 your system. The magic function %%color_info allows you to toggle this
141 141 inter- actively for testing.""")
142 142 paa('--no-color-info',
143 143 action='store_false', dest='InteractiveShell.color_info',
144 144 help="Disable using colors for info related things.")
145 145 paa('--confirm-exit',
146 146 action='store_true', dest='TerminalInteractiveShell.confirm_exit',
147 147 help=
148 148 """Set to confirm when you try to exit IPython with an EOF (Control-D
149 149 in Unix, Control-Z/Enter in Windows). By typing 'exit', 'quit' or
150 150 '%%Exit', you can force a direct exit without any confirmation.""")
151 151 paa('--no-confirm-exit',
152 152 action='store_false', dest='TerminalInteractiveShell.confirm_exit',
153 153 help="Don't prompt the user when exiting.")
154 154 paa('--deep-reload',
155 155 action='store_true', dest='InteractiveShell.deep_reload',
156 156 help=
157 157 """Enable deep (recursive) reloading by default. IPython can use the
158 158 deep_reload module which reloads changes in modules recursively (it
159 159 replaces the reload() function, so you don't need to change anything to
160 160 use it). deep_reload() forces a full reload of modules whose code may
161 161 have changed, which the default reload() function does not. When
162 162 deep_reload is off, IPython will use the normal reload(), but
163 163 deep_reload will still be available as dreload(). This fea- ture is off
164 164 by default [which means that you have both normal reload() and
165 165 dreload()].""")
166 166 paa('--no-deep-reload',
167 167 action='store_false', dest='InteractiveShell.deep_reload',
168 168 help="Disable deep (recursive) reloading by default.")
169 169 paa('--editor',
170 170 type=str, dest='TerminalInteractiveShell.editor',
171 171 help="Set the editor used by IPython (default to $EDITOR/vi/notepad).",
172 172 metavar='TerminalInteractiveShell.editor')
173 173 paa('--log','-l',
174 174 action='store_true', dest='InteractiveShell.logstart',
175 175 help="Start logging to the default log file (./ipython_log.py).")
176 176 paa('--logfile','-lf',
177 177 type=unicode, dest='InteractiveShell.logfile',
178 178 help="Start logging to logfile with this name.",
179 179 metavar='InteractiveShell.logfile')
180 180 paa('--log-append','-la',
181 181 type=unicode, dest='InteractiveShell.logappend',
182 182 help="Start logging to the given file in append mode.",
183 183 metavar='InteractiveShell.logfile')
184 184 paa('--pdb',
185 185 action='store_true', dest='InteractiveShell.pdb',
186 186 help="Enable auto calling the pdb debugger after every exception.")
187 187 paa('--no-pdb',
188 188 action='store_false', dest='InteractiveShell.pdb',
189 189 help="Disable auto calling the pdb debugger after every exception.")
190 190 paa('--pprint',
191 191 action='store_true', dest='PlainTextFormatter.pprint',
192 192 help="Enable auto pretty printing of results.")
193 193 paa('--no-pprint',
194 194 action='store_false', dest='PlainTextFormatter.pprint',
195 195 help="Disable auto auto pretty printing of results.")
196 196 paa('--prompt-in1','-pi1',
197 197 type=str, dest='InteractiveShell.prompt_in1',
198 198 help=
199 199 """Set the main input prompt ('In [\#]: '). Note that if you are using
200 200 numbered prompts, the number is represented with a '\#' in the string.
201 201 Don't forget to quote strings with spaces embedded in them. Most
202 202 bash-like escapes can be used to customize IPython's prompts, as well
203 203 as a few additional ones which are IPython-spe- cific. All valid
204 204 prompt escapes are described in detail in the Customization section of
205 205 the IPython manual.""",
206 206 metavar='InteractiveShell.prompt_in1')
207 207 paa('--prompt-in2','-pi2',
208 208 type=str, dest='InteractiveShell.prompt_in2',
209 209 help=
210 210 """Set the secondary input prompt (' .\D.: '). Similar to the previous
211 211 option, but used for the continuation prompts. The special sequence
212 212 '\D' is similar to '\#', but with all digits replaced by dots (so you
213 213 can have your continuation prompt aligned with your input prompt).
214 214 Default: ' .\D.: ' (note three spaces at the start for alignment with
215 215 'In [\#]')""",
216 216 metavar='InteractiveShell.prompt_in2')
217 217 paa('--prompt-out','-po',
218 218 type=str, dest='InteractiveShell.prompt_out',
219 219 help="Set the output prompt ('Out[\#]:')",
220 220 metavar='InteractiveShell.prompt_out')
221 221 paa('--quick',
222 222 action='store_true', dest='Global.quick',
223 223 help="Enable quick startup with no config files.")
224 224 paa('--readline',
225 225 action='store_true', dest='InteractiveShell.readline_use',
226 226 help="Enable readline for command line usage.")
227 227 paa('--no-readline',
228 228 action='store_false', dest='InteractiveShell.readline_use',
229 229 help="Disable readline for command line usage.")
230 230 paa('--screen-length','-sl',
231 231 type=int, dest='TerminalInteractiveShell.screen_length',
232 232 help=
233 233 """Number of lines of your screen, used to control printing of very
234 234 long strings. Strings longer than this number of lines will be sent
235 235 through a pager instead of directly printed. The default value for
236 236 this is 0, which means IPython will auto-detect your screen size every
237 237 time it needs to print certain potentially long strings (this doesn't
238 238 change the behavior of the 'print' keyword, it's only triggered
239 239 internally). If for some reason this isn't working well (it needs
240 240 curses support), specify it yourself. Otherwise don't change the
241 241 default.""",
242 242 metavar='TerminalInteractiveShell.screen_length')
243 243 paa('--separate-in','-si',
244 244 type=str, dest='InteractiveShell.separate_in',
245 245 help="Separator before input prompts. Default '\\n'.",
246 246 metavar='InteractiveShell.separate_in')
247 247 paa('--separate-out','-so',
248 248 type=str, dest='InteractiveShell.separate_out',
249 249 help="Separator before output prompts. Default 0 (nothing).",
250 250 metavar='InteractiveShell.separate_out')
251 251 paa('--separate-out2','-so2',
252 252 type=str, dest='InteractiveShell.separate_out2',
253 253 help="Separator after output prompts. Default 0 (nonight).",
254 254 metavar='InteractiveShell.separate_out2')
255 255 paa('--no-sep',
256 256 action='store_true', dest='Global.nosep',
257 257 help="Eliminate all spacing between prompts.")
258 258 paa('--term-title',
259 259 action='store_true', dest='TerminalInteractiveShell.term_title',
260 260 help="Enable auto setting the terminal title.")
261 261 paa('--no-term-title',
262 262 action='store_false', dest='TerminalInteractiveShell.term_title',
263 263 help="Disable auto setting the terminal title.")
264 264 paa('--xmode',
265 265 type=str, dest='InteractiveShell.xmode',
266 266 help=
267 267 """Exception reporting mode ('Plain','Context','Verbose'). Plain:
268 268 similar to python's normal traceback printing. Context: prints 5 lines
269 269 of context source code around each line in the traceback. Verbose:
270 270 similar to Context, but additionally prints the variables currently
271 271 visible where the exception happened (shortening their strings if too
272 272 long). This can potentially be very slow, if you happen to have a huge
273 273 data structure whose string representation is complex to compute.
274 274 Your computer may appear to freeze for a while with cpu usage at 100%%.
275 275 If this occurs, you can cancel the traceback with Ctrl-C (maybe hitting
276 276 it more than once).
277 277 """,
278 278 metavar='InteractiveShell.xmode')
279 279 paa('--ext',
280 280 type=str, dest='Global.extra_extension',
281 281 help="The dotted module name of an IPython extension to load.",
282 282 metavar='Global.extra_extension')
283 283 paa('-c',
284 284 type=str, dest='Global.code_to_run',
285 285 help="Execute the given command string.",
286 286 metavar='Global.code_to_run')
287 287 paa('-i',
288 288 action='store_true', dest='Global.force_interact',
289 289 help=
290 290 "If running code from the command line, become interactive afterwards.")
291 291
292 292 # Options to start with GUI control enabled from the beginning
293 293 paa('--gui',
294 294 type=str, dest='Global.gui',
295 295 help="Enable GUI event loop integration ('qt', 'wx', 'gtk').",
296 296 metavar='gui-mode')
297 297 paa('--pylab','-pylab',
298 298 type=str, dest='Global.pylab',
299 299 nargs='?', const='auto', metavar='gui-mode',
300 300 help="Pre-load matplotlib and numpy for interactive use. "+
301 301 "If no value is given, the gui backend is matplotlib's, else use "+
302 302 "one of: ['tk', 'qt', 'wx', 'gtk', 'osx'].")
303 303
304 304 # Legacy GUI options. Leave them in for backwards compatibility, but the
305 305 # 'thread' names are really a misnomer now.
306 306 paa('--wthread', '-wthread',
307 307 action='store_true', dest='Global.wthread',
308 308 help=
309 309 """Enable wxPython event loop integration. (DEPRECATED, use --gui wx)""")
310 310 paa('--q4thread', '--qthread', '-q4thread', '-qthread',
311 311 action='store_true', dest='Global.q4thread',
312 312 help=
313 313 """Enable Qt4 event loop integration. Qt3 is no longer supported.
314 314 (DEPRECATED, use --gui qt)""")
315 315 paa('--gthread', '-gthread',
316 316 action='store_true', dest='Global.gthread',
317 317 help=
318 318 """Enable GTK event loop integration. (DEPRECATED, use --gui gtk)""")
319 319
320 320
321 321 #-----------------------------------------------------------------------------
322 322 # Crash handler for this application
323 323 #-----------------------------------------------------------------------------
324 324
325 325 _message_template = """\
326 326 Oops, $self.app_name crashed. We do our best to make it stable, but...
327 327
328 328 A crash report was automatically generated with the following information:
329 329 - A verbatim copy of the crash traceback.
330 330 - A copy of your input history during this session.
331 331 - Data on your current $self.app_name configuration.
332 332
333 333 It was left in the file named:
334 334 \t'$self.crash_report_fname'
335 335 If you can email this file to the developers, the information in it will help
336 336 them in understanding and correcting the problem.
337 337
338 338 You can mail it to: $self.contact_name at $self.contact_email
339 339 with the subject '$self.app_name Crash Report'.
340 340
341 341 If you want to do it now, the following command will work (under Unix):
342 342 mail -s '$self.app_name Crash Report' $self.contact_email < $self.crash_report_fname
343 343
344 344 To ensure accurate tracking of this issue, please file a report about it at:
345 345 $self.bug_tracker
346 346 """
347 347
348 348 class IPAppCrashHandler(CrashHandler):
349 349 """sys.excepthook for IPython itself, leaves a detailed report on disk."""
350 350
351 351 message_template = _message_template
352 352
353 353 def __init__(self, app):
354 354 contact_name = release.authors['Fernando'][0]
355 355 contact_email = release.authors['Fernando'][1]
356 356 bug_tracker = 'http://github.com/ipython/ipython/issues'
357 357 super(IPAppCrashHandler,self).__init__(
358 358 app, contact_name, contact_email, bug_tracker
359 359 )
360 360
361 361 def make_report(self,traceback):
362 362 """Return a string containing a crash report."""
363 363
364 364 sec_sep = self.section_sep
365 365 # Start with parent report
366 366 report = [super(IPAppCrashHandler, self).make_report(traceback)]
367 367 # Add interactive-specific info we may have
368 368 rpt_add = report.append
369 369 try:
370 370 rpt_add(sec_sep+"History of session input:")
371 371 for line in self.app.shell.user_ns['_ih']:
372 372 rpt_add(line)
373 373 rpt_add('\n*** Last line of input (may not be in above history):\n')
374 374 rpt_add(self.app.shell._last_input_line+'\n')
375 375 except:
376 376 pass
377 377
378 378 return ''.join(report)
379 379
380 380
381 381 #-----------------------------------------------------------------------------
382 382 # Main classes and functions
383 383 #-----------------------------------------------------------------------------
384 384
385 385 class IPythonApp(Application):
386 386 name = u'ipython'
387 387 #: argparse formats better the 'usage' than the 'description' field
388 388 description = None
389 389 usage = usage.cl_usage
390 390 command_line_loader = IPAppConfigLoader
391 391 default_config_file_name = default_config_file_name
392 392 crash_handler_class = IPAppCrashHandler
393 393
394 394 def create_default_config(self):
395 395 super(IPythonApp, self).create_default_config()
396 396 # Eliminate multiple lookups
397 397 Global = self.default_config.Global
398 398
399 399 # Set all default values
400 400 Global.display_banner = True
401 401
402 402 # If the -c flag is given or a file is given to run at the cmd line
403 403 # like "ipython foo.py", normally we exit without starting the main
404 404 # loop. The force_interact config variable allows a user to override
405 405 # this and interact. It is also set by the -i cmd line flag, just
406 406 # like Python.
407 407 Global.force_interact = False
408 408
409 409 # By default always interact by starting the IPython mainloop.
410 410 Global.interact = True
411 411
412 412 # No GUI integration by default
413 413 Global.gui = False
414 414 # Pylab off by default
415 415 Global.pylab = False
416 416
417 417 # Deprecated versions of gui support that used threading, we support
418 418 # them just for bacwards compatibility as an alternate spelling for
419 419 # '--gui X'
420 420 Global.qthread = False
421 421 Global.q4thread = False
422 422 Global.wthread = False
423 423 Global.gthread = False
424 424
425 425 def load_file_config(self):
426 426 if hasattr(self.command_line_config.Global, 'quick'):
427 427 if self.command_line_config.Global.quick:
428 428 self.file_config = Config()
429 429 return
430 430 super(IPythonApp, self).load_file_config()
431 431
432 432 def post_load_file_config(self):
433 433 if hasattr(self.command_line_config.Global, 'extra_extension'):
434 434 if not hasattr(self.file_config.Global, 'extensions'):
435 435 self.file_config.Global.extensions = []
436 436 self.file_config.Global.extensions.append(
437 437 self.command_line_config.Global.extra_extension)
438 438 del self.command_line_config.Global.extra_extension
439 439
440 440 def pre_construct(self):
441 441 config = self.master_config
442 442
443 443 if hasattr(config.Global, 'classic'):
444 444 if config.Global.classic:
445 445 config.InteractiveShell.cache_size = 0
446 config.PlainTextFormatter.pprint = 0
446 config.PlainTextFormatter.pprint = False
447 447 config.InteractiveShell.prompt_in1 = '>>> '
448 448 config.InteractiveShell.prompt_in2 = '... '
449 449 config.InteractiveShell.prompt_out = ''
450 450 config.InteractiveShell.separate_in = \
451 451 config.InteractiveShell.separate_out = \
452 452 config.InteractiveShell.separate_out2 = ''
453 453 config.InteractiveShell.colors = 'NoColor'
454 454 config.InteractiveShell.xmode = 'Plain'
455 455
456 456 if hasattr(config.Global, 'nosep'):
457 457 if config.Global.nosep:
458 458 config.InteractiveShell.separate_in = \
459 459 config.InteractiveShell.separate_out = \
460 460 config.InteractiveShell.separate_out2 = ''
461 461
462 462 # if there is code of files to run from the cmd line, don't interact
463 463 # unless the -i flag (Global.force_interact) is true.
464 464 code_to_run = config.Global.get('code_to_run','')
465 465 file_to_run = False
466 466 if self.extra_args and self.extra_args[0]:
467 467 file_to_run = True
468 468 if file_to_run or code_to_run:
469 469 if not config.Global.force_interact:
470 470 config.Global.interact = False
471 471
472 472 def construct(self):
473 473 # I am a little hesitant to put these into InteractiveShell itself.
474 474 # But that might be the place for them
475 475 sys.path.insert(0, '')
476 476
477 477 # Create an InteractiveShell instance.
478 478 self.shell = TerminalInteractiveShell.instance(config=self.master_config)
479 479
480 480 def post_construct(self):
481 481 """Do actions after construct, but before starting the app."""
482 482 config = self.master_config
483 483
484 484 # shell.display_banner should always be False for the terminal
485 485 # based app, because we call shell.show_banner() by hand below
486 486 # so the banner shows *before* all extension loading stuff.
487 487 self.shell.display_banner = False
488 488 if config.Global.display_banner and \
489 489 config.Global.interact:
490 490 self.shell.show_banner()
491 491
492 492 # Make sure there is a space below the banner.
493 493 if self.log_level <= logging.INFO: print
494 494
495 495 # Now a variety of things that happen after the banner is printed.
496 496 self._enable_gui_pylab()
497 497 self._load_extensions()
498 498 self._run_exec_lines()
499 499 self._run_exec_files()
500 500 self._run_cmd_line_code()
501 501
502 502 def _enable_gui_pylab(self):
503 503 """Enable GUI event loop integration, taking pylab into account."""
504 504 Global = self.master_config.Global
505 505
506 506 # Select which gui to use
507 507 if Global.gui:
508 508 gui = Global.gui
509 509 # The following are deprecated, but there's likely to be a lot of use
510 510 # of this form out there, so we might as well support it for now. But
511 511 # the --gui option above takes precedence.
512 512 elif Global.wthread:
513 513 gui = inputhook.GUI_WX
514 514 elif Global.qthread:
515 515 gui = inputhook.GUI_QT
516 516 elif Global.gthread:
517 517 gui = inputhook.GUI_GTK
518 518 else:
519 519 gui = None
520 520
521 521 # Using --pylab will also require gui activation, though which toolkit
522 522 # to use may be chosen automatically based on mpl configuration.
523 523 if Global.pylab:
524 524 activate = self.shell.enable_pylab
525 525 if Global.pylab == 'auto':
526 526 gui = None
527 527 else:
528 528 gui = Global.pylab
529 529 else:
530 530 # Enable only GUI integration, no pylab
531 531 activate = inputhook.enable_gui
532 532
533 533 if gui or Global.pylab:
534 534 try:
535 535 self.log.info("Enabling GUI event loop integration, "
536 536 "toolkit=%s, pylab=%s" % (gui, Global.pylab) )
537 537 activate(gui)
538 538 except:
539 539 self.log.warn("Error in enabling GUI event loop integration:")
540 540 self.shell.showtraceback()
541 541
542 542 def _load_extensions(self):
543 543 """Load all IPython extensions in Global.extensions.
544 544
545 545 This uses the :meth:`ExtensionManager.load_extensions` to load all
546 546 the extensions listed in ``self.master_config.Global.extensions``.
547 547 """
548 548 try:
549 549 if hasattr(self.master_config.Global, 'extensions'):
550 550 self.log.debug("Loading IPython extensions...")
551 551 extensions = self.master_config.Global.extensions
552 552 for ext in extensions:
553 553 try:
554 554 self.log.info("Loading IPython extension: %s" % ext)
555 555 self.shell.extension_manager.load_extension(ext)
556 556 except:
557 557 self.log.warn("Error in loading extension: %s" % ext)
558 558 self.shell.showtraceback()
559 559 except:
560 560 self.log.warn("Unknown error in loading extensions:")
561 561 self.shell.showtraceback()
562 562
563 563 def _run_exec_lines(self):
564 564 """Run lines of code in Global.exec_lines in the user's namespace."""
565 565 try:
566 566 if hasattr(self.master_config.Global, 'exec_lines'):
567 567 self.log.debug("Running code from Global.exec_lines...")
568 568 exec_lines = self.master_config.Global.exec_lines
569 569 for line in exec_lines:
570 570 try:
571 571 self.log.info("Running code in user namespace: %s" %
572 572 line)
573 573 self.shell.run_cell(line, store_history=False)
574 574 except:
575 575 self.log.warn("Error in executing line in user "
576 576 "namespace: %s" % line)
577 577 self.shell.showtraceback()
578 578 except:
579 579 self.log.warn("Unknown error in handling Global.exec_lines:")
580 580 self.shell.showtraceback()
581 581
582 582 def _exec_file(self, fname):
583 583 full_filename = filefind(fname, [u'.', self.ipython_dir])
584 584 if os.path.isfile(full_filename):
585 585 if full_filename.endswith(u'.py'):
586 586 self.log.info("Running file in user namespace: %s" %
587 587 full_filename)
588 588 # Ensure that __file__ is always defined to match Python behavior
589 589 self.shell.user_ns['__file__'] = fname
590 590 try:
591 591 self.shell.safe_execfile(full_filename, self.shell.user_ns)
592 592 finally:
593 593 del self.shell.user_ns['__file__']
594 594 elif full_filename.endswith('.ipy'):
595 595 self.log.info("Running file in user namespace: %s" %
596 596 full_filename)
597 597 self.shell.safe_execfile_ipy(full_filename)
598 598 else:
599 599 self.log.warn("File does not have a .py or .ipy extension: <%s>"
600 600 % full_filename)
601 601 def _run_exec_files(self):
602 602 try:
603 603 if hasattr(self.master_config.Global, 'exec_files'):
604 604 self.log.debug("Running files in Global.exec_files...")
605 605 exec_files = self.master_config.Global.exec_files
606 606 for fname in exec_files:
607 607 self._exec_file(fname)
608 608 except:
609 609 self.log.warn("Unknown error in handling Global.exec_files:")
610 610 self.shell.showtraceback()
611 611
612 612 def _run_cmd_line_code(self):
613 613 if hasattr(self.master_config.Global, 'code_to_run'):
614 614 line = self.master_config.Global.code_to_run
615 615 try:
616 616 self.log.info("Running code given at command line (-c): %s" %
617 617 line)
618 618 self.shell.run_cell(line, store_history=False)
619 619 except:
620 620 self.log.warn("Error in executing line in user namespace: %s" %
621 621 line)
622 622 self.shell.showtraceback()
623 623 return
624 624 # Like Python itself, ignore the second if the first of these is present
625 625 try:
626 626 fname = self.extra_args[0]
627 627 except:
628 628 pass
629 629 else:
630 630 try:
631 631 self._exec_file(fname)
632 632 except:
633 633 self.log.warn("Error in executing file in user namespace: %s" %
634 634 fname)
635 635 self.shell.showtraceback()
636 636
637 637 def start_app(self):
638 638 if self.master_config.Global.interact:
639 639 self.log.debug("Starting IPython's mainloop...")
640 640 self.shell.mainloop()
641 641 else:
642 642 self.log.debug("IPython not interactive, start_app is no-op...")
643 643
644 644
645 645 def load_default_config(ipython_dir=None):
646 646 """Load the default config file from the default ipython_dir.
647 647
648 648 This is useful for embedded shells.
649 649 """
650 650 if ipython_dir is None:
651 651 ipython_dir = get_ipython_dir()
652 652 cl = PyFileConfigLoader(default_config_file_name, ipython_dir)
653 653 config = cl.load_config()
654 654 return config
655 655
656 656
657 657 def launch_new_instance():
658 658 """Create and run a full blown IPython instance"""
659 659 app = IPythonApp()
660 660 app.start()
661 661
662 662
663 663 if __name__ == '__main__':
664 664 launch_new_instance()
General Comments 0
You need to be logged in to leave comments. Login now