##// END OF EJS Templates
More informative message in ipy_user_conf import failure (suggest running %upgrade)...
vivainio -
Show More

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

@@ -1,85 +1,85 b''
1 1 # -*- coding: utf-8 -*-
2 2 """Release data for the IPython project.
3 3
4 $Id: Release.py 2010 2006-12-20 15:29:17Z vivainio $"""
4 $Id: Release.py 2012 2006-12-24 10:28:29Z vivainio $"""
5 5
6 6 #*****************************************************************************
7 7 # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu>
8 8 #
9 9 # Copyright (c) 2001 Janko Hauser <jhauser@zscout.de> and Nathaniel Gray
10 10 # <n8gray@caltech.edu>
11 11 #
12 12 # Distributed under the terms of the BSD License. The full license is in
13 13 # the file COPYING, distributed as part of this software.
14 14 #*****************************************************************************
15 15
16 16 # Name of the package for release purposes. This is the name which labels
17 17 # the tarballs and RPMs made by distutils, so it's best to lowercase it.
18 18 name = 'ipython'
19 19
20 20 # For versions with substrings (like 0.6.16.svn), use an extra . to separate
21 21 # the new substring. We have to avoid using either dashes or underscores,
22 22 # because bdist_rpm does not accept dashes (an RPM) convention, and
23 23 # bdist_deb does not accept underscores (a Debian convention).
24 24
25 revision = '2007'
25 revision = '2010M'
26 26
27 version = '0.7.3'
27 #version = '0.7.3'
28 28
29 #version = '0.7.3rc2.r' + revision.rstrip('M')
29 version = '0.7.4.svn.r' + revision.rstrip('M')
30 30
31 31 description = "An enhanced interactive Python shell."
32 32
33 33 long_description = \
34 34 """
35 35 IPython provides a replacement for the interactive Python interpreter with
36 36 extra functionality.
37 37
38 38 Main features:
39 39
40 40 * Comprehensive object introspection.
41 41
42 42 * Input history, persistent across sessions.
43 43
44 44 * Caching of output results during a session with automatically generated
45 45 references.
46 46
47 47 * Readline based name completion.
48 48
49 49 * Extensible system of 'magic' commands for controlling the environment and
50 50 performing many tasks related either to IPython or the operating system.
51 51
52 52 * Configuration system with easy switching between different setups (simpler
53 53 than changing $PYTHONSTARTUP environment variables every time).
54 54
55 55 * Session logging and reloading.
56 56
57 57 * Extensible syntax processing for special purpose situations.
58 58
59 59 * Access to the system shell with user-extensible alias system.
60 60
61 61 * Easily embeddable in other Python programs.
62 62
63 63 * Integrated access to the pdb debugger and the Python profiler.
64 64
65 65 The latest development version is always available at the IPython subversion
66 66 repository_.
67 67
68 68 .. _repository: http://ipython.scipy.org/svn/ipython/ipython/trunk#egg=ipython-dev
69 69 """
70 70
71 71 license = 'BSD'
72 72
73 73 authors = {'Fernando' : ('Fernando Perez','fperez@colorado.edu'),
74 74 'Janko' : ('Janko Hauser','jhauser@zscout.de'),
75 75 'Nathan' : ('Nathaniel Gray','n8gray@caltech.edu'),
76 76 'Ville' : ('Ville Vainio','vivainio@gmail.com')
77 77 }
78 78
79 79 url = 'http://ipython.scipy.org'
80 80
81 81 download_url = 'http://ipython.scipy.org/dist'
82 82
83 83 platforms = ['Linux','Mac OSX','Windows XP/2000/NT','Windows 95/98/ME']
84 84
85 85 keywords = ['Interactive','Interpreter','Shell']
@@ -1,336 +1,351 b''
1 1 ''' IPython customization API
2 2
3 3 Your one-stop module for configuring & extending ipython
4 4
5 5 The API will probably break when ipython 1.0 is released, but so
6 6 will the other configuration method (rc files).
7 7
8 8 All names prefixed by underscores are for internal use, not part
9 9 of the public api.
10 10
11 11 Below is an example that you can just put to a module and import from ipython.
12 12
13 13 A good practice is to install the config script below as e.g.
14 14
15 15 ~/.ipython/my_private_conf.py
16 16
17 17 And do
18 18
19 19 import_mod my_private_conf
20 20
21 21 in ~/.ipython/ipythonrc
22 22
23 23 That way the module is imported at startup and you can have all your
24 24 personal configuration (as opposed to boilerplate ipythonrc-PROFILENAME
25 25 stuff) in there.
26 26
27 27 -----------------------------------------------
28 28 import IPython.ipapi
29 29 ip = IPython.ipapi.get()
30 30
31 31 def ankka_f(self, arg):
32 32 print "Ankka",self,"says uppercase:",arg.upper()
33 33
34 34 ip.expose_magic("ankka",ankka_f)
35 35
36 36 ip.magic('alias sayhi echo "Testing, hi ok"')
37 37 ip.magic('alias helloworld echo "Hello world"')
38 38 ip.system('pwd')
39 39
40 40 ip.ex('import re')
41 41 ip.ex("""
42 42 def funcci(a,b):
43 43 print a+b
44 44 print funcci(3,4)
45 45 """)
46 46 ip.ex("funcci(348,9)")
47 47
48 48 def jed_editor(self,filename, linenum=None):
49 49 print "Calling my own editor, jed ... via hook!"
50 50 import os
51 51 if linenum is None: linenum = 0
52 52 os.system('jed +%d %s' % (linenum, filename))
53 53 print "exiting jed"
54 54
55 55 ip.set_hook('editor',jed_editor)
56 56
57 57 o = ip.options
58 58 o.autocall = 2 # FULL autocall mode
59 59
60 60 print "done!"
61 61 '''
62 62
63 63 # stdlib imports
64 64 import __builtin__
65 65 import sys
66 66
67 67 # our own
68 68 from IPython.genutils import warn,error
69 69
70 70 class TryNext(Exception):
71 71 """Try next hook exception.
72 72
73 73 Raise this in your hook function to indicate that the next hook handler
74 74 should be used to handle the operation. If you pass arguments to the
75 75 constructor those arguments will be used by the next hook instead of the
76 76 original ones.
77 77 """
78 78
79 79 def __init__(self, *args, **kwargs):
80 80 self.args = args
81 81 self.kwargs = kwargs
82 82
83 83 # contains the most recently instantiated IPApi
84 84
85 85 class IPythonNotRunning:
86 86 """Dummy do-nothing class.
87 87
88 88 Instances of this class return a dummy attribute on all accesses, which
89 89 can be called and warns. This makes it easier to write scripts which use
90 90 the ipapi.get() object for informational purposes to operate both with and
91 91 without ipython. Obviously code which uses the ipython object for
92 92 computations will not work, but this allows a wider range of code to
93 93 transparently work whether ipython is being used or not."""
94 94
95 95 def __str__(self):
96 96 return "<IPythonNotRunning>"
97 97
98 98 __repr__ = __str__
99 99
100 100 def __getattr__(self,name):
101 101 return self.dummy
102 102
103 103 def dummy(self,*args,**kw):
104 104 """Dummy function, which doesn't do anything but warn."""
105 105 warn("IPython is not running, this is a dummy no-op function")
106 106
107 107 _recent = None
108 108
109 109
110 110 def get(allow_dummy=False):
111 111 """Get an IPApi object.
112 112
113 113 If allow_dummy is true, returns an instance of IPythonNotRunning
114 114 instead of None if not running under IPython.
115 115
116 116 Running this should be the first thing you do when writing extensions that
117 117 can be imported as normal modules. You can then direct all the
118 118 configuration operations against the returned object.
119 119 """
120 120 global _recent
121 121 if allow_dummy and not _recent:
122 122 _recent = IPythonNotRunning()
123 123 return _recent
124 124
125 125 class IPApi:
126 126 """ The actual API class for configuring IPython
127 127
128 128 You should do all of the IPython configuration by getting an IPApi object
129 129 with IPython.ipapi.get() and using the attributes and methods of the
130 130 returned object."""
131 131
132 132 def __init__(self,ip):
133 133
134 134 # All attributes exposed here are considered to be the public API of
135 135 # IPython. As needs dictate, some of these may be wrapped as
136 136 # properties.
137 137
138 138 self.magic = ip.ipmagic
139 139
140 140 self.system = ip.ipsystem
141 141
142 142 self.set_hook = ip.set_hook
143 143
144 144 self.set_custom_exc = ip.set_custom_exc
145 145
146 146 self.user_ns = ip.user_ns
147 147
148 148 self.set_crash_handler = ip.set_crash_handler
149 149
150 150 # Session-specific data store, which can be used to store
151 151 # data that should persist through the ipython session.
152 152 self.meta = ip.meta
153 153
154 154 # The ipython instance provided
155 155 self.IP = ip
156 156
157 157 global _recent
158 158 _recent = self
159 159
160 160 # Use a property for some things which are added to the instance very
161 161 # late. I don't have time right now to disentangle the initialization
162 162 # order issues, so a property lets us delay item extraction while
163 163 # providing a normal attribute API.
164 164 def get_db(self):
165 165 """A handle to persistent dict-like database (a PickleShareDB object)"""
166 166 return self.IP.db
167 167
168 168 db = property(get_db,None,None,get_db.__doc__)
169 169
170 170 def get_options(self):
171 171 """All configurable variables."""
172 172
173 173 # catch typos by disabling new attribute creation. If new attr creation
174 174 # is in fact wanted (e.g. when exposing new options), do allow_new_attr(True)
175 175 # for the received rc struct.
176 176
177 177 self.IP.rc.allow_new_attr(False)
178 178 return self.IP.rc
179 179
180 180 options = property(get_options,None,None,get_options.__doc__)
181 181
182 182 def expose_magic(self,magicname, func):
183 183 ''' Expose own function as magic function for ipython
184 184
185 185 def foo_impl(self,parameter_s=''):
186 186 """My very own magic!. (Use docstrings, IPython reads them)."""
187 187 print 'Magic function. Passed parameter is between < >: <'+parameter_s+'>'
188 188 print 'The self object is:',self
189 189
190 190 ipapi.expose_magic("foo",foo_impl)
191 191 '''
192 192
193 193 import new
194 194 im = new.instancemethod(func,self.IP, self.IP.__class__)
195 195 setattr(self.IP, "magic_" + magicname, im)
196 196
197 197 def ex(self,cmd):
198 198 """ Execute a normal python statement in user namespace """
199 199 exec cmd in self.user_ns
200 200
201 201 def ev(self,expr):
202 202 """ Evaluate python expression expr in user namespace
203 203
204 204 Returns the result of evaluation"""
205 205 return eval(expr,self.user_ns)
206 206
207 207 def runlines(self,lines):
208 208 """ Run the specified lines in interpreter, honoring ipython directives.
209 209
210 210 This allows %magic and !shell escape notations.
211 211
212 212 Takes either all lines in one string or list of lines.
213 213 """
214 214 if isinstance(lines,basestring):
215 215 self.IP.runlines(lines)
216 216 else:
217 217 self.IP.runlines('\n'.join(lines))
218 218
219 219 def to_user_ns(self,vars):
220 220 """Inject a group of variables into the IPython user namespace.
221 221
222 222 Inputs:
223 223
224 224 - vars: string with variable names separated by whitespace
225 225
226 226 This utility routine is meant to ease interactive debugging work,
227 227 where you want to easily propagate some internal variable in your code
228 228 up to the interactive namespace for further exploration.
229 229
230 230 When you run code via %run, globals in your script become visible at
231 231 the interactive prompt, but this doesn't happen for locals inside your
232 232 own functions and methods. Yet when debugging, it is common to want
233 233 to explore some internal variables further at the interactive propmt.
234 234
235 235 Examples:
236 236
237 237 To use this, you first must obtain a handle on the ipython object as
238 238 indicated above, via:
239 239
240 240 import IPython.ipapi
241 241 ip = IPython.ipapi.get()
242 242
243 243 Once this is done, inside a routine foo() where you want to expose
244 244 variables x and y, you do the following:
245 245
246 246 def foo():
247 247 ...
248 248 x = your_computation()
249 249 y = something_else()
250 250
251 251 # This pushes x and y to the interactive prompt immediately, even
252 252 # if this routine crashes on the next line after:
253 253 ip.to_user_ns('x y')
254 254 ...
255 255 # return
256 256
257 257 If you need to rename variables, just use ip.user_ns with dict
258 258 and update:
259 259
260 260 # exposes variables 'foo' as 'x' and 'bar' as 'y' in IPython
261 261 # user namespace
262 262 ip.user_ns.update(dict(x=foo,y=bar))
263 263 """
264 264
265 265 # print 'vars given:',vars # dbg
266 266 # Get the caller's frame to evaluate the given names in
267 267 cf = sys._getframe(1)
268 268
269 269 user_ns = self.user_ns
270 270
271 271 for name in vars.split():
272 272 try:
273 273 user_ns[name] = eval(name,cf.f_globals,cf.f_locals)
274 274 except:
275 275 error('could not get var. %s from %s' %
276 276 (name,cf.f_code.co_name))
277 277
278 def expand_alias(self,line):
279 """ Expand an alias in the command line
280
281 Returns the provided command line, possibly with the first word
282 (command) translated according to alias expansion rules.
283
284 [ipython]|16> _ip.expand_aliases("np myfile.txt")
285 <16> 'q:/opt/np/notepad++.exe myfile.txt'
286 """
287
288 pre,fn,rest = self.IP.split_user_input(line)
289 res = pre + self.IP.expand_aliases(fn,rest)
290
291
292
278 293 def launch_new_instance(user_ns = None):
279 294 """ Make and start a new ipython instance.
280 295
281 296 This can be called even without having an already initialized
282 297 ipython session running.
283 298
284 299 This is also used as the egg entry point for the 'ipython' script.
285 300
286 301 """
287 302 ses = make_session(user_ns)
288 303 ses.mainloop()
289 304
290 305
291 306 def make_user_ns(user_ns = None):
292 307 """Return a valid user interactive namespace.
293 308
294 309 This builds a dict with the minimal information needed to operate as a
295 310 valid IPython user namespace, which you can pass to the various embedding
296 311 classes in ipython.
297 312 """
298 313
299 314 if user_ns is None:
300 315 # Set __name__ to __main__ to better match the behavior of the
301 316 # normal interpreter.
302 317 user_ns = {'__name__' :'__main__',
303 318 '__builtins__' : __builtin__,
304 319 }
305 320 else:
306 321 user_ns.setdefault('__name__','__main__')
307 322 user_ns.setdefault('__builtins__',__builtin__)
308 323
309 324 return user_ns
310 325
311 326
312 327 def make_user_global_ns(ns = None):
313 328 """Return a valid user global namespace.
314 329
315 330 Similar to make_user_ns(), but global namespaces are really only needed in
316 331 embedded applications, where there is a distinction between the user's
317 332 interactive namespace and the global one where ipython is running."""
318 333
319 334 if ns is None: ns = {}
320 335 return ns
321 336
322 337
323 338 def make_session(user_ns = None):
324 339 """Makes, but does not launch an IPython session.
325 340
326 341 Later on you can call obj.mainloop() on the returned object.
327 342
328 343 Inputs:
329 344
330 345 - user_ns(None): a dict to be used as the user's namespace with initial
331 346 data.
332 347
333 348 WARNING: This should *not* be run when a session exists already."""
334 349
335 350 import IPython
336 351 return IPython.Shell.start(user_ns)
@@ -1,755 +1,755 b''
1 1 # -*- coding: utf-8 -*-
2 2 """
3 3 IPython -- An enhanced Interactive Python
4 4
5 5 Requires Python 2.1 or better.
6 6
7 7 This file contains the main make_IPython() starter function.
8 8
9 $Id: ipmaker.py 1979 2006-12-12 18:50:20Z vivainio $"""
9 $Id: ipmaker.py 2012 2006-12-24 10:28:29Z vivainio $"""
10 10
11 11 #*****************************************************************************
12 12 # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
13 13 #
14 14 # Distributed under the terms of the BSD License. The full license is in
15 15 # the file COPYING, distributed as part of this software.
16 16 #*****************************************************************************
17 17
18 18 from IPython import Release
19 19 __author__ = '%s <%s>' % Release.authors['Fernando']
20 20 __license__ = Release.license
21 21 __version__ = Release.version
22 22
23 23 credits._Printer__data = """
24 24 Python: %s
25 25
26 26 IPython: Fernando Perez, Janko Hauser, Nathan Gray, and many users.
27 27 See http://ipython.scipy.org for more information.""" \
28 28 % credits._Printer__data
29 29
30 30 copyright._Printer__data += """
31 31
32 32 Copyright (c) 2001-2004 Fernando Perez, Janko Hauser, Nathan Gray.
33 33 All Rights Reserved."""
34 34
35 35 #****************************************************************************
36 36 # Required modules
37 37
38 38 # From the standard library
39 39 import __main__
40 40 import __builtin__
41 41 import os
42 42 import re
43 43 import sys
44 44 import types
45 45 from pprint import pprint,pformat
46 46
47 47 # Our own
48 48 from IPython import DPyGetOpt
49 49 from IPython.ipstruct import Struct
50 50 from IPython.OutputTrap import OutputTrap
51 51 from IPython.ConfigLoader import ConfigLoader
52 52 from IPython.iplib import InteractiveShell
53 53 from IPython.usage import cmd_line_usage,interactive_usage
54 54 from IPython.genutils import *
55 55
56 56 #-----------------------------------------------------------------------------
57 57 def make_IPython(argv=None,user_ns=None,user_global_ns=None,debug=1,
58 58 rc_override=None,shell_class=InteractiveShell,
59 59 embedded=False,**kw):
60 60 """This is a dump of IPython into a single function.
61 61
62 62 Later it will have to be broken up in a sensible manner.
63 63
64 64 Arguments:
65 65
66 66 - argv: a list similar to sys.argv[1:]. It should NOT contain the desired
67 67 script name, b/c DPyGetOpt strips the first argument only for the real
68 68 sys.argv.
69 69
70 70 - user_ns: a dict to be used as the user's namespace."""
71 71
72 72 #----------------------------------------------------------------------
73 73 # Defaults and initialization
74 74
75 75 # For developer debugging, deactivates crash handler and uses pdb.
76 76 DEVDEBUG = False
77 77
78 78 if argv is None:
79 79 argv = sys.argv
80 80
81 81 # __IP is the main global that lives throughout and represents the whole
82 82 # application. If the user redefines it, all bets are off as to what
83 83 # happens.
84 84
85 85 # __IP is the name of he global which the caller will have accessible as
86 86 # __IP.name. We set its name via the first parameter passed to
87 87 # InteractiveShell:
88 88
89 89 IP = shell_class('__IP',user_ns=user_ns,user_global_ns=user_global_ns,
90 90 embedded=embedded,**kw)
91 91
92 92 # Put 'help' in the user namespace
93 93 from site import _Helper
94 94 IP.user_ns['help'] = _Helper()
95 95
96 96
97 97 if DEVDEBUG:
98 98 # For developer debugging only (global flag)
99 99 from IPython import ultraTB
100 100 sys.excepthook = ultraTB.VerboseTB(call_pdb=1)
101 101
102 102 IP.BANNER_PARTS = ['Python %s\n'
103 103 'Type "copyright", "credits" or "license" '
104 104 'for more information.\n'
105 105 % (sys.version.split('\n')[0],),
106 106 "IPython %s -- An enhanced Interactive Python."
107 107 % (__version__,),
108 108 """? -> Introduction to IPython's features.
109 109 %magic -> Information about IPython's 'magic' % functions.
110 110 help -> Python's own help system.
111 111 object? -> Details about 'object'. ?object also works, ?? prints more.
112 112 """ ]
113 113
114 114 IP.usage = interactive_usage
115 115
116 116 # Platform-dependent suffix and directory names. We use _ipython instead
117 117 # of .ipython under win32 b/c there's software that breaks with .named
118 118 # directories on that platform.
119 119 if os.name == 'posix':
120 120 rc_suffix = ''
121 121 ipdir_def = '.ipython'
122 122 else:
123 123 rc_suffix = '.ini'
124 124 ipdir_def = '_ipython'
125 125
126 126 # default directory for configuration
127 127 ipythondir_def = os.path.abspath(os.environ.get('IPYTHONDIR',
128 128 os.path.join(IP.home_dir,ipdir_def)))
129 129
130 130 sys.path.insert(0, '') # add . to sys.path. Fix from Prabhu Ramachandran
131 131
132 132 # we need the directory where IPython itself is installed
133 133 import IPython
134 134 IPython_dir = os.path.dirname(IPython.__file__)
135 135 del IPython
136 136
137 137 #-------------------------------------------------------------------------
138 138 # Command line handling
139 139
140 140 # Valid command line options (uses DPyGetOpt syntax, like Perl's
141 141 # GetOpt::Long)
142 142
143 143 # Any key not listed here gets deleted even if in the file (like session
144 144 # or profile). That's deliberate, to maintain the rc namespace clean.
145 145
146 146 # Each set of options appears twice: under _conv only the names are
147 147 # listed, indicating which type they must be converted to when reading the
148 148 # ipythonrc file. And under DPyGetOpt they are listed with the regular
149 149 # DPyGetOpt syntax (=s,=i,:f,etc).
150 150
151 151 # Make sure there's a space before each end of line (they get auto-joined!)
152 152 cmdline_opts = ('autocall=i autoindent! automagic! banner! cache_size|cs=i '
153 153 'c=s classic|cl color_info! colors=s confirm_exit! '
154 154 'debug! deep_reload! editor=s log|l messages! nosep '
155 155 'object_info_string_level=i pdb! '
156 156 'pprint! prompt_in1|pi1=s prompt_in2|pi2=s prompt_out|po=s '
157 157 'quick screen_length|sl=i prompts_pad_left=i '
158 158 'logfile|lf=s logplay|lp=s profile|p=s '
159 159 'readline! readline_merge_completions! '
160 160 'readline_omit__names! '
161 161 'rcfile=s separate_in|si=s separate_out|so=s '
162 162 'separate_out2|so2=s xmode=s wildcards_case_sensitive! '
163 163 'magic_docstrings system_verbose! '
164 164 'multi_line_specials! '
165 165 'wxversion=s '
166 166 'autoedit_syntax!')
167 167
168 168 # Options that can *only* appear at the cmd line (not in rcfiles).
169 169
170 170 # The "ignore" option is a kludge so that Emacs buffers don't crash, since
171 171 # the 'C-c !' command in emacs automatically appends a -i option at the end.
172 172 cmdline_only = ('help ignore|i ipythondir=s Version upgrade '
173 173 'gthread! qthread! q4thread! wthread! pylab! tk!')
174 174
175 175 # Build the actual name list to be used by DPyGetOpt
176 176 opts_names = qw(cmdline_opts) + qw(cmdline_only)
177 177
178 178 # Set sensible command line defaults.
179 179 # This should have everything from cmdline_opts and cmdline_only
180 180 opts_def = Struct(autocall = 1,
181 181 autoedit_syntax = 0,
182 182 autoindent = 0,
183 183 automagic = 1,
184 184 banner = 1,
185 185 cache_size = 1000,
186 186 c = '',
187 187 classic = 0,
188 188 colors = 'NoColor',
189 189 color_info = 0,
190 190 confirm_exit = 1,
191 191 debug = 0,
192 192 deep_reload = 0,
193 193 editor = '0',
194 194 help = 0,
195 195 ignore = 0,
196 196 ipythondir = ipythondir_def,
197 197 log = 0,
198 198 logfile = '',
199 199 logplay = '',
200 200 multi_line_specials = 1,
201 201 messages = 1,
202 202 object_info_string_level = 0,
203 203 nosep = 0,
204 204 pdb = 0,
205 205 pprint = 0,
206 206 profile = '',
207 207 prompt_in1 = 'In [\\#]: ',
208 208 prompt_in2 = ' .\\D.: ',
209 209 prompt_out = 'Out[\\#]: ',
210 210 prompts_pad_left = 1,
211 211 quiet = 0,
212 212 quick = 0,
213 213 readline = 1,
214 214 readline_merge_completions = 1,
215 215 readline_omit__names = 0,
216 216 rcfile = 'ipythonrc' + rc_suffix,
217 217 screen_length = 0,
218 218 separate_in = '\n',
219 219 separate_out = '\n',
220 220 separate_out2 = '',
221 221 system_header = 'IPython system call: ',
222 222 system_verbose = 0,
223 223 gthread = 0,
224 224 qthread = 0,
225 225 q4thread = 0,
226 226 wthread = 0,
227 227 pylab = 0,
228 228 tk = 0,
229 229 upgrade = 0,
230 230 Version = 0,
231 231 xmode = 'Verbose',
232 232 wildcards_case_sensitive = 1,
233 233 wxversion = '0',
234 234 magic_docstrings = 0, # undocumented, for doc generation
235 235 )
236 236
237 237 # Things that will *only* appear in rcfiles (not at the command line).
238 238 # Make sure there's a space before each end of line (they get auto-joined!)
239 239 rcfile_opts = { qwflat: 'include import_mod import_all execfile ',
240 240 qw_lol: 'import_some ',
241 241 # for things with embedded whitespace:
242 242 list_strings:'execute alias readline_parse_and_bind ',
243 243 # Regular strings need no conversion:
244 244 None:'readline_remove_delims ',
245 245 }
246 246 # Default values for these
247 247 rc_def = Struct(include = [],
248 248 import_mod = [],
249 249 import_all = [],
250 250 import_some = [[]],
251 251 execute = [],
252 252 execfile = [],
253 253 alias = [],
254 254 readline_parse_and_bind = [],
255 255 readline_remove_delims = '',
256 256 )
257 257
258 258 # Build the type conversion dictionary from the above tables:
259 259 typeconv = rcfile_opts.copy()
260 260 typeconv.update(optstr2types(cmdline_opts))
261 261
262 262 # FIXME: the None key appears in both, put that back together by hand. Ugly!
263 263 typeconv[None] += ' ' + rcfile_opts[None]
264 264
265 265 # Remove quotes at ends of all strings (used to protect spaces)
266 266 typeconv[unquote_ends] = typeconv[None]
267 267 del typeconv[None]
268 268
269 269 # Build the list we'll use to make all config decisions with defaults:
270 270 opts_all = opts_def.copy()
271 271 opts_all.update(rc_def)
272 272
273 273 # Build conflict resolver for recursive loading of config files:
274 274 # - preserve means the outermost file maintains the value, it is not
275 275 # overwritten if an included file has the same key.
276 276 # - add_flip applies + to the two values, so it better make sense to add
277 277 # those types of keys. But it flips them first so that things loaded
278 278 # deeper in the inclusion chain have lower precedence.
279 279 conflict = {'preserve': ' '.join([ typeconv[int],
280 280 typeconv[unquote_ends] ]),
281 281 'add_flip': ' '.join([ typeconv[qwflat],
282 282 typeconv[qw_lol],
283 283 typeconv[list_strings] ])
284 284 }
285 285
286 286 # Now actually process the command line
287 287 getopt = DPyGetOpt.DPyGetOpt()
288 288 getopt.setIgnoreCase(0)
289 289
290 290 getopt.parseConfiguration(opts_names)
291 291
292 292 try:
293 293 getopt.processArguments(argv)
294 294 except:
295 295 print cmd_line_usage
296 296 warn('\nError in Arguments: ' + `sys.exc_value`)
297 297 sys.exit(1)
298 298
299 299 # convert the options dict to a struct for much lighter syntax later
300 300 opts = Struct(getopt.optionValues)
301 301 args = getopt.freeValues
302 302
303 303 # this is the struct (which has default values at this point) with which
304 304 # we make all decisions:
305 305 opts_all.update(opts)
306 306
307 307 # Options that force an immediate exit
308 308 if opts_all.help:
309 309 page(cmd_line_usage)
310 310 sys.exit()
311 311
312 312 if opts_all.Version:
313 313 print __version__
314 314 sys.exit()
315 315
316 316 if opts_all.magic_docstrings:
317 317 IP.magic_magic('-latex')
318 318 sys.exit()
319 319
320 320 # add personal ipythondir to sys.path so that users can put things in
321 321 # there for customization
322 322 sys.path.append(os.path.abspath(opts_all.ipythondir))
323 323
324 324 # Create user config directory if it doesn't exist. This must be done
325 325 # *after* getting the cmd line options.
326 326 if not os.path.isdir(opts_all.ipythondir):
327 327 IP.user_setup(opts_all.ipythondir,rc_suffix,'install')
328 328
329 329 # upgrade user config files while preserving a copy of the originals
330 330 if opts_all.upgrade:
331 331 IP.user_setup(opts_all.ipythondir,rc_suffix,'upgrade')
332 332
333 333 # check mutually exclusive options in the *original* command line
334 334 mutex_opts(opts,[qw('log logfile'),qw('rcfile profile'),
335 335 qw('classic profile'),qw('classic rcfile')])
336 336
337 337 #---------------------------------------------------------------------------
338 338 # Log replay
339 339
340 340 # if -logplay, we need to 'become' the other session. That basically means
341 341 # replacing the current command line environment with that of the old
342 342 # session and moving on.
343 343
344 344 # this is needed so that later we know we're in session reload mode, as
345 345 # opts_all will get overwritten:
346 346 load_logplay = 0
347 347
348 348 if opts_all.logplay:
349 349 load_logplay = opts_all.logplay
350 350 opts_debug_save = opts_all.debug
351 351 try:
352 352 logplay = open(opts_all.logplay)
353 353 except IOError:
354 354 if opts_all.debug: IP.InteractiveTB()
355 355 warn('Could not open logplay file '+`opts_all.logplay`)
356 356 # restore state as if nothing had happened and move on, but make
357 357 # sure that later we don't try to actually load the session file
358 358 logplay = None
359 359 load_logplay = 0
360 360 del opts_all.logplay
361 361 else:
362 362 try:
363 363 logplay.readline()
364 364 logplay.readline();
365 365 # this reloads that session's command line
366 366 cmd = logplay.readline()[6:]
367 367 exec cmd
368 368 # restore the true debug flag given so that the process of
369 369 # session loading itself can be monitored.
370 370 opts.debug = opts_debug_save
371 371 # save the logplay flag so later we don't overwrite the log
372 372 opts.logplay = load_logplay
373 373 # now we must update our own structure with defaults
374 374 opts_all.update(opts)
375 375 # now load args
376 376 cmd = logplay.readline()[6:]
377 377 exec cmd
378 378 logplay.close()
379 379 except:
380 380 logplay.close()
381 381 if opts_all.debug: IP.InteractiveTB()
382 382 warn("Logplay file lacking full configuration information.\n"
383 383 "I'll try to read it, but some things may not work.")
384 384
385 385 #-------------------------------------------------------------------------
386 386 # set up output traps: catch all output from files, being run, modules
387 387 # loaded, etc. Then give it to the user in a clean form at the end.
388 388
389 389 msg_out = 'Output messages. '
390 390 msg_err = 'Error messages. '
391 391 msg_sep = '\n'
392 392 msg = Struct(config = OutputTrap('Configuration Loader',msg_out,
393 393 msg_err,msg_sep,debug,
394 394 quiet_out=1),
395 395 user_exec = OutputTrap('User File Execution',msg_out,
396 396 msg_err,msg_sep,debug),
397 397 logplay = OutputTrap('Log Loader',msg_out,
398 398 msg_err,msg_sep,debug),
399 399 summary = ''
400 400 )
401 401
402 402 #-------------------------------------------------------------------------
403 403 # Process user ipythonrc-type configuration files
404 404
405 405 # turn on output trapping and log to msg.config
406 406 # remember that with debug on, trapping is actually disabled
407 407 msg.config.trap_all()
408 408
409 409 # look for rcfile in current or default directory
410 410 try:
411 411 opts_all.rcfile = filefind(opts_all.rcfile,opts_all.ipythondir)
412 412 except IOError:
413 413 if opts_all.debug: IP.InteractiveTB()
414 414 warn('Configuration file %s not found. Ignoring request.'
415 415 % (opts_all.rcfile) )
416 416
417 417 # 'profiles' are a shorthand notation for config filenames
418 418 if opts_all.profile:
419 419
420 420 try:
421 421 opts_all.rcfile = filefind('ipythonrc-' + opts_all.profile
422 422 + rc_suffix,
423 423 opts_all.ipythondir)
424 424 except IOError:
425 425 if opts_all.debug: IP.InteractiveTB()
426 426 opts.profile = '' # remove profile from options if invalid
427 427 # We won't warn anymore, primary method is ipy_profile_PROFNAME
428 428 # which does trigger a warning.
429 429
430 430 # load the config file
431 431 rcfiledata = None
432 432 if opts_all.quick:
433 433 print 'Launching IPython in quick mode. No config file read.'
434 434 elif opts_all.classic:
435 435 print 'Launching IPython in classic mode. No config file read.'
436 436 elif opts_all.rcfile:
437 437 try:
438 438 cfg_loader = ConfigLoader(conflict)
439 439 rcfiledata = cfg_loader.load(opts_all.rcfile,typeconv,
440 440 'include',opts_all.ipythondir,
441 441 purge = 1,
442 442 unique = conflict['preserve'])
443 443 except:
444 444 IP.InteractiveTB()
445 445 warn('Problems loading configuration file '+
446 446 `opts_all.rcfile`+
447 447 '\nStarting with default -bare bones- configuration.')
448 448 else:
449 449 warn('No valid configuration file found in either currrent directory\n'+
450 450 'or in the IPython config. directory: '+`opts_all.ipythondir`+
451 451 '\nProceeding with internal defaults.')
452 452
453 453 #------------------------------------------------------------------------
454 454 # Set exception handlers in mode requested by user.
455 455 otrap = OutputTrap(trap_out=1) # trap messages from magic_xmode
456 456 IP.magic_xmode(opts_all.xmode)
457 457 otrap.release_out()
458 458
459 459 #------------------------------------------------------------------------
460 460 # Execute user config
461 461
462 462 # Create a valid config structure with the right precedence order:
463 463 # defaults < rcfile < command line. This needs to be in the instance, so
464 464 # that method calls below that rely on it find it.
465 465 IP.rc = rc_def.copy()
466 466
467 467 # Work with a local alias inside this routine to avoid unnecessary
468 468 # attribute lookups.
469 469 IP_rc = IP.rc
470 470
471 471 IP_rc.update(opts_def)
472 472 if rcfiledata:
473 473 # now we can update
474 474 IP_rc.update(rcfiledata)
475 475 IP_rc.update(opts)
476 476 IP_rc.update(rc_override)
477 477
478 478 # Store the original cmd line for reference:
479 479 IP_rc.opts = opts
480 480 IP_rc.args = args
481 481
482 482 # create a *runtime* Struct like rc for holding parameters which may be
483 483 # created and/or modified by runtime user extensions.
484 484 IP.runtime_rc = Struct()
485 485
486 486 # from this point on, all config should be handled through IP_rc,
487 487 # opts* shouldn't be used anymore.
488 488
489 489
490 490 # update IP_rc with some special things that need manual
491 491 # tweaks. Basically options which affect other options. I guess this
492 492 # should just be written so that options are fully orthogonal and we
493 493 # wouldn't worry about this stuff!
494 494
495 495 if IP_rc.classic:
496 496 IP_rc.quick = 1
497 497 IP_rc.cache_size = 0
498 498 IP_rc.pprint = 0
499 499 IP_rc.prompt_in1 = '>>> '
500 500 IP_rc.prompt_in2 = '... '
501 501 IP_rc.prompt_out = ''
502 502 IP_rc.separate_in = IP_rc.separate_out = IP_rc.separate_out2 = '0'
503 503 IP_rc.colors = 'NoColor'
504 504 IP_rc.xmode = 'Plain'
505 505
506 506 IP.pre_config_initialization()
507 507 # configure readline
508 508 # Define the history file for saving commands in between sessions
509 509 if IP_rc.profile:
510 510 histfname = 'history-%s' % IP_rc.profile
511 511 else:
512 512 histfname = 'history'
513 513 IP.histfile = os.path.join(opts_all.ipythondir,histfname)
514 514
515 515 # update exception handlers with rc file status
516 516 otrap.trap_out() # I don't want these messages ever.
517 517 IP.magic_xmode(IP_rc.xmode)
518 518 otrap.release_out()
519 519
520 520 # activate logging if requested and not reloading a log
521 521 if IP_rc.logplay:
522 522 IP.magic_logstart(IP_rc.logplay + ' append')
523 523 elif IP_rc.logfile:
524 524 IP.magic_logstart(IP_rc.logfile)
525 525 elif IP_rc.log:
526 526 IP.magic_logstart()
527 527
528 528 # find user editor so that it we don't have to look it up constantly
529 529 if IP_rc.editor.strip()=='0':
530 530 try:
531 531 ed = os.environ['EDITOR']
532 532 except KeyError:
533 533 if os.name == 'posix':
534 534 ed = 'vi' # the only one guaranteed to be there!
535 535 else:
536 536 ed = 'notepad' # same in Windows!
537 537 IP_rc.editor = ed
538 538
539 539 # Keep track of whether this is an embedded instance or not (useful for
540 540 # post-mortems).
541 541 IP_rc.embedded = IP.embedded
542 542
543 543 # Recursive reload
544 544 try:
545 545 from IPython import deep_reload
546 546 if IP_rc.deep_reload:
547 547 __builtin__.reload = deep_reload.reload
548 548 else:
549 549 __builtin__.dreload = deep_reload.reload
550 550 del deep_reload
551 551 except ImportError:
552 552 pass
553 553
554 554 # Save the current state of our namespace so that the interactive shell
555 555 # can later know which variables have been created by us from config files
556 556 # and loading. This way, loading a file (in any way) is treated just like
557 557 # defining things on the command line, and %who works as expected.
558 558
559 559 # DON'T do anything that affects the namespace beyond this point!
560 560 IP.internal_ns.update(__main__.__dict__)
561 561
562 562 #IP.internal_ns.update(locals()) # so our stuff doesn't show up in %who
563 563
564 564 # Now run through the different sections of the users's config
565 565 if IP_rc.debug:
566 566 print 'Trying to execute the following configuration structure:'
567 567 print '(Things listed first are deeper in the inclusion tree and get'
568 568 print 'loaded first).\n'
569 569 pprint(IP_rc.__dict__)
570 570
571 571 for mod in IP_rc.import_mod:
572 572 try:
573 573 exec 'import '+mod in IP.user_ns
574 574 except :
575 575 IP.InteractiveTB()
576 576 import_fail_info(mod)
577 577
578 578 for mod_fn in IP_rc.import_some:
579 579 if not mod_fn == []:
580 580 mod,fn = mod_fn[0],','.join(mod_fn[1:])
581 581 try:
582 582 exec 'from '+mod+' import '+fn in IP.user_ns
583 583 except :
584 584 IP.InteractiveTB()
585 585 import_fail_info(mod,fn)
586 586
587 587 for mod in IP_rc.import_all:
588 588 try:
589 589 exec 'from '+mod+' import *' in IP.user_ns
590 590 except :
591 591 IP.InteractiveTB()
592 592 import_fail_info(mod)
593 593
594 594 for code in IP_rc.execute:
595 595 try:
596 596 exec code in IP.user_ns
597 597 except:
598 598 IP.InteractiveTB()
599 599 warn('Failure executing code: ' + `code`)
600 600
601 601 # Execute the files the user wants in ipythonrc
602 602 for file in IP_rc.execfile:
603 603 try:
604 604 file = filefind(file,sys.path+[IPython_dir])
605 605 except IOError:
606 606 warn(itpl('File $file not found. Skipping it.'))
607 607 else:
608 608 IP.safe_execfile(os.path.expanduser(file),IP.user_ns)
609 609
610 610 # finally, try importing ipy_*_conf for final configuration
611 611 try:
612 612 import ipy_system_conf
613 613 except ImportError:
614 614 if opts_all.debug: IP.InteractiveTB()
615 615 warn("Could not import 'ipy_system_conf'")
616 616 except:
617 617 IP.InteractiveTB()
618 618 import_fail_info('ipy_system_conf')
619 619
620 620 if opts_all.profile:
621 621 profmodname = 'ipy_profile_' + opts_all.profile
622 622 try:
623 623 __import__(profmodname)
624 624 except ImportError:
625 625 # only warn if ipythonrc-PROFNAME didn't exist
626 626 if opts.profile =='':
627 627 warn("Could not start with profile '%s'!\n"
628 628 "('%s/%s.py' does not exist? run '%%upgrade')" %
629 629 (opts_all.profile, opts_all.ipythondir, profmodname) )
630 except:
631 print "Error importing",profmodname
630 except:
631 print "Error importing",profmodname,"- perhaps you should run %upgrade?"
632 632 IP.InteractiveTB()
633 633 import_fail_info(profmodname)
634 634
635 635 try:
636 636 import ipy_user_conf
637 637 except ImportError:
638 638 if opts_all.debug: IP.InteractiveTB()
639 639 warn("Could not import user config!\n "
640 640 "('%s/ipy_user_conf.py' does not exist? Please run '%%upgrade')\n"
641 641 % opts_all.ipythondir)
642 642 except:
643 print "Error importing ipy_user_conf"
643 print "Error importing ipy_user_conf - perhaps you should run %upgrade?"
644 644 IP.InteractiveTB()
645 645 import_fail_info("ipy_user_conf")
646 646
647 647 # release stdout and stderr and save config log into a global summary
648 648 msg.config.release_all()
649 649 if IP_rc.messages:
650 650 msg.summary += msg.config.summary_all()
651 651
652 652 #------------------------------------------------------------------------
653 653 # Setup interactive session
654 654
655 655 # Now we should be fully configured. We can then execute files or load
656 656 # things only needed for interactive use. Then we'll open the shell.
657 657
658 658 # Take a snapshot of the user namespace before opening the shell. That way
659 659 # we'll be able to identify which things were interactively defined and
660 660 # which were defined through config files.
661 661 IP.user_config_ns = IP.user_ns.copy()
662 662
663 663 # Force reading a file as if it were a session log. Slower but safer.
664 664 if load_logplay:
665 665 print 'Replaying log...'
666 666 try:
667 667 if IP_rc.debug:
668 668 logplay_quiet = 0
669 669 else:
670 670 logplay_quiet = 1
671 671
672 672 msg.logplay.trap_all()
673 673 IP.safe_execfile(load_logplay,IP.user_ns,
674 674 islog = 1, quiet = logplay_quiet)
675 675 msg.logplay.release_all()
676 676 if IP_rc.messages:
677 677 msg.summary += msg.logplay.summary_all()
678 678 except:
679 679 warn('Problems replaying logfile %s.' % load_logplay)
680 680 IP.InteractiveTB()
681 681
682 682 # Load remaining files in command line
683 683 msg.user_exec.trap_all()
684 684
685 685 # Do NOT execute files named in the command line as scripts to be loaded
686 686 # by embedded instances. Doing so has the potential for an infinite
687 687 # recursion if there are exceptions thrown in the process.
688 688
689 689 # XXX FIXME: the execution of user files should be moved out to after
690 690 # ipython is fully initialized, just as if they were run via %run at the
691 691 # ipython prompt. This would also give them the benefit of ipython's
692 692 # nice tracebacks.
693 693
694 694 if (not embedded and IP_rc.args and
695 695 not IP_rc.args[0].lower().endswith('.ipy')):
696 696 name_save = IP.user_ns['__name__']
697 697 IP.user_ns['__name__'] = '__main__'
698 698 # Set our own excepthook in case the user code tries to call it
699 699 # directly. This prevents triggering the IPython crash handler.
700 700 old_excepthook,sys.excepthook = sys.excepthook, IP.excepthook
701 701
702 702 save_argv = sys.argv[1:] # save it for later restoring
703 703
704 704 sys.argv = args
705 705
706 706 try:
707 707 IP.safe_execfile(args[0], IP.user_ns)
708 708 finally:
709 709 # Reset our crash handler in place
710 710 sys.excepthook = old_excepthook
711 711 sys.argv[:] = save_argv
712 712 IP.user_ns['__name__'] = name_save
713 713
714 714 msg.user_exec.release_all()
715 715
716 716 if IP_rc.messages:
717 717 msg.summary += msg.user_exec.summary_all()
718 718
719 719 # since we can't specify a null string on the cmd line, 0 is the equivalent:
720 720 if IP_rc.nosep:
721 721 IP_rc.separate_in = IP_rc.separate_out = IP_rc.separate_out2 = '0'
722 722 if IP_rc.separate_in == '0': IP_rc.separate_in = ''
723 723 if IP_rc.separate_out == '0': IP_rc.separate_out = ''
724 724 if IP_rc.separate_out2 == '0': IP_rc.separate_out2 = ''
725 725 IP_rc.separate_in = IP_rc.separate_in.replace('\\n','\n')
726 726 IP_rc.separate_out = IP_rc.separate_out.replace('\\n','\n')
727 727 IP_rc.separate_out2 = IP_rc.separate_out2.replace('\\n','\n')
728 728
729 729 # Determine how many lines at the bottom of the screen are needed for
730 730 # showing prompts, so we can know wheter long strings are to be printed or
731 731 # paged:
732 732 num_lines_bot = IP_rc.separate_in.count('\n')+1
733 733 IP_rc.screen_length = IP_rc.screen_length - num_lines_bot
734 734
735 735 # configure startup banner
736 736 if IP_rc.c: # regular python doesn't print the banner with -c
737 737 IP_rc.banner = 0
738 738 if IP_rc.banner:
739 739 BANN_P = IP.BANNER_PARTS
740 740 else:
741 741 BANN_P = []
742 742
743 743 if IP_rc.profile: BANN_P.append('IPython profile: %s\n' % IP_rc.profile)
744 744
745 745 # add message log (possibly empty)
746 746 if msg.summary: BANN_P.append(msg.summary)
747 747 # Final banner is a string
748 748 IP.BANNER = '\n'.join(BANN_P)
749 749
750 750 # Finalize the IPython instance. This assumes the rc structure is fully
751 751 # in place.
752 752 IP.post_config_initialization()
753 753
754 754 return IP
755 755 #************************ end of file <ipmaker.py> **************************
1 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