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