##// END OF EJS Templates
Reenabled -wthread/-q4thread/-gthread and added warning for -pylab....
Brian Granger -
Show More
@@ -1,490 +1,543 b''
1 1 #!/usr/bin/env python
2 2 # encoding: utf-8
3 3 """
4 4 The main IPython application object
5 5
6 6 Authors:
7 7
8 8 * Brian Granger
9 9 * Fernando Perez
10 10
11 11 Notes
12 12 -----
13 13 """
14 14
15 15 #-----------------------------------------------------------------------------
16 16 # Copyright (C) 2008-2009 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 import logging
27 27 import os
28 28 import sys
29 29 import warnings
30 30
31 31 from IPython.core.application import Application, IPythonArgParseConfigLoader
32 32 from IPython.core import release
33 33 from IPython.core.iplib import InteractiveShell
34 34 from IPython.config.loader import (
35 35 NoConfigDefault,
36 36 Config,
37 37 ConfigError,
38 38 PyFileConfigLoader
39 39 )
40 40
41 from IPython.lib import inputhook
42
41 43 from IPython.utils.ipstruct import Struct
42 44 from IPython.utils.genutils import filefind, get_ipython_dir
43 45
44 46 #-----------------------------------------------------------------------------
45 47 # Utilities and helpers
46 48 #-----------------------------------------------------------------------------
47 49
48 50
49 51 ipython_desc = """
50 52 A Python shell with automatic history (input and output), dynamic object
51 53 introspection, easier configuration, command completion, access to the system
52 54 shell and more.
53 55 """
54 56
55 def threaded_shell_warning():
57 def pylab_warning():
56 58 msg = """
57 59
58 The IPython threaded shells and their associated command line
59 arguments (pylab/wthread/gthread/qthread/q4thread) have been
60 deprecated. See the %gui magic for information on the new interface.
60 IPython's -pylab mode has been disabled until matplotlib supports this version
61 of IPython. This version of IPython has greatly improved GUI integration that
62 matplotlib will soon be able to take advantage of. This will eventually
63 result in greater stability and a richer API for matplotlib under IPython.
64 However during this transition, you will either need to use an older version
65 of IPython, or do the following to use matplotlib interactively::
66
67 import matplotlib
68 matplotlib.interactive(True)
69 matplotlib.use('wxagg') # adjust for your backend
70 %gui -a wx # adjust for your GUI
71 from matplotlib import pyplot as plt
72
73 See the %gui magic for information on the new interface.
61 74 """
62 75 warnings.warn(msg, category=DeprecationWarning, stacklevel=1)
63 76
64 77
65 78 #-----------------------------------------------------------------------------
66 79 # Main classes and functions
67 80 #-----------------------------------------------------------------------------
68 81
69 82 cl_args = (
70 83 (('-autocall',), dict(
71 84 type=int, dest='InteractiveShell.autocall', default=NoConfigDefault,
72 85 help='Set the autocall value (0,1,2).',
73 86 metavar='InteractiveShell.autocall')
74 87 ),
75 88 (('-autoindent',), dict(
76 89 action='store_true', dest='InteractiveShell.autoindent', default=NoConfigDefault,
77 90 help='Turn on autoindenting.')
78 91 ),
79 92 (('-noautoindent',), dict(
80 93 action='store_false', dest='InteractiveShell.autoindent', default=NoConfigDefault,
81 94 help='Turn off autoindenting.')
82 95 ),
83 96 (('-automagic',), dict(
84 97 action='store_true', dest='InteractiveShell.automagic', default=NoConfigDefault,
85 98 help='Turn on the auto calling of magic commands.')
86 99 ),
87 100 (('-noautomagic',), dict(
88 101 action='store_false', dest='InteractiveShell.automagic', default=NoConfigDefault,
89 102 help='Turn off the auto calling of magic commands.')
90 103 ),
91 104 (('-autoedit_syntax',), dict(
92 105 action='store_true', dest='InteractiveShell.autoedit_syntax', default=NoConfigDefault,
93 106 help='Turn on auto editing of files with syntax errors.')
94 107 ),
95 108 (('-noautoedit_syntax',), dict(
96 109 action='store_false', dest='InteractiveShell.autoedit_syntax', default=NoConfigDefault,
97 110 help='Turn off auto editing of files with syntax errors.')
98 111 ),
99 112 (('-banner',), dict(
100 113 action='store_true', dest='Global.display_banner', default=NoConfigDefault,
101 114 help='Display a banner upon starting IPython.')
102 115 ),
103 116 (('-nobanner',), dict(
104 117 action='store_false', dest='Global.display_banner', default=NoConfigDefault,
105 118 help="Don't display a banner upon starting IPython.")
106 119 ),
107 120 (('-cache_size',), dict(
108 121 type=int, dest='InteractiveShell.cache_size', default=NoConfigDefault,
109 122 help="Set the size of the output cache.",
110 123 metavar='InteractiveShell.cache_size')
111 124 ),
112 125 (('-classic',), dict(
113 126 action='store_true', dest='Global.classic', default=NoConfigDefault,
114 127 help="Gives IPython a similar feel to the classic Python prompt.")
115 128 ),
116 129 (('-colors',), dict(
117 130 type=str, dest='InteractiveShell.colors', default=NoConfigDefault,
118 131 help="Set the color scheme (NoColor, Linux, and LightBG).",
119 132 metavar='InteractiveShell.colors')
120 133 ),
121 134 (('-color_info',), dict(
122 135 action='store_true', dest='InteractiveShell.color_info', default=NoConfigDefault,
123 136 help="Enable using colors for info related things.")
124 137 ),
125 138 (('-nocolor_info',), dict(
126 139 action='store_false', dest='InteractiveShell.color_info', default=NoConfigDefault,
127 140 help="Disable using colors for info related things.")
128 141 ),
129 142 (('-confirm_exit',), dict(
130 143 action='store_true', dest='InteractiveShell.confirm_exit', default=NoConfigDefault,
131 144 help="Prompt the user when existing.")
132 145 ),
133 146 (('-noconfirm_exit',), dict(
134 147 action='store_false', dest='InteractiveShell.confirm_exit', default=NoConfigDefault,
135 148 help="Don't prompt the user when existing.")
136 149 ),
137 150 (('-deep_reload',), dict(
138 151 action='store_true', dest='InteractiveShell.deep_reload', default=NoConfigDefault,
139 152 help="Enable deep (recursive) reloading by default.")
140 153 ),
141 154 (('-nodeep_reload',), dict(
142 155 action='store_false', dest='InteractiveShell.deep_reload', default=NoConfigDefault,
143 156 help="Disable deep (recursive) reloading by default.")
144 157 ),
145 158 (('-editor',), dict(
146 159 type=str, dest='InteractiveShell.editor', default=NoConfigDefault,
147 160 help="Set the editor used by IPython (default to $EDITOR/vi/notepad).",
148 161 metavar='InteractiveShell.editor')
149 162 ),
150 163 (('-log','-l'), dict(
151 164 action='store_true', dest='InteractiveShell.logstart', default=NoConfigDefault,
152 165 help="Start logging to the default file (./ipython_log.py).")
153 166 ),
154 167 (('-logfile','-lf'), dict(
155 168 type=str, dest='InteractiveShell.logfile', default=NoConfigDefault,
156 169 help="Specify the name of your logfile.",
157 170 metavar='InteractiveShell.logfile')
158 171 ),
159 172 (('-logplay','-lp'), dict(
160 173 type=str, dest='InteractiveShell.logplay', default=NoConfigDefault,
161 174 help="Re-play a log file and then append to it.",
162 175 metavar='InteractiveShell.logplay')
163 176 ),
164 177 (('-pdb',), dict(
165 178 action='store_true', dest='InteractiveShell.pdb', default=NoConfigDefault,
166 179 help="Enable auto calling the pdb debugger after every exception.")
167 180 ),
168 181 (('-nopdb',), dict(
169 182 action='store_false', dest='InteractiveShell.pdb', default=NoConfigDefault,
170 183 help="Disable auto calling the pdb debugger after every exception.")
171 184 ),
172 185 (('-pprint',), dict(
173 186 action='store_true', dest='InteractiveShell.pprint', default=NoConfigDefault,
174 187 help="Enable auto pretty printing of results.")
175 188 ),
176 189 (('-nopprint',), dict(
177 190 action='store_false', dest='InteractiveShell.pprint', default=NoConfigDefault,
178 191 help="Disable auto auto pretty printing of results.")
179 192 ),
180 193 (('-prompt_in1','-pi1'), dict(
181 194 type=str, dest='InteractiveShell.prompt_in1', default=NoConfigDefault,
182 195 help="Set the main input prompt ('In [\#]: ')",
183 196 metavar='InteractiveShell.prompt_in1')
184 197 ),
185 198 (('-prompt_in2','-pi2'), dict(
186 199 type=str, dest='InteractiveShell.prompt_in2', default=NoConfigDefault,
187 200 help="Set the secondary input prompt (' .\D.: ')",
188 201 metavar='InteractiveShell.prompt_in2')
189 202 ),
190 203 (('-prompt_out','-po'), dict(
191 204 type=str, dest='InteractiveShell.prompt_out', default=NoConfigDefault,
192 205 help="Set the output prompt ('Out[\#]:')",
193 206 metavar='InteractiveShell.prompt_out')
194 207 ),
195 208 (('-quick',), dict(
196 209 action='store_true', dest='Global.quick', default=NoConfigDefault,
197 210 help="Enable quick startup with no config files.")
198 211 ),
199 212 (('-readline',), dict(
200 213 action='store_true', dest='InteractiveShell.readline_use', default=NoConfigDefault,
201 214 help="Enable readline for command line usage.")
202 215 ),
203 216 (('-noreadline',), dict(
204 217 action='store_false', dest='InteractiveShell.readline_use', default=NoConfigDefault,
205 218 help="Disable readline for command line usage.")
206 219 ),
207 220 (('-screen_length','-sl'), dict(
208 221 type=int, dest='InteractiveShell.screen_length', default=NoConfigDefault,
209 222 help='Number of lines on screen, used to control printing of long strings.',
210 223 metavar='InteractiveShell.screen_length')
211 224 ),
212 225 (('-separate_in','-si'), dict(
213 226 type=str, dest='InteractiveShell.separate_in', default=NoConfigDefault,
214 227 help="Separator before input prompts. Default '\n'.",
215 228 metavar='InteractiveShell.separate_in')
216 229 ),
217 230 (('-separate_out','-so'), dict(
218 231 type=str, dest='InteractiveShell.separate_out', default=NoConfigDefault,
219 232 help="Separator before output prompts. Default 0 (nothing).",
220 233 metavar='InteractiveShell.separate_out')
221 234 ),
222 235 (('-separate_out2','-so2'), dict(
223 236 type=str, dest='InteractiveShell.separate_out2', default=NoConfigDefault,
224 237 help="Separator after output prompts. Default 0 (nonight).",
225 238 metavar='InteractiveShell.separate_out2')
226 239 ),
227 240 (('-nosep',), dict(
228 241 action='store_true', dest='Global.nosep', default=NoConfigDefault,
229 242 help="Eliminate all spacing between prompts.")
230 243 ),
231 244 (('-term_title',), dict(
232 245 action='store_true', dest='InteractiveShell.term_title', default=NoConfigDefault,
233 246 help="Enable auto setting the terminal title.")
234 247 ),
235 248 (('-noterm_title',), dict(
236 249 action='store_false', dest='InteractiveShell.term_title', default=NoConfigDefault,
237 250 help="Disable auto setting the terminal title.")
238 251 ),
239 252 (('-xmode',), dict(
240 253 type=str, dest='InteractiveShell.xmode', default=NoConfigDefault,
241 254 help="Exception mode ('Plain','Context','Verbose')",
242 255 metavar='InteractiveShell.xmode')
243 256 ),
244 257 (('-ext',), dict(
245 258 type=str, dest='Global.extra_extension', default=NoConfigDefault,
246 259 help="The dotted module name of an IPython extension to load.",
247 260 metavar='Global.extra_extension')
248 261 ),
249 262 (('-c',), dict(
250 263 type=str, dest='Global.code_to_run', default=NoConfigDefault,
251 264 help="Execute the given command string.",
252 265 metavar='Global.code_to_run')
253 266 ),
254 267 (('-i',), dict(
255 268 action='store_true', dest='Global.force_interact', default=NoConfigDefault,
256 269 help="If running code from the command line, become interactive afterwards.")
257 270 ),
258 # These are only here to get the proper deprecation warnings
259 (('-pylab','-wthread','-qthread','-q4thread','-gthread'), dict(
260 action='store_true', dest='Global.threaded_shell', default=NoConfigDefault,
261 help="These command line flags are deprecated, see the 'gui' magic.")
271 (('-wthread',), dict(
272 action='store_true', dest='Global.wthread', default=NoConfigDefault,
273 help="Enable wxPython event loop integration.")
274 ),
275 (('-q4thread','-qthread'), dict(
276 action='store_true', dest='Global.q4thread', default=NoConfigDefault,
277 help="Enable Qt4 event loop integration. Qt3 is no longer supported.")
262 278 ),
279 (('-gthread',), dict(
280 action='store_true', dest='Global.gthread', default=NoConfigDefault,
281 help="Enable GTK event loop integration.")
282 ),
283 # # These are only here to get the proper deprecation warnings
284 (('-pylab',), dict(
285 action='store_true', dest='Global.pylab', default=NoConfigDefault,
286 help="Disabled. Pylab has been disabled until matplotlib supports this version of IPython.")
287 )
263 288 )
264 289
265 290
266 291 class IPythonAppCLConfigLoader(IPythonArgParseConfigLoader):
267 292
268 293 arguments = cl_args
269 294
270 295
271 296 _default_config_file_name = 'ipython_config.py'
272 297
273 298 class IPythonApp(Application):
274 299 name = 'ipython'
275 300 config_file_name = _default_config_file_name
276 301
277 302 def create_default_config(self):
278 303 super(IPythonApp, self).create_default_config()
279 304 self.default_config.Global.display_banner = True
280 305
281 306 # If the -c flag is given or a file is given to run at the cmd line
282 307 # like "ipython foo.py", normally we exit without starting the main
283 308 # loop. The force_interact config variable allows a user to override
284 309 # this and interact. It is also set by the -i cmd line flag, just
285 310 # like Python.
286 311 self.default_config.Global.force_interact = False
312
287 313 # By default always interact by starting the IPython mainloop.
288 314 self.default_config.Global.interact = True
315
289 316 # Let the parent class set the default, but each time log_level
290 317 # changes from config, we need to update self.log_level as that is
291 318 # what updates the actual log level in self.log.
292 319 self.default_config.Global.log_level = self.log_level
293 320
321 # No GUI integration by default
322 self.default_config.Global.wthread = False
323 self.default_config.Global.q4thread = False
324 self.default_config.Global.gthread = False
325
294 326 def create_command_line_config(self):
295 327 """Create and return a command line config loader."""
296 328 return IPythonAppCLConfigLoader(
297 329 description=ipython_desc,
298 330 version=release.version)
299 331
300 332 def post_load_command_line_config(self):
301 333 """Do actions after loading cl config."""
302 334 clc = self.command_line_config
303 335
304 336 # Display the deprecation warnings about threaded shells
305 if hasattr(clc.Global, 'threaded_shell'):
306 threaded_shell_warning()
307 del clc.Global['threaded_shell']
337 if hasattr(clc.Global, 'pylab'):
338 pylab_warning()
339 del clc.Global['pylab']
308 340
309 341 def load_file_config(self):
310 342 if hasattr(self.command_line_config.Global, 'quick'):
311 343 if self.command_line_config.Global.quick:
312 344 self.file_config = Config()
313 345 return
314 346 super(IPythonApp, self).load_file_config()
315 347
316 348 def post_load_file_config(self):
317 349 if hasattr(self.command_line_config.Global, 'extra_extension'):
318 350 if not hasattr(self.file_config.Global, 'extensions'):
319 351 self.file_config.Global.extensions = []
320 352 self.file_config.Global.extensions.append(
321 353 self.command_line_config.Global.extra_extension)
322 354 del self.command_line_config.Global.extra_extension
323 355
324 356 def pre_construct(self):
325 357 config = self.master_config
326 358
327 359 if hasattr(config.Global, 'classic'):
328 360 if config.Global.classic:
329 361 config.InteractiveShell.cache_size = 0
330 362 config.InteractiveShell.pprint = 0
331 363 config.InteractiveShell.prompt_in1 = '>>> '
332 364 config.InteractiveShell.prompt_in2 = '... '
333 365 config.InteractiveShell.prompt_out = ''
334 366 config.InteractiveShell.separate_in = \
335 367 config.InteractiveShell.separate_out = \
336 368 config.InteractiveShell.separate_out2 = ''
337 369 config.InteractiveShell.colors = 'NoColor'
338 370 config.InteractiveShell.xmode = 'Plain'
339 371
340 372 if hasattr(config.Global, 'nosep'):
341 373 if config.Global.nosep:
342 374 config.InteractiveShell.separate_in = \
343 375 config.InteractiveShell.separate_out = \
344 376 config.InteractiveShell.separate_out2 = ''
345 377
346 378 # if there is code of files to run from the cmd line, don't interact
347 379 # unless the -i flag (Global.force_interact) is true.
348 380 code_to_run = config.Global.get('code_to_run','')
349 381 file_to_run = False
350 382 if len(self.extra_args)>=1:
351 383 if self.extra_args[0]:
352 384 file_to_run = True
353 385 if file_to_run or code_to_run:
354 386 if not config.Global.force_interact:
355 387 config.Global.interact = False
356 388
357 389 def construct(self):
358 390 # I am a little hesitant to put these into InteractiveShell itself.
359 391 # But that might be the place for them
360 392 sys.path.insert(0, '')
361 393
362 394 # Create an InteractiveShell instance
363 395 self.shell = InteractiveShell(
364 396 parent=None,
365 397 config=self.master_config
366 398 )
367 399
368 400 def post_construct(self):
369 401 """Do actions after construct, but before starting the app."""
402 config = self.master_config
403
370 404 # shell.display_banner should always be False for the terminal
371 405 # based app, because we call shell.show_banner() by hand below
372 406 # so the banner shows *before* all extension loading stuff.
373 407 self.shell.display_banner = False
374 408
375 if self.master_config.Global.display_banner and \
376 self.master_config.Global.interact:
409 if config.Global.display_banner and \
410 config.Global.interact:
377 411 self.shell.show_banner()
378 412
379 413 # Make sure there is a space below the banner.
380 414 if self.log_level <= logging.INFO: print
381 415
416 self._enable_gui()
382 417 self._load_extensions()
383 418 self._run_exec_lines()
384 419 self._run_exec_files()
385 420 self._run_cmd_line_code()
386 421
422 def _enable_gui(self):
423 """Enable GUI event loop integration."""
424 config = self.master_config
425 try:
426 # Enable GUI integration
427 if config.Global.wthread:
428 self.log.info("Enabling wx GUI event loop integration")
429 inputhook.enable_wx(app=True)
430 elif config.Global.q4thread:
431 self.log.info("Enabling Qt4 GUI event loop integration")
432 inputhook.enable_qt4(app=True)
433 elif config.Global.gthread:
434 self.log.info("Enabling GTK GUI event loop integration")
435 inputhook.enable_gtk(app=True)
436 except:
437 self.log.warn("Error in enabling GUI event loop integration:")
438 self.shell.showtraceback()
439
387 440 def _load_extensions(self):
388 441 """Load all IPython extensions in Global.extensions.
389 442
390 443 This uses the :meth:`InteractiveShell.load_extensions` to load all
391 444 the extensions listed in ``self.master_config.Global.extensions``.
392 445 """
393 446 try:
394 447 if hasattr(self.master_config.Global, 'extensions'):
395 448 self.log.debug("Loading IPython extensions...")
396 449 extensions = self.master_config.Global.extensions
397 450 for ext in extensions:
398 451 try:
399 452 self.log.info("Loading IPython extension: %s" % ext)
400 453 self.shell.load_extension(ext)
401 454 except:
402 455 self.log.warn("Error in loading extension: %s" % ext)
403 456 self.shell.showtraceback()
404 457 except:
405 458 self.log.warn("Unknown error in loading extensions:")
406 459 self.shell.showtraceback()
407 460
408 461 def _run_exec_lines(self):
409 462 """Run lines of code in Global.exec_lines in the user's namespace."""
410 463 try:
411 464 if hasattr(self.master_config.Global, 'exec_lines'):
412 465 self.log.debug("Running code from Global.exec_lines...")
413 466 exec_lines = self.master_config.Global.exec_lines
414 467 for line in exec_lines:
415 468 try:
416 469 self.log.info("Running code in user namespace: %s" % line)
417 470 self.shell.runlines(line)
418 471 except:
419 472 self.log.warn("Error in executing line in user namespace: %s" % line)
420 473 self.shell.showtraceback()
421 474 except:
422 475 self.log.warn("Unknown error in handling Global.exec_lines:")
423 476 self.shell.showtraceback()
424 477
425 478 def _exec_file(self, fname):
426 479 full_filename = filefind(fname, ['.', self.ipythondir])
427 480 if os.path.isfile(full_filename):
428 481 if full_filename.endswith('.py'):
429 482 self.log.info("Running file in user namespace: %s" % full_filename)
430 483 self.shell.safe_execfile(full_filename, self.shell.user_ns)
431 484 elif full_filename.endswith('.ipy'):
432 485 self.log.info("Running file in user namespace: %s" % full_filename)
433 486 self.shell.safe_execfile_ipy(full_filename)
434 487 else:
435 488 self.log.warn("File does not have a .py or .ipy extension: <%s>" % full_filename)
436 489
437 490 def _run_exec_files(self):
438 491 try:
439 492 if hasattr(self.master_config.Global, 'exec_files'):
440 493 self.log.debug("Running files in Global.exec_files...")
441 494 exec_files = self.master_config.Global.exec_files
442 495 for fname in exec_files:
443 496 self._exec_file(fname)
444 497 except:
445 498 self.log.warn("Unknown error in handling Global.exec_files:")
446 499 self.shell.showtraceback()
447 500
448 501 def _run_cmd_line_code(self):
449 502 if hasattr(self.master_config.Global, 'code_to_run'):
450 503 line = self.master_config.Global.code_to_run
451 504 try:
452 505 self.log.info("Running code given at command line (-c): %s" % line)
453 506 self.shell.runlines(line)
454 507 except:
455 508 self.log.warn("Error in executing line in user namespace: %s" % line)
456 509 self.shell.showtraceback()
457 510 return
458 511 # Like Python itself, ignore the second if the first of these is present
459 512 try:
460 513 fname = self.extra_args[0]
461 514 except:
462 515 pass
463 516 else:
464 517 try:
465 518 self._exec_file(fname)
466 519 except:
467 520 self.log.warn("Error in executing file in user namespace: %s" % fname)
468 521 self.shell.showtraceback()
469 522
470 523 def start_app(self):
471 524 if self.master_config.Global.interact:
472 525 self.log.debug("Starting IPython's mainloop...")
473 526 self.shell.mainloop()
474 527
475 528
476 529 def load_default_config(ipythondir=None):
477 530 """Load the default config file from the default ipythondir.
478 531
479 532 This is useful for embedded shells.
480 533 """
481 534 if ipythondir is None:
482 535 ipythondir = get_ipython_dir()
483 536 cl = PyFileConfigLoader(_default_config_file_name, ipythondir)
484 537 config = cl.load_config()
485 538 return config
486 539
487 540
488 541 if __name__ == '__main__':
489 542 app = IPythonApp()
490 543 app.start() No newline at end of file
General Comments 0
You need to be logged in to leave comments. Login now