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