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