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