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