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