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