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