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