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