##// END OF EJS Templates
Add forgotten pydb flag to options list
Fernando Perez -
Show More
@@ -1,779 +1,780 b''
1 1 # -*- coding: utf-8 -*-
2 2 """
3 3 IPython -- An enhanced Interactive Python
4 4
5 5 Requires Python 2.1 or better.
6 6
7 7 This file contains the main make_IPython() starter function.
8 8
9 9 $Id: ipmaker.py 2930 2008-01-11 07:03:11Z vivainio $"""
10 10
11 11 #*****************************************************************************
12 12 # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
13 13 #
14 14 # Distributed under the terms of the BSD License. The full license is in
15 15 # the file COPYING, distributed as part of this software.
16 16 #*****************************************************************************
17 17
18 18 from IPython import Release
19 19 __author__ = '%s <%s>' % Release.authors['Fernando']
20 20 __license__ = Release.license
21 21 __version__ = Release.version
22 22
23 23 try:
24 24 credits._Printer__data = """
25 25 Python: %s
26 26
27 27 IPython: Fernando Perez, Janko Hauser, Nathan Gray, and many users.
28 28 See http://ipython.scipy.org for more information.""" \
29 29 % credits._Printer__data
30 30
31 31 copyright._Printer__data += """
32 32
33 33 Copyright (c) 2001-2004 Fernando Perez, Janko Hauser, Nathan Gray.
34 34 All Rights Reserved."""
35 35 except NameError:
36 36 # Can happen if ipython was started with 'python -S', so that site.py is
37 37 # not loaded
38 38 pass
39 39
40 40 #****************************************************************************
41 41 # Required modules
42 42
43 43 # From the standard library
44 44 import __main__
45 45 import __builtin__
46 46 import os
47 47 import re
48 48 import sys
49 49 import types
50 50 from pprint import pprint,pformat
51 51
52 52 # Our own
53 53 from IPython import DPyGetOpt
54 54 from IPython.ipstruct import Struct
55 55 from IPython.OutputTrap import OutputTrap
56 56 from IPython.ConfigLoader import ConfigLoader
57 57 from IPython.iplib import InteractiveShell
58 58 from IPython.usage import cmd_line_usage,interactive_usage
59 59 from IPython.genutils import *
60 60
61 61 def force_import(modname):
62 62 if modname in sys.modules:
63 63 print "reload",modname
64 64 reload(sys.modules[modname])
65 65 else:
66 66 __import__(modname)
67 67
68 68
69 69 #-----------------------------------------------------------------------------
70 70 def make_IPython(argv=None,user_ns=None,user_global_ns=None,debug=1,
71 71 rc_override=None,shell_class=InteractiveShell,
72 72 embedded=False,**kw):
73 73 """This is a dump of IPython into a single function.
74 74
75 75 Later it will have to be broken up in a sensible manner.
76 76
77 77 Arguments:
78 78
79 79 - argv: a list similar to sys.argv[1:]. It should NOT contain the desired
80 80 script name, b/c DPyGetOpt strips the first argument only for the real
81 81 sys.argv.
82 82
83 83 - user_ns: a dict to be used as the user's namespace."""
84 84
85 85 #----------------------------------------------------------------------
86 86 # Defaults and initialization
87 87
88 88 # For developer debugging, deactivates crash handler and uses pdb.
89 89 DEVDEBUG = False
90 90
91 91 if argv is None:
92 92 argv = sys.argv
93 93
94 94 # __IP is the main global that lives throughout and represents the whole
95 95 # application. If the user redefines it, all bets are off as to what
96 96 # happens.
97 97
98 98 # __IP is the name of he global which the caller will have accessible as
99 99 # __IP.name. We set its name via the first parameter passed to
100 100 # InteractiveShell:
101 101
102 102 IP = shell_class('__IP',user_ns=user_ns,user_global_ns=user_global_ns,
103 103 embedded=embedded,**kw)
104 104
105 105 # Put 'help' in the user namespace
106 106 try:
107 107 from site import _Helper
108 108 IP.user_ns['help'] = _Helper()
109 109 except ImportError:
110 110 warn('help() not available - check site.py')
111 111 IP.user_config_ns = {}
112 112
113 113
114 114 if DEVDEBUG:
115 115 # For developer debugging only (global flag)
116 116 from IPython import ultraTB
117 117 sys.excepthook = ultraTB.VerboseTB(call_pdb=1)
118 118
119 119 IP.BANNER_PARTS = ['Python %s\n'
120 120 'Type "copyright", "credits" or "license" '
121 121 'for more information.\n'
122 122 % (sys.version.split('\n')[0],),
123 123 "IPython %s -- An enhanced Interactive Python."
124 124 % (__version__,),
125 125 """\
126 126 ? -> Introduction and overview of IPython's features.
127 127 %quickref -> Quick reference.
128 128 help -> Python's own help system.
129 129 object? -> Details about 'object'. ?object also works, ?? prints more.
130 130 """ ]
131 131
132 132 IP.usage = interactive_usage
133 133
134 134 # Platform-dependent suffix and directory names. We use _ipython instead
135 135 # of .ipython under win32 b/c there's software that breaks with .named
136 136 # directories on that platform.
137 137 if os.name == 'posix':
138 138 rc_suffix = ''
139 139 ipdir_def = '.ipython'
140 140 else:
141 141 rc_suffix = '.ini'
142 142 ipdir_def = '_ipython'
143 143
144 144 # default directory for configuration
145 145 ipythondir_def = os.path.abspath(os.environ.get('IPYTHONDIR',
146 146 os.path.join(IP.home_dir,ipdir_def)))
147 147
148 148 sys.path.insert(0, '') # add . to sys.path. Fix from Prabhu Ramachandran
149 149
150 150 # we need the directory where IPython itself is installed
151 151 import IPython
152 152 IPython_dir = os.path.dirname(IPython.__file__)
153 153 del IPython
154 154
155 155 #-------------------------------------------------------------------------
156 156 # Command line handling
157 157
158 158 # Valid command line options (uses DPyGetOpt syntax, like Perl's
159 159 # GetOpt::Long)
160 160
161 161 # Any key not listed here gets deleted even if in the file (like session
162 162 # or profile). That's deliberate, to maintain the rc namespace clean.
163 163
164 164 # Each set of options appears twice: under _conv only the names are
165 165 # listed, indicating which type they must be converted to when reading the
166 166 # ipythonrc file. And under DPyGetOpt they are listed with the regular
167 167 # DPyGetOpt syntax (=s,=i,:f,etc).
168 168
169 169 # Make sure there's a space before each end of line (they get auto-joined!)
170 170 cmdline_opts = ('autocall=i autoindent! automagic! banner! cache_size|cs=i '
171 171 'c=s classic|cl color_info! colors=s confirm_exit! '
172 172 'debug! deep_reload! editor=s log|l messages! nosep '
173 173 'object_info_string_level=i pdb! '
174 174 'pprint! prompt_in1|pi1=s prompt_in2|pi2=s prompt_out|po=s '
175 175 'pydb! '
176 176 'pylab_import_all! '
177 177 'quick screen_length|sl=i prompts_pad_left=i '
178 178 'logfile|lf=s logplay|lp=s profile|p=s '
179 179 'readline! readline_merge_completions! '
180 180 'readline_omit__names! '
181 181 'rcfile=s separate_in|si=s separate_out|so=s '
182 182 'separate_out2|so2=s xmode=s wildcards_case_sensitive! '
183 183 'magic_docstrings system_verbose! '
184 184 'multi_line_specials! '
185 185 'term_title! wxversion=s '
186 186 'autoedit_syntax!')
187 187
188 188 # Options that can *only* appear at the cmd line (not in rcfiles).
189 189
190 190 cmdline_only = ('help interact|i ipythondir=s Version upgrade '
191 191 'gthread! qthread! q4thread! wthread! tkthread! pylab! tk! '
192 192 # 'twisted!' # disabled for now.
193 193 )
194 194
195 195 # Build the actual name list to be used by DPyGetOpt
196 196 opts_names = qw(cmdline_opts) + qw(cmdline_only)
197 197
198 198 # Set sensible command line defaults.
199 199 # This should have everything from cmdline_opts and cmdline_only
200 200 opts_def = Struct(autocall = 1,
201 201 autoedit_syntax = 0,
202 202 autoindent = 0,
203 203 automagic = 1,
204 204 autoexec = [],
205 205 banner = 1,
206 206 c = '',
207 207 cache_size = 1000,
208 208 classic = 0,
209 209 color_info = 0,
210 210 colors = 'NoColor',
211 211 confirm_exit = 1,
212 212 debug = 0,
213 213 deep_reload = 0,
214 214 editor = '0',
215 215 gthread = 0,
216 216 help = 0,
217 217 interact = 0,
218 218 ipythondir = ipythondir_def,
219 219 log = 0,
220 220 logfile = '',
221 221 logplay = '',
222 222 messages = 1,
223 223 multi_line_specials = 1,
224 224 nosep = 0,
225 225 object_info_string_level = 0,
226 226 pdb = 0,
227 227 pprint = 0,
228 228 profile = '',
229 229 prompt_in1 = 'In [\\#]: ',
230 230 prompt_in2 = ' .\\D.: ',
231 231 prompt_out = 'Out[\\#]: ',
232 232 prompts_pad_left = 1,
233 pydb = 0,
233 234 pylab = 0,
234 235 pylab_import_all = 1,
235 236 q4thread = 0,
236 237 qthread = 0,
237 238 quick = 0,
238 239 quiet = 0,
239 240 rcfile = 'ipythonrc' + rc_suffix,
240 241 readline = 1,
241 242 readline_merge_completions = 1,
242 243 readline_omit__names = 0,
243 244 screen_length = 0,
244 245 separate_in = '\n',
245 246 separate_out = '\n',
246 247 separate_out2 = '',
247 248 system_header = 'IPython system call: ',
248 249 system_verbose = 0,
249 250 term_title = 1,
250 251 tk = 0,
251 252 #twisted= 0, # disabled for now
252 253 upgrade = 0,
253 254 Version = 0,
254 255 wildcards_case_sensitive = 1,
255 256 wthread = 0,
256 257 wxversion = '0',
257 258 xmode = 'Context',
258 259 magic_docstrings = 0, # undocumented, for doc generation
259 260 )
260 261
261 262 # Things that will *only* appear in rcfiles (not at the command line).
262 263 # Make sure there's a space before each end of line (they get auto-joined!)
263 264 rcfile_opts = { qwflat: 'include import_mod import_all execfile ',
264 265 qw_lol: 'import_some ',
265 266 # for things with embedded whitespace:
266 267 list_strings:'execute alias readline_parse_and_bind ',
267 268 # Regular strings need no conversion:
268 269 None:'readline_remove_delims ',
269 270 }
270 271 # Default values for these
271 272 rc_def = Struct(include = [],
272 273 import_mod = [],
273 274 import_all = [],
274 275 import_some = [[]],
275 276 execute = [],
276 277 execfile = [],
277 278 alias = [],
278 279 readline_parse_and_bind = [],
279 280 readline_remove_delims = '',
280 281 )
281 282
282 283 # Build the type conversion dictionary from the above tables:
283 284 typeconv = rcfile_opts.copy()
284 285 typeconv.update(optstr2types(cmdline_opts))
285 286
286 287 # FIXME: the None key appears in both, put that back together by hand. Ugly!
287 288 typeconv[None] += ' ' + rcfile_opts[None]
288 289
289 290 # Remove quotes at ends of all strings (used to protect spaces)
290 291 typeconv[unquote_ends] = typeconv[None]
291 292 del typeconv[None]
292 293
293 294 # Build the list we'll use to make all config decisions with defaults:
294 295 opts_all = opts_def.copy()
295 296 opts_all.update(rc_def)
296 297
297 298 # Build conflict resolver for recursive loading of config files:
298 299 # - preserve means the outermost file maintains the value, it is not
299 300 # overwritten if an included file has the same key.
300 301 # - add_flip applies + to the two values, so it better make sense to add
301 302 # those types of keys. But it flips them first so that things loaded
302 303 # deeper in the inclusion chain have lower precedence.
303 304 conflict = {'preserve': ' '.join([ typeconv[int],
304 305 typeconv[unquote_ends] ]),
305 306 'add_flip': ' '.join([ typeconv[qwflat],
306 307 typeconv[qw_lol],
307 308 typeconv[list_strings] ])
308 309 }
309 310
310 311 # Now actually process the command line
311 312 getopt = DPyGetOpt.DPyGetOpt()
312 313 getopt.setIgnoreCase(0)
313 314
314 315 getopt.parseConfiguration(opts_names)
315 316
316 317 try:
317 318 getopt.processArguments(argv)
318 319 except DPyGetOpt.ArgumentError, exc:
319 320 print cmd_line_usage
320 321 warn('\nError in Arguments: "%s"' % exc)
321 322 sys.exit(1)
322 323
323 324 # convert the options dict to a struct for much lighter syntax later
324 325 opts = Struct(getopt.optionValues)
325 326 args = getopt.freeValues
326 327
327 328 # this is the struct (which has default values at this point) with which
328 329 # we make all decisions:
329 330 opts_all.update(opts)
330 331
331 332 # Options that force an immediate exit
332 333 if opts_all.help:
333 334 page(cmd_line_usage)
334 335 sys.exit()
335 336
336 337 if opts_all.Version:
337 338 print __version__
338 339 sys.exit()
339 340
340 341 if opts_all.magic_docstrings:
341 342 IP.magic_magic('-latex')
342 343 sys.exit()
343 344
344 345 # add personal ipythondir to sys.path so that users can put things in
345 346 # there for customization
346 347 sys.path.append(os.path.abspath(opts_all.ipythondir))
347 348
348 349 # Create user config directory if it doesn't exist. This must be done
349 350 # *after* getting the cmd line options.
350 351 if not os.path.isdir(opts_all.ipythondir):
351 352 IP.user_setup(opts_all.ipythondir,rc_suffix,'install')
352 353
353 354 # upgrade user config files while preserving a copy of the originals
354 355 if opts_all.upgrade:
355 356 IP.user_setup(opts_all.ipythondir,rc_suffix,'upgrade')
356 357
357 358 # check mutually exclusive options in the *original* command line
358 359 mutex_opts(opts,[qw('log logfile'),qw('rcfile profile'),
359 360 qw('classic profile'),qw('classic rcfile')])
360 361
361 362 #---------------------------------------------------------------------------
362 363 # Log replay
363 364
364 365 # if -logplay, we need to 'become' the other session. That basically means
365 366 # replacing the current command line environment with that of the old
366 367 # session and moving on.
367 368
368 369 # this is needed so that later we know we're in session reload mode, as
369 370 # opts_all will get overwritten:
370 371 load_logplay = 0
371 372
372 373 if opts_all.logplay:
373 374 load_logplay = opts_all.logplay
374 375 opts_debug_save = opts_all.debug
375 376 try:
376 377 logplay = open(opts_all.logplay)
377 378 except IOError:
378 379 if opts_all.debug: IP.InteractiveTB()
379 380 warn('Could not open logplay file '+`opts_all.logplay`)
380 381 # restore state as if nothing had happened and move on, but make
381 382 # sure that later we don't try to actually load the session file
382 383 logplay = None
383 384 load_logplay = 0
384 385 del opts_all.logplay
385 386 else:
386 387 try:
387 388 logplay.readline()
388 389 logplay.readline();
389 390 # this reloads that session's command line
390 391 cmd = logplay.readline()[6:]
391 392 exec cmd
392 393 # restore the true debug flag given so that the process of
393 394 # session loading itself can be monitored.
394 395 opts.debug = opts_debug_save
395 396 # save the logplay flag so later we don't overwrite the log
396 397 opts.logplay = load_logplay
397 398 # now we must update our own structure with defaults
398 399 opts_all.update(opts)
399 400 # now load args
400 401 cmd = logplay.readline()[6:]
401 402 exec cmd
402 403 logplay.close()
403 404 except:
404 405 logplay.close()
405 406 if opts_all.debug: IP.InteractiveTB()
406 407 warn("Logplay file lacking full configuration information.\n"
407 408 "I'll try to read it, but some things may not work.")
408 409
409 410 #-------------------------------------------------------------------------
410 411 # set up output traps: catch all output from files, being run, modules
411 412 # loaded, etc. Then give it to the user in a clean form at the end.
412 413
413 414 msg_out = 'Output messages. '
414 415 msg_err = 'Error messages. '
415 416 msg_sep = '\n'
416 417 msg = Struct(config = OutputTrap('Configuration Loader',msg_out,
417 418 msg_err,msg_sep,debug,
418 419 quiet_out=1),
419 420 user_exec = OutputTrap('User File Execution',msg_out,
420 421 msg_err,msg_sep,debug),
421 422 logplay = OutputTrap('Log Loader',msg_out,
422 423 msg_err,msg_sep,debug),
423 424 summary = ''
424 425 )
425 426
426 427 #-------------------------------------------------------------------------
427 428 # Process user ipythonrc-type configuration files
428 429
429 430 # turn on output trapping and log to msg.config
430 431 # remember that with debug on, trapping is actually disabled
431 432 msg.config.trap_all()
432 433
433 434 # look for rcfile in current or default directory
434 435 try:
435 436 opts_all.rcfile = filefind(opts_all.rcfile,opts_all.ipythondir)
436 437 except IOError:
437 438 if opts_all.debug: IP.InteractiveTB()
438 439 warn('Configuration file %s not found. Ignoring request.'
439 440 % (opts_all.rcfile) )
440 441
441 442 # 'profiles' are a shorthand notation for config filenames
442 443 profile_handled_by_legacy = False
443 444 if opts_all.profile:
444 445
445 446 try:
446 447 opts_all.rcfile = filefind('ipythonrc-' + opts_all.profile
447 448 + rc_suffix,
448 449 opts_all.ipythondir)
449 450 profile_handled_by_legacy = True
450 451 except IOError:
451 452 if opts_all.debug: IP.InteractiveTB()
452 453 opts.profile = '' # remove profile from options if invalid
453 454 # We won't warn anymore, primary method is ipy_profile_PROFNAME
454 455 # which does trigger a warning.
455 456
456 457 # load the config file
457 458 rcfiledata = None
458 459 if opts_all.quick:
459 460 print 'Launching IPython in quick mode. No config file read.'
460 461 elif opts_all.rcfile:
461 462 try:
462 463 cfg_loader = ConfigLoader(conflict)
463 464 rcfiledata = cfg_loader.load(opts_all.rcfile,typeconv,
464 465 'include',opts_all.ipythondir,
465 466 purge = 1,
466 467 unique = conflict['preserve'])
467 468 except:
468 469 IP.InteractiveTB()
469 470 warn('Problems loading configuration file '+
470 471 `opts_all.rcfile`+
471 472 '\nStarting with default -bare bones- configuration.')
472 473 else:
473 474 warn('No valid configuration file found in either currrent directory\n'+
474 475 'or in the IPython config. directory: '+`opts_all.ipythondir`+
475 476 '\nProceeding with internal defaults.')
476 477
477 478 #------------------------------------------------------------------------
478 479 # Set exception handlers in mode requested by user.
479 480 otrap = OutputTrap(trap_out=1) # trap messages from magic_xmode
480 481 IP.magic_xmode(opts_all.xmode)
481 482 otrap.release_out()
482 483
483 484 #------------------------------------------------------------------------
484 485 # Execute user config
485 486
486 487 # Create a valid config structure with the right precedence order:
487 488 # defaults < rcfile < command line. This needs to be in the instance, so
488 489 # that method calls below that rely on it find it.
489 490 IP.rc = rc_def.copy()
490 491
491 492 # Work with a local alias inside this routine to avoid unnecessary
492 493 # attribute lookups.
493 494 IP_rc = IP.rc
494 495
495 496 IP_rc.update(opts_def)
496 497 if rcfiledata:
497 498 # now we can update
498 499 IP_rc.update(rcfiledata)
499 500 IP_rc.update(opts)
500 501 IP_rc.update(rc_override)
501 502
502 503 # Store the original cmd line for reference:
503 504 IP_rc.opts = opts
504 505 IP_rc.args = args
505 506
506 507 # create a *runtime* Struct like rc for holding parameters which may be
507 508 # created and/or modified by runtime user extensions.
508 509 IP.runtime_rc = Struct()
509 510
510 511 # from this point on, all config should be handled through IP_rc,
511 512 # opts* shouldn't be used anymore.
512 513
513 514
514 515 # update IP_rc with some special things that need manual
515 516 # tweaks. Basically options which affect other options. I guess this
516 517 # should just be written so that options are fully orthogonal and we
517 518 # wouldn't worry about this stuff!
518 519
519 520 if IP_rc.classic:
520 521 IP_rc.quick = 1
521 522 IP_rc.cache_size = 0
522 523 IP_rc.pprint = 0
523 524 IP_rc.prompt_in1 = '>>> '
524 525 IP_rc.prompt_in2 = '... '
525 526 IP_rc.prompt_out = ''
526 527 IP_rc.separate_in = IP_rc.separate_out = IP_rc.separate_out2 = '0'
527 528 IP_rc.colors = 'NoColor'
528 529 IP_rc.xmode = 'Plain'
529 530
530 531 IP.pre_config_initialization()
531 532 # configure readline
532 533 # Define the history file for saving commands in between sessions
533 534 if IP_rc.profile:
534 535 histfname = 'history-%s' % IP_rc.profile
535 536 else:
536 537 histfname = 'history'
537 538 IP.histfile = os.path.join(opts_all.ipythondir,histfname)
538 539
539 540 # update exception handlers with rc file status
540 541 otrap.trap_out() # I don't want these messages ever.
541 542 IP.magic_xmode(IP_rc.xmode)
542 543 otrap.release_out()
543 544
544 545 # activate logging if requested and not reloading a log
545 546 if IP_rc.logplay:
546 547 IP.magic_logstart(IP_rc.logplay + ' append')
547 548 elif IP_rc.logfile:
548 549 IP.magic_logstart(IP_rc.logfile)
549 550 elif IP_rc.log:
550 551 IP.magic_logstart()
551 552
552 553 # find user editor so that it we don't have to look it up constantly
553 554 if IP_rc.editor.strip()=='0':
554 555 try:
555 556 ed = os.environ['EDITOR']
556 557 except KeyError:
557 558 if os.name == 'posix':
558 559 ed = 'vi' # the only one guaranteed to be there!
559 560 else:
560 561 ed = 'notepad' # same in Windows!
561 562 IP_rc.editor = ed
562 563
563 564 # Keep track of whether this is an embedded instance or not (useful for
564 565 # post-mortems).
565 566 IP_rc.embedded = IP.embedded
566 567
567 568 # Recursive reload
568 569 try:
569 570 from IPython import deep_reload
570 571 if IP_rc.deep_reload:
571 572 __builtin__.reload = deep_reload.reload
572 573 else:
573 574 __builtin__.dreload = deep_reload.reload
574 575 del deep_reload
575 576 except ImportError:
576 577 pass
577 578
578 579 # Save the current state of our namespace so that the interactive shell
579 580 # can later know which variables have been created by us from config files
580 581 # and loading. This way, loading a file (in any way) is treated just like
581 582 # defining things on the command line, and %who works as expected.
582 583
583 584 # DON'T do anything that affects the namespace beyond this point!
584 585 IP.internal_ns.update(__main__.__dict__)
585 586
586 587 #IP.internal_ns.update(locals()) # so our stuff doesn't show up in %who
587 588
588 589 # Now run through the different sections of the users's config
589 590 if IP_rc.debug:
590 591 print 'Trying to execute the following configuration structure:'
591 592 print '(Things listed first are deeper in the inclusion tree and get'
592 593 print 'loaded first).\n'
593 594 pprint(IP_rc.__dict__)
594 595
595 596 for mod in IP_rc.import_mod:
596 597 try:
597 598 exec 'import '+mod in IP.user_ns
598 599 except :
599 600 IP.InteractiveTB()
600 601 import_fail_info(mod)
601 602
602 603 for mod_fn in IP_rc.import_some:
603 604 if not mod_fn == []:
604 605 mod,fn = mod_fn[0],','.join(mod_fn[1:])
605 606 try:
606 607 exec 'from '+mod+' import '+fn in IP.user_ns
607 608 except :
608 609 IP.InteractiveTB()
609 610 import_fail_info(mod,fn)
610 611
611 612 for mod in IP_rc.import_all:
612 613 try:
613 614 exec 'from '+mod+' import *' in IP.user_ns
614 615 except :
615 616 IP.InteractiveTB()
616 617 import_fail_info(mod)
617 618
618 619 for code in IP_rc.execute:
619 620 try:
620 621 exec code in IP.user_ns
621 622 except:
622 623 IP.InteractiveTB()
623 624 warn('Failure executing code: ' + `code`)
624 625
625 626 # Execute the files the user wants in ipythonrc
626 627 for file in IP_rc.execfile:
627 628 try:
628 629 file = filefind(file,sys.path+[IPython_dir])
629 630 except IOError:
630 631 warn(itpl('File $file not found. Skipping it.'))
631 632 else:
632 633 IP.safe_execfile(os.path.expanduser(file),IP.user_ns)
633 634
634 635 # finally, try importing ipy_*_conf for final configuration
635 636 try:
636 637 import ipy_system_conf
637 638 except ImportError:
638 639 if opts_all.debug: IP.InteractiveTB()
639 640 warn("Could not import 'ipy_system_conf'")
640 641 except:
641 642 IP.InteractiveTB()
642 643 import_fail_info('ipy_system_conf')
643 644
644 645 # only import prof module if ipythonrc-PROF was not found
645 646 if opts_all.profile and not profile_handled_by_legacy:
646 647 profmodname = 'ipy_profile_' + opts_all.profile
647 648 try:
648 649
649 650 force_import(profmodname)
650 651 except:
651 652 IP.InteractiveTB()
652 653 print "Error importing",profmodname,"- perhaps you should run %upgrade?"
653 654 import_fail_info(profmodname)
654 655 else:
655 656 force_import('ipy_profile_none')
656 657 try:
657 658
658 659 force_import('ipy_user_conf')
659 660
660 661 except:
661 662 conf = opts_all.ipythondir + "/ipy_user_conf.py"
662 663 IP.InteractiveTB()
663 664 if not os.path.isfile(conf):
664 665 warn(conf + ' does not exist, please run %upgrade!')
665 666
666 667 import_fail_info("ipy_user_conf")
667 668
668 669 # finally, push the argv to options again to ensure highest priority
669 670 IP_rc.update(opts)
670 671
671 672 # release stdout and stderr and save config log into a global summary
672 673 msg.config.release_all()
673 674 if IP_rc.messages:
674 675 msg.summary += msg.config.summary_all()
675 676
676 677 #------------------------------------------------------------------------
677 678 # Setup interactive session
678 679
679 680 # Now we should be fully configured. We can then execute files or load
680 681 # things only needed for interactive use. Then we'll open the shell.
681 682
682 683 # Take a snapshot of the user namespace before opening the shell. That way
683 684 # we'll be able to identify which things were interactively defined and
684 685 # which were defined through config files.
685 686 IP.user_config_ns.update(IP.user_ns)
686 687
687 688 # Force reading a file as if it were a session log. Slower but safer.
688 689 if load_logplay:
689 690 print 'Replaying log...'
690 691 try:
691 692 if IP_rc.debug:
692 693 logplay_quiet = 0
693 694 else:
694 695 logplay_quiet = 1
695 696
696 697 msg.logplay.trap_all()
697 698 IP.safe_execfile(load_logplay,IP.user_ns,
698 699 islog = 1, quiet = logplay_quiet)
699 700 msg.logplay.release_all()
700 701 if IP_rc.messages:
701 702 msg.summary += msg.logplay.summary_all()
702 703 except:
703 704 warn('Problems replaying logfile %s.' % load_logplay)
704 705 IP.InteractiveTB()
705 706
706 707 # Load remaining files in command line
707 708 msg.user_exec.trap_all()
708 709
709 710 # Do NOT execute files named in the command line as scripts to be loaded
710 711 # by embedded instances. Doing so has the potential for an infinite
711 712 # recursion if there are exceptions thrown in the process.
712 713
713 714 # XXX FIXME: the execution of user files should be moved out to after
714 715 # ipython is fully initialized, just as if they were run via %run at the
715 716 # ipython prompt. This would also give them the benefit of ipython's
716 717 # nice tracebacks.
717 718
718 719 if (not embedded and IP_rc.args and
719 720 not IP_rc.args[0].lower().endswith('.ipy')):
720 721 name_save = IP.user_ns['__name__']
721 722 IP.user_ns['__name__'] = '__main__'
722 723 # Set our own excepthook in case the user code tries to call it
723 724 # directly. This prevents triggering the IPython crash handler.
724 725 old_excepthook,sys.excepthook = sys.excepthook, IP.excepthook
725 726
726 727 save_argv = sys.argv[1:] # save it for later restoring
727 728
728 729 sys.argv = args
729 730
730 731 try:
731 732 IP.safe_execfile(args[0], IP.user_ns)
732 733 finally:
733 734 # Reset our crash handler in place
734 735 sys.excepthook = old_excepthook
735 736 sys.argv[:] = save_argv
736 737 IP.user_ns['__name__'] = name_save
737 738
738 739 msg.user_exec.release_all()
739 740
740 741 if IP_rc.messages:
741 742 msg.summary += msg.user_exec.summary_all()
742 743
743 744 # since we can't specify a null string on the cmd line, 0 is the equivalent:
744 745 if IP_rc.nosep:
745 746 IP_rc.separate_in = IP_rc.separate_out = IP_rc.separate_out2 = '0'
746 747 if IP_rc.separate_in == '0': IP_rc.separate_in = ''
747 748 if IP_rc.separate_out == '0': IP_rc.separate_out = ''
748 749 if IP_rc.separate_out2 == '0': IP_rc.separate_out2 = ''
749 750 IP_rc.separate_in = IP_rc.separate_in.replace('\\n','\n')
750 751 IP_rc.separate_out = IP_rc.separate_out.replace('\\n','\n')
751 752 IP_rc.separate_out2 = IP_rc.separate_out2.replace('\\n','\n')
752 753
753 754 # Determine how many lines at the bottom of the screen are needed for
754 755 # showing prompts, so we can know wheter long strings are to be printed or
755 756 # paged:
756 757 num_lines_bot = IP_rc.separate_in.count('\n')+1
757 758 IP_rc.screen_length = IP_rc.screen_length - num_lines_bot
758 759
759 760 # configure startup banner
760 761 if IP_rc.c: # regular python doesn't print the banner with -c
761 762 IP_rc.banner = 0
762 763 if IP_rc.banner:
763 764 BANN_P = IP.BANNER_PARTS
764 765 else:
765 766 BANN_P = []
766 767
767 768 if IP_rc.profile: BANN_P.append('IPython profile: %s\n' % IP_rc.profile)
768 769
769 770 # add message log (possibly empty)
770 771 if msg.summary: BANN_P.append(msg.summary)
771 772 # Final banner is a string
772 773 IP.BANNER = '\n'.join(BANN_P)
773 774
774 775 # Finalize the IPython instance. This assumes the rc structure is fully
775 776 # in place.
776 777 IP.post_config_initialization()
777 778
778 779 return IP
779 780 #************************ end of file <ipmaker.py> **************************
General Comments 0
You need to be logged in to leave comments. Login now