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