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