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