##// END OF EJS Templates
Fix %upgrade, and suggest using it.
vivainio -
Show More

The requested changes are too big and content was truncated. Show full diff

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