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