Show More
@@ -0,0 +1,6 b'' | |||
|
1 | #!/usr/bin/env python | |
|
2 | # encoding: utf-8 | |
|
3 | ||
|
4 | def test_import_backgroundjobs(): | |
|
5 | from IPython.lib import backgroundjobs | |
|
6 |
@@ -0,0 +1,6 b'' | |||
|
1 | #!/usr/bin/env python | |
|
2 | # encoding: utf-8 | |
|
3 | ||
|
4 | def test_import_coloransi(): | |
|
5 | from IPython.utils import coloransi | |
|
6 |
@@ -1,2862 +1,2862 b'' | |||
|
1 | 1 | # -*- coding: utf-8 -*- |
|
2 | 2 | """ |
|
3 | 3 | IPython -- An enhanced Interactive Python |
|
4 | 4 | |
|
5 | 5 | Requires Python 2.4 or newer. |
|
6 | 6 | |
|
7 | 7 | This file contains all the classes and helper functions specific to IPython. |
|
8 | 8 | """ |
|
9 | 9 | |
|
10 | 10 | #***************************************************************************** |
|
11 | 11 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and |
|
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 | # Note: this code originally subclassed code.InteractiveConsole from the |
|
18 | 18 | # Python standard library. Over time, all of that class has been copied |
|
19 | 19 | # verbatim here for modifications which could not be accomplished by |
|
20 | 20 | # subclassing. At this point, there are no dependencies at all on the code |
|
21 | 21 | # module anymore (it is not even imported). The Python License (sec. 2) |
|
22 | 22 | # allows for this, but it's always nice to acknowledge credit where credit is |
|
23 | 23 | # due. |
|
24 | 24 | #***************************************************************************** |
|
25 | 25 | |
|
26 | 26 | #**************************************************************************** |
|
27 | 27 | # Modules and globals |
|
28 | 28 | |
|
29 | 29 | # Python standard modules |
|
30 | 30 | import __main__ |
|
31 | 31 | import __builtin__ |
|
32 | 32 | import StringIO |
|
33 | 33 | import bdb |
|
34 | 34 | import codeop |
|
35 | 35 | import exceptions |
|
36 | 36 | import glob |
|
37 | 37 | import keyword |
|
38 | 38 | import new |
|
39 | 39 | import os |
|
40 | 40 | import re |
|
41 | 41 | import shutil |
|
42 | 42 | import string |
|
43 | 43 | import sys |
|
44 | 44 | import tempfile |
|
45 | 45 | |
|
46 | 46 | # IPython's own modules |
|
47 | 47 | #import IPython |
|
48 | 48 | from IPython import Debugger,OInspect,PyColorize,ultraTB |
|
49 | 49 | from IPython.Extensions import pickleshare |
|
50 | 50 | from IPython.FakeModule import FakeModule, init_fakemod_dict |
|
51 | 51 | from IPython.Itpl import ItplNS |
|
52 | 52 | from IPython.Logger import Logger |
|
53 | 53 | from IPython.Magic import Magic |
|
54 | 54 | from IPython.Prompts import CachedOutput |
|
55 | 55 | from IPython.ipstruct import Struct |
|
56 |
from IPython.background |
|
|
56 | from IPython.lib.backgroundjobs import BackgroundJobManager | |
|
57 | 57 | from IPython.genutils import * |
|
58 | 58 | from IPython.strdispatch import StrDispatch |
|
59 | 59 | import IPython.ipapi |
|
60 | 60 | import IPython.history |
|
61 | 61 | import IPython.prefilter as prefilter |
|
62 | 62 | import IPython.shadowns |
|
63 | 63 | # Globals |
|
64 | 64 | |
|
65 | 65 | # store the builtin raw_input globally, and use this always, in case user code |
|
66 | 66 | # overwrites it (like wx.py.PyShell does) |
|
67 | 67 | raw_input_original = raw_input |
|
68 | 68 | |
|
69 | 69 | # compiled regexps for autoindent management |
|
70 | 70 | dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass') |
|
71 | 71 | |
|
72 | 72 | |
|
73 | 73 | #**************************************************************************** |
|
74 | 74 | # Some utility function definitions |
|
75 | 75 | |
|
76 | 76 | ini_spaces_re = re.compile(r'^(\s+)') |
|
77 | 77 | |
|
78 | 78 | def num_ini_spaces(strng): |
|
79 | 79 | """Return the number of initial spaces in a string""" |
|
80 | 80 | |
|
81 | 81 | ini_spaces = ini_spaces_re.match(strng) |
|
82 | 82 | if ini_spaces: |
|
83 | 83 | return ini_spaces.end() |
|
84 | 84 | else: |
|
85 | 85 | return 0 |
|
86 | 86 | |
|
87 | 87 | def softspace(file, newvalue): |
|
88 | 88 | """Copied from code.py, to remove the dependency""" |
|
89 | 89 | |
|
90 | 90 | oldvalue = 0 |
|
91 | 91 | try: |
|
92 | 92 | oldvalue = file.softspace |
|
93 | 93 | except AttributeError: |
|
94 | 94 | pass |
|
95 | 95 | try: |
|
96 | 96 | file.softspace = newvalue |
|
97 | 97 | except (AttributeError, TypeError): |
|
98 | 98 | # "attribute-less object" or "read-only attributes" |
|
99 | 99 | pass |
|
100 | 100 | return oldvalue |
|
101 | 101 | |
|
102 | 102 | |
|
103 | 103 | def user_setup(ipythondir,rc_suffix,mode='install',interactive=True): |
|
104 | 104 | """Install or upgrade the user configuration directory. |
|
105 | 105 | |
|
106 | 106 | Can be called when running for the first time or to upgrade the user's |
|
107 | 107 | .ipython/ directory. |
|
108 | 108 | |
|
109 | 109 | Parameters |
|
110 | 110 | ---------- |
|
111 | 111 | ipythondir : path |
|
112 | 112 | The directory to be used for installation/upgrade. In 'install' mode, |
|
113 | 113 | if this path already exists, the function exits immediately. |
|
114 | 114 | |
|
115 | 115 | rc_suffix : str |
|
116 | 116 | Extension for the config files. On *nix platforms it is typically the |
|
117 | 117 | empty string, while Windows normally uses '.ini'. |
|
118 | 118 | |
|
119 | 119 | mode : str, optional |
|
120 | 120 | Valid modes are 'install' and 'upgrade'. |
|
121 | 121 | |
|
122 | 122 | interactive : bool, optional |
|
123 | 123 | If False, do not wait for user input on any errors. Normally after |
|
124 | 124 | printing its status information, this function waits for the user to |
|
125 | 125 | hit Return before proceeding. This is because the default use case is |
|
126 | 126 | when first installing the IPython configuration, so we want the user to |
|
127 | 127 | acknowledge the initial message, which contains some useful |
|
128 | 128 | information. |
|
129 | 129 | """ |
|
130 | 130 | |
|
131 | 131 | # For automatic use, deactivate all i/o |
|
132 | 132 | if interactive: |
|
133 | 133 | def wait(): |
|
134 | 134 | try: |
|
135 | 135 | raw_input("Please press <RETURN> to start IPython.") |
|
136 | 136 | except EOFError: |
|
137 | 137 | print >> Term.cout |
|
138 | 138 | print '*'*70 |
|
139 | 139 | |
|
140 | 140 | def printf(s): |
|
141 | 141 | print s |
|
142 | 142 | else: |
|
143 | 143 | wait = lambda : None |
|
144 | 144 | printf = lambda s : None |
|
145 | 145 | |
|
146 | 146 | # Install mode should be re-entrant: if the install dir already exists, |
|
147 | 147 | # bail out cleanly. |
|
148 | 148 | # XXX. This is too hasty to return. We need to check to make sure that |
|
149 | 149 | # all the expected config files and directories are actually there. We |
|
150 | 150 | # currently have a failure mode if someone deletes a needed config file |
|
151 | 151 | # but still has the ipythondir. |
|
152 | 152 | if mode == 'install' and os.path.isdir(ipythondir): |
|
153 | 153 | return |
|
154 | 154 | |
|
155 | 155 | cwd = os.getcwd() # remember where we started |
|
156 | 156 | glb = glob.glob |
|
157 | 157 | |
|
158 | 158 | printf('*'*70) |
|
159 | 159 | if mode == 'install': |
|
160 | 160 | printf( |
|
161 | 161 | """Welcome to IPython. I will try to create a personal configuration directory |
|
162 | 162 | where you can customize many aspects of IPython's functionality in:\n""") |
|
163 | 163 | else: |
|
164 | 164 | printf('I am going to upgrade your configuration in:') |
|
165 | 165 | |
|
166 | 166 | printf(ipythondir) |
|
167 | 167 | |
|
168 | 168 | rcdirend = os.path.join('IPython','UserConfig') |
|
169 | 169 | cfg = lambda d: os.path.join(d,rcdirend) |
|
170 | 170 | try: |
|
171 | 171 | rcdir = filter(os.path.isdir,map(cfg,sys.path))[0] |
|
172 | 172 | printf("Initializing from configuration: %s" % rcdir) |
|
173 | 173 | except IndexError: |
|
174 | 174 | warning = """ |
|
175 | 175 | Installation error. IPython's directory was not found. |
|
176 | 176 | |
|
177 | 177 | Check the following: |
|
178 | 178 | |
|
179 | 179 | The ipython/IPython directory should be in a directory belonging to your |
|
180 | 180 | PYTHONPATH environment variable (that is, it should be in a directory |
|
181 | 181 | belonging to sys.path). You can copy it explicitly there or just link to it. |
|
182 | 182 | |
|
183 | 183 | IPython will create a minimal default configuration for you. |
|
184 | 184 | |
|
185 | 185 | """ |
|
186 | 186 | warn(warning) |
|
187 | 187 | wait() |
|
188 | 188 | |
|
189 | 189 | if sys.platform =='win32': |
|
190 | 190 | inif = 'ipythonrc.ini' |
|
191 | 191 | else: |
|
192 | 192 | inif = 'ipythonrc' |
|
193 | 193 | minimal_setup = {'ipy_user_conf.py' : 'import ipy_defaults', |
|
194 | 194 | inif : '# intentionally left blank' } |
|
195 | 195 | os.makedirs(ipythondir, mode = 0777) |
|
196 | 196 | for f, cont in minimal_setup.items(): |
|
197 | 197 | # In 2.5, this can be more cleanly done using 'with' |
|
198 | 198 | fobj = file(ipythondir + '/' + f,'w') |
|
199 | 199 | fobj.write(cont) |
|
200 | 200 | fobj.close() |
|
201 | 201 | |
|
202 | 202 | return |
|
203 | 203 | |
|
204 | 204 | if mode == 'install': |
|
205 | 205 | try: |
|
206 | 206 | shutil.copytree(rcdir,ipythondir) |
|
207 | 207 | os.chdir(ipythondir) |
|
208 | 208 | rc_files = glb("ipythonrc*") |
|
209 | 209 | for rc_file in rc_files: |
|
210 | 210 | os.rename(rc_file,rc_file+rc_suffix) |
|
211 | 211 | except: |
|
212 | 212 | warning = """ |
|
213 | 213 | |
|
214 | 214 | There was a problem with the installation: |
|
215 | 215 | %s |
|
216 | 216 | Try to correct it or contact the developers if you think it's a bug. |
|
217 | 217 | IPython will proceed with builtin defaults.""" % sys.exc_info()[1] |
|
218 | 218 | warn(warning) |
|
219 | 219 | wait() |
|
220 | 220 | return |
|
221 | 221 | |
|
222 | 222 | elif mode == 'upgrade': |
|
223 | 223 | try: |
|
224 | 224 | os.chdir(ipythondir) |
|
225 | 225 | except: |
|
226 | 226 | printf(""" |
|
227 | 227 | Can not upgrade: changing to directory %s failed. Details: |
|
228 | 228 | %s |
|
229 | 229 | """ % (ipythondir,sys.exc_info()[1]) ) |
|
230 | 230 | wait() |
|
231 | 231 | return |
|
232 | 232 | else: |
|
233 | 233 | sources = glb(os.path.join(rcdir,'[A-Za-z]*')) |
|
234 | 234 | for new_full_path in sources: |
|
235 | 235 | new_filename = os.path.basename(new_full_path) |
|
236 | 236 | if new_filename.startswith('ipythonrc'): |
|
237 | 237 | new_filename = new_filename + rc_suffix |
|
238 | 238 | # The config directory should only contain files, skip any |
|
239 | 239 | # directories which may be there (like CVS) |
|
240 | 240 | if os.path.isdir(new_full_path): |
|
241 | 241 | continue |
|
242 | 242 | if os.path.exists(new_filename): |
|
243 | 243 | old_file = new_filename+'.old' |
|
244 | 244 | if os.path.exists(old_file): |
|
245 | 245 | os.remove(old_file) |
|
246 | 246 | os.rename(new_filename,old_file) |
|
247 | 247 | shutil.copy(new_full_path,new_filename) |
|
248 | 248 | else: |
|
249 | 249 | raise ValueError('unrecognized mode for install: %r' % mode) |
|
250 | 250 | |
|
251 | 251 | # Fix line-endings to those native to each platform in the config |
|
252 | 252 | # directory. |
|
253 | 253 | try: |
|
254 | 254 | os.chdir(ipythondir) |
|
255 | 255 | except: |
|
256 | 256 | printf(""" |
|
257 | 257 | Problem: changing to directory %s failed. |
|
258 | 258 | Details: |
|
259 | 259 | %s |
|
260 | 260 | |
|
261 | 261 | Some configuration files may have incorrect line endings. This should not |
|
262 | 262 | cause any problems during execution. """ % (ipythondir,sys.exc_info()[1]) ) |
|
263 | 263 | wait() |
|
264 | 264 | else: |
|
265 | 265 | for fname in glb('ipythonrc*'): |
|
266 | 266 | try: |
|
267 | 267 | native_line_ends(fname,backup=0) |
|
268 | 268 | except IOError: |
|
269 | 269 | pass |
|
270 | 270 | |
|
271 | 271 | if mode == 'install': |
|
272 | 272 | printf(""" |
|
273 | 273 | Successful installation! |
|
274 | 274 | |
|
275 | 275 | Please read the sections 'Initial Configuration' and 'Quick Tips' in the |
|
276 | 276 | IPython manual (there are both HTML and PDF versions supplied with the |
|
277 | 277 | distribution) to make sure that your system environment is properly configured |
|
278 | 278 | to take advantage of IPython's features. |
|
279 | 279 | |
|
280 | 280 | Important note: the configuration system has changed! The old system is |
|
281 | 281 | still in place, but its setting may be partly overridden by the settings in |
|
282 | 282 | "~/.ipython/ipy_user_conf.py" config file. Please take a look at the file |
|
283 | 283 | if some of the new settings bother you. |
|
284 | 284 | |
|
285 | 285 | """) |
|
286 | 286 | else: |
|
287 | 287 | printf(""" |
|
288 | 288 | Successful upgrade! |
|
289 | 289 | |
|
290 | 290 | All files in your directory: |
|
291 | 291 | %(ipythondir)s |
|
292 | 292 | which would have been overwritten by the upgrade were backed up with a .old |
|
293 | 293 | extension. If you had made particular customizations in those files you may |
|
294 | 294 | want to merge them back into the new files.""" % locals() ) |
|
295 | 295 | wait() |
|
296 | 296 | os.chdir(cwd) |
|
297 | 297 | |
|
298 | 298 | #**************************************************************************** |
|
299 | 299 | # Local use exceptions |
|
300 | 300 | class SpaceInInput(exceptions.Exception): pass |
|
301 | 301 | |
|
302 | 302 | |
|
303 | 303 | #**************************************************************************** |
|
304 | 304 | # Local use classes |
|
305 | 305 | class Bunch: pass |
|
306 | 306 | |
|
307 | 307 | class Undefined: pass |
|
308 | 308 | |
|
309 | 309 | class Quitter(object): |
|
310 | 310 | """Simple class to handle exit, similar to Python 2.5's. |
|
311 | 311 | |
|
312 | 312 | It handles exiting in an ipython-safe manner, which the one in Python 2.5 |
|
313 | 313 | doesn't do (obviously, since it doesn't know about ipython).""" |
|
314 | 314 | |
|
315 | 315 | def __init__(self,shell,name): |
|
316 | 316 | self.shell = shell |
|
317 | 317 | self.name = name |
|
318 | 318 | |
|
319 | 319 | def __repr__(self): |
|
320 | 320 | return 'Type %s() to exit.' % self.name |
|
321 | 321 | __str__ = __repr__ |
|
322 | 322 | |
|
323 | 323 | def __call__(self): |
|
324 | 324 | self.shell.exit() |
|
325 | 325 | |
|
326 | 326 | class InputList(list): |
|
327 | 327 | """Class to store user input. |
|
328 | 328 | |
|
329 | 329 | It's basically a list, but slices return a string instead of a list, thus |
|
330 | 330 | allowing things like (assuming 'In' is an instance): |
|
331 | 331 | |
|
332 | 332 | exec In[4:7] |
|
333 | 333 | |
|
334 | 334 | or |
|
335 | 335 | |
|
336 | 336 | exec In[5:9] + In[14] + In[21:25]""" |
|
337 | 337 | |
|
338 | 338 | def __getslice__(self,i,j): |
|
339 | 339 | return ''.join(list.__getslice__(self,i,j)) |
|
340 | 340 | |
|
341 | 341 | class SyntaxTB(ultraTB.ListTB): |
|
342 | 342 | """Extension which holds some state: the last exception value""" |
|
343 | 343 | |
|
344 | 344 | def __init__(self,color_scheme = 'NoColor'): |
|
345 | 345 | ultraTB.ListTB.__init__(self,color_scheme) |
|
346 | 346 | self.last_syntax_error = None |
|
347 | 347 | |
|
348 | 348 | def __call__(self, etype, value, elist): |
|
349 | 349 | self.last_syntax_error = value |
|
350 | 350 | ultraTB.ListTB.__call__(self,etype,value,elist) |
|
351 | 351 | |
|
352 | 352 | def clear_err_state(self): |
|
353 | 353 | """Return the current error state and clear it""" |
|
354 | 354 | e = self.last_syntax_error |
|
355 | 355 | self.last_syntax_error = None |
|
356 | 356 | return e |
|
357 | 357 | |
|
358 | 358 | #**************************************************************************** |
|
359 | 359 | # Main IPython class |
|
360 | 360 | |
|
361 | 361 | # FIXME: the Magic class is a mixin for now, and will unfortunately remain so |
|
362 | 362 | # until a full rewrite is made. I've cleaned all cross-class uses of |
|
363 | 363 | # attributes and methods, but too much user code out there relies on the |
|
364 | 364 | # equlity %foo == __IP.magic_foo, so I can't actually remove the mixin usage. |
|
365 | 365 | # |
|
366 | 366 | # But at least now, all the pieces have been separated and we could, in |
|
367 | 367 | # principle, stop using the mixin. This will ease the transition to the |
|
368 | 368 | # chainsaw branch. |
|
369 | 369 | |
|
370 | 370 | # For reference, the following is the list of 'self.foo' uses in the Magic |
|
371 | 371 | # class as of 2005-12-28. These are names we CAN'T use in the main ipython |
|
372 | 372 | # class, to prevent clashes. |
|
373 | 373 | |
|
374 | 374 | # ['self.__class__', 'self.__dict__', 'self._inspect', 'self._ofind', |
|
375 | 375 | # 'self.arg_err', 'self.extract_input', 'self.format_', 'self.lsmagic', |
|
376 | 376 | # 'self.magic_', 'self.options_table', 'self.parse', 'self.shell', |
|
377 | 377 | # 'self.value'] |
|
378 | 378 | |
|
379 | 379 | class InteractiveShell(object,Magic): |
|
380 | 380 | """An enhanced console for Python.""" |
|
381 | 381 | |
|
382 | 382 | # class attribute to indicate whether the class supports threads or not. |
|
383 | 383 | # Subclasses with thread support should override this as needed. |
|
384 | 384 | isthreaded = False |
|
385 | 385 | |
|
386 | 386 | def __init__(self,name,usage=None,rc=Struct(opts=None,args=None), |
|
387 | 387 | user_ns=None,user_global_ns=None,banner2='', |
|
388 | 388 | custom_exceptions=((),None),embedded=False): |
|
389 | 389 | |
|
390 | 390 | # log system |
|
391 | 391 | self.logger = Logger(self,logfname='ipython_log.py',logmode='rotate') |
|
392 | 392 | |
|
393 | 393 | # Job manager (for jobs run as background threads) |
|
394 | 394 | self.jobs = BackgroundJobManager() |
|
395 | 395 | |
|
396 | 396 | # Store the actual shell's name |
|
397 | 397 | self.name = name |
|
398 | 398 | self.more = False |
|
399 | 399 | |
|
400 | 400 | # We need to know whether the instance is meant for embedding, since |
|
401 | 401 | # global/local namespaces need to be handled differently in that case |
|
402 | 402 | self.embedded = embedded |
|
403 | 403 | if embedded: |
|
404 | 404 | # Control variable so users can, from within the embedded instance, |
|
405 | 405 | # permanently deactivate it. |
|
406 | 406 | self.embedded_active = True |
|
407 | 407 | |
|
408 | 408 | # command compiler |
|
409 | 409 | self.compile = codeop.CommandCompiler() |
|
410 | 410 | |
|
411 | 411 | # User input buffer |
|
412 | 412 | self.buffer = [] |
|
413 | 413 | |
|
414 | 414 | # Default name given in compilation of code |
|
415 | 415 | self.filename = '<ipython console>' |
|
416 | 416 | |
|
417 | 417 | # Install our own quitter instead of the builtins. For python2.3-2.4, |
|
418 | 418 | # this brings in behavior like 2.5, and for 2.5 it's identical. |
|
419 | 419 | __builtin__.exit = Quitter(self,'exit') |
|
420 | 420 | __builtin__.quit = Quitter(self,'quit') |
|
421 | 421 | |
|
422 | 422 | # Make an empty namespace, which extension writers can rely on both |
|
423 | 423 | # existing and NEVER being used by ipython itself. This gives them a |
|
424 | 424 | # convenient location for storing additional information and state |
|
425 | 425 | # their extensions may require, without fear of collisions with other |
|
426 | 426 | # ipython names that may develop later. |
|
427 | 427 | self.meta = Struct() |
|
428 | 428 | |
|
429 | 429 | # Create the namespace where the user will operate. user_ns is |
|
430 | 430 | # normally the only one used, and it is passed to the exec calls as |
|
431 | 431 | # the locals argument. But we do carry a user_global_ns namespace |
|
432 | 432 | # given as the exec 'globals' argument, This is useful in embedding |
|
433 | 433 | # situations where the ipython shell opens in a context where the |
|
434 | 434 | # distinction between locals and globals is meaningful. For |
|
435 | 435 | # non-embedded contexts, it is just the same object as the user_ns dict. |
|
436 | 436 | |
|
437 | 437 | # FIXME. For some strange reason, __builtins__ is showing up at user |
|
438 | 438 | # level as a dict instead of a module. This is a manual fix, but I |
|
439 | 439 | # should really track down where the problem is coming from. Alex |
|
440 | 440 | # Schmolck reported this problem first. |
|
441 | 441 | |
|
442 | 442 | # A useful post by Alex Martelli on this topic: |
|
443 | 443 | # Re: inconsistent value from __builtins__ |
|
444 | 444 | # Von: Alex Martelli <aleaxit@yahoo.com> |
|
445 | 445 | # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends |
|
446 | 446 | # Gruppen: comp.lang.python |
|
447 | 447 | |
|
448 | 448 | # Michael Hohn <hohn@hooknose.lbl.gov> wrote: |
|
449 | 449 | # > >>> print type(builtin_check.get_global_binding('__builtins__')) |
|
450 | 450 | # > <type 'dict'> |
|
451 | 451 | # > >>> print type(__builtins__) |
|
452 | 452 | # > <type 'module'> |
|
453 | 453 | # > Is this difference in return value intentional? |
|
454 | 454 | |
|
455 | 455 | # Well, it's documented that '__builtins__' can be either a dictionary |
|
456 | 456 | # or a module, and it's been that way for a long time. Whether it's |
|
457 | 457 | # intentional (or sensible), I don't know. In any case, the idea is |
|
458 | 458 | # that if you need to access the built-in namespace directly, you |
|
459 | 459 | # should start with "import __builtin__" (note, no 's') which will |
|
460 | 460 | # definitely give you a module. Yeah, it's somewhat confusing:-(. |
|
461 | 461 | |
|
462 | 462 | # These routines return properly built dicts as needed by the rest of |
|
463 | 463 | # the code, and can also be used by extension writers to generate |
|
464 | 464 | # properly initialized namespaces. |
|
465 | 465 | user_ns, user_global_ns = IPython.ipapi.make_user_namespaces(user_ns, |
|
466 | 466 | user_global_ns) |
|
467 | 467 | |
|
468 | 468 | # Assign namespaces |
|
469 | 469 | # This is the namespace where all normal user variables live |
|
470 | 470 | self.user_ns = user_ns |
|
471 | 471 | self.user_global_ns = user_global_ns |
|
472 | 472 | |
|
473 | 473 | # An auxiliary namespace that checks what parts of the user_ns were |
|
474 | 474 | # loaded at startup, so we can list later only variables defined in |
|
475 | 475 | # actual interactive use. Since it is always a subset of user_ns, it |
|
476 | 476 | # doesn't need to be seaparately tracked in the ns_table |
|
477 | 477 | self.user_config_ns = {} |
|
478 | 478 | |
|
479 | 479 | # A namespace to keep track of internal data structures to prevent |
|
480 | 480 | # them from cluttering user-visible stuff. Will be updated later |
|
481 | 481 | self.internal_ns = {} |
|
482 | 482 | |
|
483 | 483 | # Namespace of system aliases. Each entry in the alias |
|
484 | 484 | # table must be a 2-tuple of the form (N,name), where N is the number |
|
485 | 485 | # of positional arguments of the alias. |
|
486 | 486 | self.alias_table = {} |
|
487 | 487 | |
|
488 | 488 | # Now that FakeModule produces a real module, we've run into a nasty |
|
489 | 489 | # problem: after script execution (via %run), the module where the user |
|
490 | 490 | # code ran is deleted. Now that this object is a true module (needed |
|
491 | 491 | # so docetst and other tools work correctly), the Python module |
|
492 | 492 | # teardown mechanism runs over it, and sets to None every variable |
|
493 | 493 | # present in that module. Top-level references to objects from the |
|
494 | 494 | # script survive, because the user_ns is updated with them. However, |
|
495 | 495 | # calling functions defined in the script that use other things from |
|
496 | 496 | # the script will fail, because the function's closure had references |
|
497 | 497 | # to the original objects, which are now all None. So we must protect |
|
498 | 498 | # these modules from deletion by keeping a cache. |
|
499 | 499 | # |
|
500 | 500 | # To avoid keeping stale modules around (we only need the one from the |
|
501 | 501 | # last run), we use a dict keyed with the full path to the script, so |
|
502 | 502 | # only the last version of the module is held in the cache. Note, |
|
503 | 503 | # however, that we must cache the module *namespace contents* (their |
|
504 | 504 | # __dict__). Because if we try to cache the actual modules, old ones |
|
505 | 505 | # (uncached) could be destroyed while still holding references (such as |
|
506 | 506 | # those held by GUI objects that tend to be long-lived)> |
|
507 | 507 | # |
|
508 | 508 | # The %reset command will flush this cache. See the cache_main_mod() |
|
509 | 509 | # and clear_main_mod_cache() methods for details on use. |
|
510 | 510 | |
|
511 | 511 | # This is the cache used for 'main' namespaces |
|
512 | 512 | self._main_ns_cache = {} |
|
513 | 513 | # And this is the single instance of FakeModule whose __dict__ we keep |
|
514 | 514 | # copying and clearing for reuse on each %run |
|
515 | 515 | self._user_main_module = FakeModule() |
|
516 | 516 | |
|
517 | 517 | # A table holding all the namespaces IPython deals with, so that |
|
518 | 518 | # introspection facilities can search easily. |
|
519 | 519 | self.ns_table = {'user':user_ns, |
|
520 | 520 | 'user_global':user_global_ns, |
|
521 | 521 | 'alias':self.alias_table, |
|
522 | 522 | 'internal':self.internal_ns, |
|
523 | 523 | 'builtin':__builtin__.__dict__ |
|
524 | 524 | } |
|
525 | 525 | |
|
526 | 526 | # Similarly, track all namespaces where references can be held and that |
|
527 | 527 | # we can safely clear (so it can NOT include builtin). This one can be |
|
528 | 528 | # a simple list. |
|
529 | 529 | self.ns_refs_table = [ user_ns, user_global_ns, self.user_config_ns, |
|
530 | 530 | self.alias_table, self.internal_ns, |
|
531 | 531 | self._main_ns_cache ] |
|
532 | 532 | |
|
533 | 533 | # We need to insert into sys.modules something that looks like a |
|
534 | 534 | # module but which accesses the IPython namespace, for shelve and |
|
535 | 535 | # pickle to work interactively. Normally they rely on getting |
|
536 | 536 | # everything out of __main__, but for embedding purposes each IPython |
|
537 | 537 | # instance has its own private namespace, so we can't go shoving |
|
538 | 538 | # everything into __main__. |
|
539 | 539 | |
|
540 | 540 | # note, however, that we should only do this for non-embedded |
|
541 | 541 | # ipythons, which really mimic the __main__.__dict__ with their own |
|
542 | 542 | # namespace. Embedded instances, on the other hand, should not do |
|
543 | 543 | # this because they need to manage the user local/global namespaces |
|
544 | 544 | # only, but they live within a 'normal' __main__ (meaning, they |
|
545 | 545 | # shouldn't overtake the execution environment of the script they're |
|
546 | 546 | # embedded in). |
|
547 | 547 | |
|
548 | 548 | if not embedded: |
|
549 | 549 | try: |
|
550 | 550 | main_name = self.user_ns['__name__'] |
|
551 | 551 | except KeyError: |
|
552 | 552 | raise KeyError,'user_ns dictionary MUST have a "__name__" key' |
|
553 | 553 | else: |
|
554 | 554 | #print "pickle hack in place" # dbg |
|
555 | 555 | #print 'main_name:',main_name # dbg |
|
556 | 556 | sys.modules[main_name] = FakeModule(self.user_ns) |
|
557 | 557 | |
|
558 | 558 | # List of input with multi-line handling. |
|
559 | 559 | self.input_hist = InputList() |
|
560 | 560 | # This one will hold the 'raw' input history, without any |
|
561 | 561 | # pre-processing. This will allow users to retrieve the input just as |
|
562 | 562 | # it was exactly typed in by the user, with %hist -r. |
|
563 | 563 | self.input_hist_raw = InputList() |
|
564 | 564 | |
|
565 | 565 | # list of visited directories |
|
566 | 566 | try: |
|
567 | 567 | self.dir_hist = [os.getcwd()] |
|
568 | 568 | except OSError: |
|
569 | 569 | self.dir_hist = [] |
|
570 | 570 | |
|
571 | 571 | # dict of output history |
|
572 | 572 | self.output_hist = {} |
|
573 | 573 | |
|
574 | 574 | # Get system encoding at startup time. Certain terminals (like Emacs |
|
575 | 575 | # under Win32 have it set to None, and we need to have a known valid |
|
576 | 576 | # encoding to use in the raw_input() method |
|
577 | 577 | try: |
|
578 | 578 | self.stdin_encoding = sys.stdin.encoding or 'ascii' |
|
579 | 579 | except AttributeError: |
|
580 | 580 | self.stdin_encoding = 'ascii' |
|
581 | 581 | |
|
582 | 582 | # dict of things NOT to alias (keywords, builtins and some magics) |
|
583 | 583 | no_alias = {} |
|
584 | 584 | no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias'] |
|
585 | 585 | for key in keyword.kwlist + no_alias_magics: |
|
586 | 586 | no_alias[key] = 1 |
|
587 | 587 | no_alias.update(__builtin__.__dict__) |
|
588 | 588 | self.no_alias = no_alias |
|
589 | 589 | |
|
590 | 590 | # Object variable to store code object waiting execution. This is |
|
591 | 591 | # used mainly by the multithreaded shells, but it can come in handy in |
|
592 | 592 | # other situations. No need to use a Queue here, since it's a single |
|
593 | 593 | # item which gets cleared once run. |
|
594 | 594 | self.code_to_run = None |
|
595 | 595 | |
|
596 | 596 | # escapes for automatic behavior on the command line |
|
597 | 597 | self.ESC_SHELL = '!' |
|
598 | 598 | self.ESC_SH_CAP = '!!' |
|
599 | 599 | self.ESC_HELP = '?' |
|
600 | 600 | self.ESC_MAGIC = '%' |
|
601 | 601 | self.ESC_QUOTE = ',' |
|
602 | 602 | self.ESC_QUOTE2 = ';' |
|
603 | 603 | self.ESC_PAREN = '/' |
|
604 | 604 | |
|
605 | 605 | # And their associated handlers |
|
606 | 606 | self.esc_handlers = {self.ESC_PAREN : self.handle_auto, |
|
607 | 607 | self.ESC_QUOTE : self.handle_auto, |
|
608 | 608 | self.ESC_QUOTE2 : self.handle_auto, |
|
609 | 609 | self.ESC_MAGIC : self.handle_magic, |
|
610 | 610 | self.ESC_HELP : self.handle_help, |
|
611 | 611 | self.ESC_SHELL : self.handle_shell_escape, |
|
612 | 612 | self.ESC_SH_CAP : self.handle_shell_escape, |
|
613 | 613 | } |
|
614 | 614 | |
|
615 | 615 | # class initializations |
|
616 | 616 | Magic.__init__(self,self) |
|
617 | 617 | |
|
618 | 618 | # Python source parser/formatter for syntax highlighting |
|
619 | 619 | pyformat = PyColorize.Parser().format |
|
620 | 620 | self.pycolorize = lambda src: pyformat(src,'str',self.rc['colors']) |
|
621 | 621 | |
|
622 | 622 | # hooks holds pointers used for user-side customizations |
|
623 | 623 | self.hooks = Struct() |
|
624 | 624 | |
|
625 | 625 | self.strdispatchers = {} |
|
626 | 626 | |
|
627 | 627 | # Set all default hooks, defined in the IPython.hooks module. |
|
628 | 628 | hooks = IPython.hooks |
|
629 | 629 | for hook_name in hooks.__all__: |
|
630 | 630 | # default hooks have priority 100, i.e. low; user hooks should have |
|
631 | 631 | # 0-100 priority |
|
632 | 632 | self.set_hook(hook_name,getattr(hooks,hook_name), 100) |
|
633 | 633 | #print "bound hook",hook_name |
|
634 | 634 | |
|
635 | 635 | # Flag to mark unconditional exit |
|
636 | 636 | self.exit_now = False |
|
637 | 637 | |
|
638 | 638 | self.usage_min = """\ |
|
639 | 639 | An enhanced console for Python. |
|
640 | 640 | Some of its features are: |
|
641 | 641 | - Readline support if the readline library is present. |
|
642 | 642 | - Tab completion in the local namespace. |
|
643 | 643 | - Logging of input, see command-line options. |
|
644 | 644 | - System shell escape via ! , eg !ls. |
|
645 | 645 | - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.) |
|
646 | 646 | - Keeps track of locally defined variables via %who, %whos. |
|
647 | 647 | - Show object information with a ? eg ?x or x? (use ?? for more info). |
|
648 | 648 | """ |
|
649 | 649 | if usage: self.usage = usage |
|
650 | 650 | else: self.usage = self.usage_min |
|
651 | 651 | |
|
652 | 652 | # Storage |
|
653 | 653 | self.rc = rc # This will hold all configuration information |
|
654 | 654 | self.pager = 'less' |
|
655 | 655 | # temporary files used for various purposes. Deleted at exit. |
|
656 | 656 | self.tempfiles = [] |
|
657 | 657 | |
|
658 | 658 | # Keep track of readline usage (later set by init_readline) |
|
659 | 659 | self.has_readline = False |
|
660 | 660 | |
|
661 | 661 | # template for logfile headers. It gets resolved at runtime by the |
|
662 | 662 | # logstart method. |
|
663 | 663 | self.loghead_tpl = \ |
|
664 | 664 | """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE *** |
|
665 | 665 | #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW |
|
666 | 666 | #log# opts = %s |
|
667 | 667 | #log# args = %s |
|
668 | 668 | #log# It is safe to make manual edits below here. |
|
669 | 669 | #log#----------------------------------------------------------------------- |
|
670 | 670 | """ |
|
671 | 671 | # for pushd/popd management |
|
672 | 672 | try: |
|
673 | 673 | self.home_dir = get_home_dir() |
|
674 | 674 | except HomeDirError,msg: |
|
675 | 675 | fatal(msg) |
|
676 | 676 | |
|
677 | 677 | self.dir_stack = [] |
|
678 | 678 | |
|
679 | 679 | # Functions to call the underlying shell. |
|
680 | 680 | |
|
681 | 681 | # The first is similar to os.system, but it doesn't return a value, |
|
682 | 682 | # and it allows interpolation of variables in the user's namespace. |
|
683 | 683 | self.system = lambda cmd: \ |
|
684 | 684 | self.hooks.shell_hook(self.var_expand(cmd,depth=2)) |
|
685 | 685 | |
|
686 | 686 | # These are for getoutput and getoutputerror: |
|
687 | 687 | self.getoutput = lambda cmd: \ |
|
688 | 688 | getoutput(self.var_expand(cmd,depth=2), |
|
689 | 689 | header=self.rc.system_header, |
|
690 | 690 | verbose=self.rc.system_verbose) |
|
691 | 691 | |
|
692 | 692 | self.getoutputerror = lambda cmd: \ |
|
693 | 693 | getoutputerror(self.var_expand(cmd,depth=2), |
|
694 | 694 | header=self.rc.system_header, |
|
695 | 695 | verbose=self.rc.system_verbose) |
|
696 | 696 | |
|
697 | 697 | |
|
698 | 698 | # keep track of where we started running (mainly for crash post-mortem) |
|
699 | 699 | self.starting_dir = os.getcwd() |
|
700 | 700 | |
|
701 | 701 | # Various switches which can be set |
|
702 | 702 | self.CACHELENGTH = 5000 # this is cheap, it's just text |
|
703 | 703 | self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__ |
|
704 | 704 | self.banner2 = banner2 |
|
705 | 705 | |
|
706 | 706 | # TraceBack handlers: |
|
707 | 707 | |
|
708 | 708 | # Syntax error handler. |
|
709 | 709 | self.SyntaxTB = SyntaxTB(color_scheme='NoColor') |
|
710 | 710 | |
|
711 | 711 | # The interactive one is initialized with an offset, meaning we always |
|
712 | 712 | # want to remove the topmost item in the traceback, which is our own |
|
713 | 713 | # internal code. Valid modes: ['Plain','Context','Verbose'] |
|
714 | 714 | self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain', |
|
715 | 715 | color_scheme='NoColor', |
|
716 | 716 | tb_offset = 1) |
|
717 | 717 | |
|
718 | 718 | # IPython itself shouldn't crash. This will produce a detailed |
|
719 | 719 | # post-mortem if it does. But we only install the crash handler for |
|
720 | 720 | # non-threaded shells, the threaded ones use a normal verbose reporter |
|
721 | 721 | # and lose the crash handler. This is because exceptions in the main |
|
722 | 722 | # thread (such as in GUI code) propagate directly to sys.excepthook, |
|
723 | 723 | # and there's no point in printing crash dumps for every user exception. |
|
724 | 724 | if self.isthreaded: |
|
725 | 725 | ipCrashHandler = ultraTB.FormattedTB() |
|
726 | 726 | else: |
|
727 | 727 | from IPython import CrashHandler |
|
728 | 728 | ipCrashHandler = CrashHandler.IPythonCrashHandler(self) |
|
729 | 729 | self.set_crash_handler(ipCrashHandler) |
|
730 | 730 | |
|
731 | 731 | # and add any custom exception handlers the user may have specified |
|
732 | 732 | self.set_custom_exc(*custom_exceptions) |
|
733 | 733 | |
|
734 | 734 | # indentation management |
|
735 | 735 | self.autoindent = False |
|
736 | 736 | self.indent_current_nsp = 0 |
|
737 | 737 | |
|
738 | 738 | # Make some aliases automatically |
|
739 | 739 | # Prepare list of shell aliases to auto-define |
|
740 | 740 | if os.name == 'posix': |
|
741 | 741 | auto_alias = ('mkdir mkdir', 'rmdir rmdir', |
|
742 | 742 | 'mv mv -i','rm rm -i','cp cp -i', |
|
743 | 743 | 'cat cat','less less','clear clear', |
|
744 | 744 | # a better ls |
|
745 | 745 | 'ls ls -F', |
|
746 | 746 | # long ls |
|
747 | 747 | 'll ls -lF') |
|
748 | 748 | # Extra ls aliases with color, which need special treatment on BSD |
|
749 | 749 | # variants |
|
750 | 750 | ls_extra = ( # color ls |
|
751 | 751 | 'lc ls -F -o --color', |
|
752 | 752 | # ls normal files only |
|
753 | 753 | 'lf ls -F -o --color %l | grep ^-', |
|
754 | 754 | # ls symbolic links |
|
755 | 755 | 'lk ls -F -o --color %l | grep ^l', |
|
756 | 756 | # directories or links to directories, |
|
757 | 757 | 'ldir ls -F -o --color %l | grep /$', |
|
758 | 758 | # things which are executable |
|
759 | 759 | 'lx ls -F -o --color %l | grep ^-..x', |
|
760 | 760 | ) |
|
761 | 761 | # The BSDs don't ship GNU ls, so they don't understand the |
|
762 | 762 | # --color switch out of the box |
|
763 | 763 | if 'bsd' in sys.platform: |
|
764 | 764 | ls_extra = ( # ls normal files only |
|
765 | 765 | 'lf ls -lF | grep ^-', |
|
766 | 766 | # ls symbolic links |
|
767 | 767 | 'lk ls -lF | grep ^l', |
|
768 | 768 | # directories or links to directories, |
|
769 | 769 | 'ldir ls -lF | grep /$', |
|
770 | 770 | # things which are executable |
|
771 | 771 | 'lx ls -lF | grep ^-..x', |
|
772 | 772 | ) |
|
773 | 773 | auto_alias = auto_alias + ls_extra |
|
774 | 774 | elif os.name in ['nt','dos']: |
|
775 | 775 | auto_alias = ('ls dir /on', |
|
776 | 776 | 'ddir dir /ad /on', 'ldir dir /ad /on', |
|
777 | 777 | 'mkdir mkdir','rmdir rmdir','echo echo', |
|
778 | 778 | 'ren ren','cls cls','copy copy') |
|
779 | 779 | else: |
|
780 | 780 | auto_alias = () |
|
781 | 781 | self.auto_alias = [s.split(None,1) for s in auto_alias] |
|
782 | 782 | |
|
783 | 783 | # Produce a public API instance |
|
784 | 784 | self.api = IPython.ipapi.IPApi(self) |
|
785 | 785 | |
|
786 | 786 | # Initialize all user-visible namespaces |
|
787 | 787 | self.init_namespaces() |
|
788 | 788 | |
|
789 | 789 | # Call the actual (public) initializer |
|
790 | 790 | self.init_auto_alias() |
|
791 | 791 | |
|
792 | 792 | # track which builtins we add, so we can clean up later |
|
793 | 793 | self.builtins_added = {} |
|
794 | 794 | # This method will add the necessary builtins for operation, but |
|
795 | 795 | # tracking what it did via the builtins_added dict. |
|
796 | 796 | |
|
797 | 797 | #TODO: remove this, redundant |
|
798 | 798 | self.add_builtins() |
|
799 | 799 | # end __init__ |
|
800 | 800 | |
|
801 | 801 | def var_expand(self,cmd,depth=0): |
|
802 | 802 | """Expand python variables in a string. |
|
803 | 803 | |
|
804 | 804 | The depth argument indicates how many frames above the caller should |
|
805 | 805 | be walked to look for the local namespace where to expand variables. |
|
806 | 806 | |
|
807 | 807 | The global namespace for expansion is always the user's interactive |
|
808 | 808 | namespace. |
|
809 | 809 | """ |
|
810 | 810 | |
|
811 | 811 | return str(ItplNS(cmd, |
|
812 | 812 | self.user_ns, # globals |
|
813 | 813 | # Skip our own frame in searching for locals: |
|
814 | 814 | sys._getframe(depth+1).f_locals # locals |
|
815 | 815 | )) |
|
816 | 816 | |
|
817 | 817 | def pre_config_initialization(self): |
|
818 | 818 | """Pre-configuration init method |
|
819 | 819 | |
|
820 | 820 | This is called before the configuration files are processed to |
|
821 | 821 | prepare the services the config files might need. |
|
822 | 822 | |
|
823 | 823 | self.rc already has reasonable default values at this point. |
|
824 | 824 | """ |
|
825 | 825 | rc = self.rc |
|
826 | 826 | try: |
|
827 | 827 | self.db = pickleshare.PickleShareDB(rc.ipythondir + "/db") |
|
828 | 828 | except exceptions.UnicodeDecodeError: |
|
829 | 829 | print "Your ipythondir can't be decoded to unicode!" |
|
830 | 830 | print "Please set HOME environment variable to something that" |
|
831 | 831 | print r"only has ASCII characters, e.g. c:\home" |
|
832 | 832 | print "Now it is",rc.ipythondir |
|
833 | 833 | sys.exit() |
|
834 | 834 | self.shadowhist = IPython.history.ShadowHist(self.db) |
|
835 | 835 | |
|
836 | 836 | def post_config_initialization(self): |
|
837 | 837 | """Post configuration init method |
|
838 | 838 | |
|
839 | 839 | This is called after the configuration files have been processed to |
|
840 | 840 | 'finalize' the initialization.""" |
|
841 | 841 | |
|
842 | 842 | rc = self.rc |
|
843 | 843 | |
|
844 | 844 | # Object inspector |
|
845 | 845 | self.inspector = OInspect.Inspector(OInspect.InspectColors, |
|
846 | 846 | PyColorize.ANSICodeColors, |
|
847 | 847 | 'NoColor', |
|
848 | 848 | rc.object_info_string_level) |
|
849 | 849 | |
|
850 | 850 | self.rl_next_input = None |
|
851 | 851 | self.rl_do_indent = False |
|
852 | 852 | # Load readline proper |
|
853 | 853 | if rc.readline: |
|
854 | 854 | self.init_readline() |
|
855 | 855 | |
|
856 | 856 | # local shortcut, this is used a LOT |
|
857 | 857 | self.log = self.logger.log |
|
858 | 858 | |
|
859 | 859 | # Initialize cache, set in/out prompts and printing system |
|
860 | 860 | self.outputcache = CachedOutput(self, |
|
861 | 861 | rc.cache_size, |
|
862 | 862 | rc.pprint, |
|
863 | 863 | input_sep = rc.separate_in, |
|
864 | 864 | output_sep = rc.separate_out, |
|
865 | 865 | output_sep2 = rc.separate_out2, |
|
866 | 866 | ps1 = rc.prompt_in1, |
|
867 | 867 | ps2 = rc.prompt_in2, |
|
868 | 868 | ps_out = rc.prompt_out, |
|
869 | 869 | pad_left = rc.prompts_pad_left) |
|
870 | 870 | |
|
871 | 871 | # user may have over-ridden the default print hook: |
|
872 | 872 | try: |
|
873 | 873 | self.outputcache.__class__.display = self.hooks.display |
|
874 | 874 | except AttributeError: |
|
875 | 875 | pass |
|
876 | 876 | |
|
877 | 877 | # I don't like assigning globally to sys, because it means when |
|
878 | 878 | # embedding instances, each embedded instance overrides the previous |
|
879 | 879 | # choice. But sys.displayhook seems to be called internally by exec, |
|
880 | 880 | # so I don't see a way around it. We first save the original and then |
|
881 | 881 | # overwrite it. |
|
882 | 882 | self.sys_displayhook = sys.displayhook |
|
883 | 883 | sys.displayhook = self.outputcache |
|
884 | 884 | |
|
885 | 885 | # Do a proper resetting of doctest, including the necessary displayhook |
|
886 | 886 | # monkeypatching |
|
887 | 887 | try: |
|
888 | 888 | doctest_reload() |
|
889 | 889 | except ImportError: |
|
890 | 890 | warn("doctest module does not exist.") |
|
891 | 891 | |
|
892 | 892 | # Set user colors (don't do it in the constructor above so that it |
|
893 | 893 | # doesn't crash if colors option is invalid) |
|
894 | 894 | self.magic_colors(rc.colors) |
|
895 | 895 | |
|
896 | 896 | # Set calling of pdb on exceptions |
|
897 | 897 | self.call_pdb = rc.pdb |
|
898 | 898 | |
|
899 | 899 | # Load user aliases |
|
900 | 900 | for alias in rc.alias: |
|
901 | 901 | self.magic_alias(alias) |
|
902 | 902 | |
|
903 | 903 | self.hooks.late_startup_hook() |
|
904 | 904 | |
|
905 | 905 | for cmd in self.rc.autoexec: |
|
906 | 906 | #print "autoexec>",cmd #dbg |
|
907 | 907 | self.api.runlines(cmd) |
|
908 | 908 | |
|
909 | 909 | batchrun = False |
|
910 | 910 | for batchfile in [path(arg) for arg in self.rc.args |
|
911 | 911 | if arg.lower().endswith('.ipy')]: |
|
912 | 912 | if not batchfile.isfile(): |
|
913 | 913 | print "No such batch file:", batchfile |
|
914 | 914 | continue |
|
915 | 915 | self.api.runlines(batchfile.text()) |
|
916 | 916 | batchrun = True |
|
917 | 917 | # without -i option, exit after running the batch file |
|
918 | 918 | if batchrun and not self.rc.interact: |
|
919 | 919 | self.ask_exit() |
|
920 | 920 | |
|
921 | 921 | def init_namespaces(self): |
|
922 | 922 | """Initialize all user-visible namespaces to their minimum defaults. |
|
923 | 923 | |
|
924 | 924 | Certain history lists are also initialized here, as they effectively |
|
925 | 925 | act as user namespaces. |
|
926 | 926 | |
|
927 | 927 | Note |
|
928 | 928 | ---- |
|
929 | 929 | All data structures here are only filled in, they are NOT reset by this |
|
930 | 930 | method. If they were not empty before, data will simply be added to |
|
931 | 931 | therm. |
|
932 | 932 | """ |
|
933 | 933 | # The user namespace MUST have a pointer to the shell itself. |
|
934 | 934 | self.user_ns[self.name] = self |
|
935 | 935 | |
|
936 | 936 | # Store the public api instance |
|
937 | 937 | self.user_ns['_ip'] = self.api |
|
938 | 938 | |
|
939 | 939 | # make global variables for user access to the histories |
|
940 | 940 | self.user_ns['_ih'] = self.input_hist |
|
941 | 941 | self.user_ns['_oh'] = self.output_hist |
|
942 | 942 | self.user_ns['_dh'] = self.dir_hist |
|
943 | 943 | |
|
944 | 944 | # user aliases to input and output histories |
|
945 | 945 | self.user_ns['In'] = self.input_hist |
|
946 | 946 | self.user_ns['Out'] = self.output_hist |
|
947 | 947 | |
|
948 | 948 | self.user_ns['_sh'] = IPython.shadowns |
|
949 | 949 | |
|
950 | 950 | # Fill the history zero entry, user counter starts at 1 |
|
951 | 951 | self.input_hist.append('\n') |
|
952 | 952 | self.input_hist_raw.append('\n') |
|
953 | 953 | |
|
954 | 954 | def add_builtins(self): |
|
955 | 955 | """Store ipython references into the builtin namespace. |
|
956 | 956 | |
|
957 | 957 | Some parts of ipython operate via builtins injected here, which hold a |
|
958 | 958 | reference to IPython itself.""" |
|
959 | 959 | |
|
960 | 960 | # TODO: deprecate all of these, they are unsafe |
|
961 | 961 | builtins_new = dict(__IPYTHON__ = self, |
|
962 | 962 | ip_set_hook = self.set_hook, |
|
963 | 963 | jobs = self.jobs, |
|
964 | 964 | ipmagic = wrap_deprecated(self.ipmagic,'_ip.magic()'), |
|
965 | 965 | ipalias = wrap_deprecated(self.ipalias), |
|
966 | 966 | ipsystem = wrap_deprecated(self.ipsystem,'_ip.system()'), |
|
967 | 967 | #_ip = self.api |
|
968 | 968 | ) |
|
969 | 969 | for biname,bival in builtins_new.items(): |
|
970 | 970 | try: |
|
971 | 971 | # store the orignal value so we can restore it |
|
972 | 972 | self.builtins_added[biname] = __builtin__.__dict__[biname] |
|
973 | 973 | except KeyError: |
|
974 | 974 | # or mark that it wasn't defined, and we'll just delete it at |
|
975 | 975 | # cleanup |
|
976 | 976 | self.builtins_added[biname] = Undefined |
|
977 | 977 | __builtin__.__dict__[biname] = bival |
|
978 | 978 | |
|
979 | 979 | # Keep in the builtins a flag for when IPython is active. We set it |
|
980 | 980 | # with setdefault so that multiple nested IPythons don't clobber one |
|
981 | 981 | # another. Each will increase its value by one upon being activated, |
|
982 | 982 | # which also gives us a way to determine the nesting level. |
|
983 | 983 | __builtin__.__dict__.setdefault('__IPYTHON__active',0) |
|
984 | 984 | |
|
985 | 985 | def clean_builtins(self): |
|
986 | 986 | """Remove any builtins which might have been added by add_builtins, or |
|
987 | 987 | restore overwritten ones to their previous values.""" |
|
988 | 988 | for biname,bival in self.builtins_added.items(): |
|
989 | 989 | if bival is Undefined: |
|
990 | 990 | del __builtin__.__dict__[biname] |
|
991 | 991 | else: |
|
992 | 992 | __builtin__.__dict__[biname] = bival |
|
993 | 993 | self.builtins_added.clear() |
|
994 | 994 | |
|
995 | 995 | def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None): |
|
996 | 996 | """set_hook(name,hook) -> sets an internal IPython hook. |
|
997 | 997 | |
|
998 | 998 | IPython exposes some of its internal API as user-modifiable hooks. By |
|
999 | 999 | adding your function to one of these hooks, you can modify IPython's |
|
1000 | 1000 | behavior to call at runtime your own routines.""" |
|
1001 | 1001 | |
|
1002 | 1002 | # At some point in the future, this should validate the hook before it |
|
1003 | 1003 | # accepts it. Probably at least check that the hook takes the number |
|
1004 | 1004 | # of args it's supposed to. |
|
1005 | 1005 | |
|
1006 | 1006 | f = new.instancemethod(hook,self,self.__class__) |
|
1007 | 1007 | |
|
1008 | 1008 | # check if the hook is for strdispatcher first |
|
1009 | 1009 | if str_key is not None: |
|
1010 | 1010 | sdp = self.strdispatchers.get(name, StrDispatch()) |
|
1011 | 1011 | sdp.add_s(str_key, f, priority ) |
|
1012 | 1012 | self.strdispatchers[name] = sdp |
|
1013 | 1013 | return |
|
1014 | 1014 | if re_key is not None: |
|
1015 | 1015 | sdp = self.strdispatchers.get(name, StrDispatch()) |
|
1016 | 1016 | sdp.add_re(re.compile(re_key), f, priority ) |
|
1017 | 1017 | self.strdispatchers[name] = sdp |
|
1018 | 1018 | return |
|
1019 | 1019 | |
|
1020 | 1020 | dp = getattr(self.hooks, name, None) |
|
1021 | 1021 | if name not in IPython.hooks.__all__: |
|
1022 | 1022 | print "Warning! Hook '%s' is not one of %s" % (name, IPython.hooks.__all__ ) |
|
1023 | 1023 | if not dp: |
|
1024 | 1024 | dp = IPython.hooks.CommandChainDispatcher() |
|
1025 | 1025 | |
|
1026 | 1026 | try: |
|
1027 | 1027 | dp.add(f,priority) |
|
1028 | 1028 | except AttributeError: |
|
1029 | 1029 | # it was not commandchain, plain old func - replace |
|
1030 | 1030 | dp = f |
|
1031 | 1031 | |
|
1032 | 1032 | setattr(self.hooks,name, dp) |
|
1033 | 1033 | |
|
1034 | 1034 | |
|
1035 | 1035 | #setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__)) |
|
1036 | 1036 | |
|
1037 | 1037 | def set_crash_handler(self,crashHandler): |
|
1038 | 1038 | """Set the IPython crash handler. |
|
1039 | 1039 | |
|
1040 | 1040 | This must be a callable with a signature suitable for use as |
|
1041 | 1041 | sys.excepthook.""" |
|
1042 | 1042 | |
|
1043 | 1043 | # Install the given crash handler as the Python exception hook |
|
1044 | 1044 | sys.excepthook = crashHandler |
|
1045 | 1045 | |
|
1046 | 1046 | # The instance will store a pointer to this, so that runtime code |
|
1047 | 1047 | # (such as magics) can access it. This is because during the |
|
1048 | 1048 | # read-eval loop, it gets temporarily overwritten (to deal with GUI |
|
1049 | 1049 | # frameworks). |
|
1050 | 1050 | self.sys_excepthook = sys.excepthook |
|
1051 | 1051 | |
|
1052 | 1052 | |
|
1053 | 1053 | def set_custom_exc(self,exc_tuple,handler): |
|
1054 | 1054 | """set_custom_exc(exc_tuple,handler) |
|
1055 | 1055 | |
|
1056 | 1056 | Set a custom exception handler, which will be called if any of the |
|
1057 | 1057 | exceptions in exc_tuple occur in the mainloop (specifically, in the |
|
1058 | 1058 | runcode() method. |
|
1059 | 1059 | |
|
1060 | 1060 | Inputs: |
|
1061 | 1061 | |
|
1062 | 1062 | - exc_tuple: a *tuple* of valid exceptions to call the defined |
|
1063 | 1063 | handler for. It is very important that you use a tuple, and NOT A |
|
1064 | 1064 | LIST here, because of the way Python's except statement works. If |
|
1065 | 1065 | you only want to trap a single exception, use a singleton tuple: |
|
1066 | 1066 | |
|
1067 | 1067 | exc_tuple == (MyCustomException,) |
|
1068 | 1068 | |
|
1069 | 1069 | - handler: this must be defined as a function with the following |
|
1070 | 1070 | basic interface: def my_handler(self,etype,value,tb). |
|
1071 | 1071 | |
|
1072 | 1072 | This will be made into an instance method (via new.instancemethod) |
|
1073 | 1073 | of IPython itself, and it will be called if any of the exceptions |
|
1074 | 1074 | listed in the exc_tuple are caught. If the handler is None, an |
|
1075 | 1075 | internal basic one is used, which just prints basic info. |
|
1076 | 1076 | |
|
1077 | 1077 | WARNING: by putting in your own exception handler into IPython's main |
|
1078 | 1078 | execution loop, you run a very good chance of nasty crashes. This |
|
1079 | 1079 | facility should only be used if you really know what you are doing.""" |
|
1080 | 1080 | |
|
1081 | 1081 | assert type(exc_tuple)==type(()) , \ |
|
1082 | 1082 | "The custom exceptions must be given AS A TUPLE." |
|
1083 | 1083 | |
|
1084 | 1084 | def dummy_handler(self,etype,value,tb): |
|
1085 | 1085 | print '*** Simple custom exception handler ***' |
|
1086 | 1086 | print 'Exception type :',etype |
|
1087 | 1087 | print 'Exception value:',value |
|
1088 | 1088 | print 'Traceback :',tb |
|
1089 | 1089 | print 'Source code :','\n'.join(self.buffer) |
|
1090 | 1090 | |
|
1091 | 1091 | if handler is None: handler = dummy_handler |
|
1092 | 1092 | |
|
1093 | 1093 | self.CustomTB = new.instancemethod(handler,self,self.__class__) |
|
1094 | 1094 | self.custom_exceptions = exc_tuple |
|
1095 | 1095 | |
|
1096 | 1096 | def set_custom_completer(self,completer,pos=0): |
|
1097 | 1097 | """set_custom_completer(completer,pos=0) |
|
1098 | 1098 | |
|
1099 | 1099 | Adds a new custom completer function. |
|
1100 | 1100 | |
|
1101 | 1101 | The position argument (defaults to 0) is the index in the completers |
|
1102 | 1102 | list where you want the completer to be inserted.""" |
|
1103 | 1103 | |
|
1104 | 1104 | newcomp = new.instancemethod(completer,self.Completer, |
|
1105 | 1105 | self.Completer.__class__) |
|
1106 | 1106 | self.Completer.matchers.insert(pos,newcomp) |
|
1107 | 1107 | |
|
1108 | 1108 | def set_completer(self): |
|
1109 | 1109 | """reset readline's completer to be our own.""" |
|
1110 | 1110 | self.readline.set_completer(self.Completer.complete) |
|
1111 | 1111 | |
|
1112 | 1112 | def _get_call_pdb(self): |
|
1113 | 1113 | return self._call_pdb |
|
1114 | 1114 | |
|
1115 | 1115 | def _set_call_pdb(self,val): |
|
1116 | 1116 | |
|
1117 | 1117 | if val not in (0,1,False,True): |
|
1118 | 1118 | raise ValueError,'new call_pdb value must be boolean' |
|
1119 | 1119 | |
|
1120 | 1120 | # store value in instance |
|
1121 | 1121 | self._call_pdb = val |
|
1122 | 1122 | |
|
1123 | 1123 | # notify the actual exception handlers |
|
1124 | 1124 | self.InteractiveTB.call_pdb = val |
|
1125 | 1125 | if self.isthreaded: |
|
1126 | 1126 | try: |
|
1127 | 1127 | self.sys_excepthook.call_pdb = val |
|
1128 | 1128 | except: |
|
1129 | 1129 | warn('Failed to activate pdb for threaded exception handler') |
|
1130 | 1130 | |
|
1131 | 1131 | call_pdb = property(_get_call_pdb,_set_call_pdb,None, |
|
1132 | 1132 | 'Control auto-activation of pdb at exceptions') |
|
1133 | 1133 | |
|
1134 | 1134 | # These special functions get installed in the builtin namespace, to |
|
1135 | 1135 | # provide programmatic (pure python) access to magics, aliases and system |
|
1136 | 1136 | # calls. This is important for logging, user scripting, and more. |
|
1137 | 1137 | |
|
1138 | 1138 | # We are basically exposing, via normal python functions, the three |
|
1139 | 1139 | # mechanisms in which ipython offers special call modes (magics for |
|
1140 | 1140 | # internal control, aliases for direct system access via pre-selected |
|
1141 | 1141 | # names, and !cmd for calling arbitrary system commands). |
|
1142 | 1142 | |
|
1143 | 1143 | def ipmagic(self,arg_s): |
|
1144 | 1144 | """Call a magic function by name. |
|
1145 | 1145 | |
|
1146 | 1146 | Input: a string containing the name of the magic function to call and any |
|
1147 | 1147 | additional arguments to be passed to the magic. |
|
1148 | 1148 | |
|
1149 | 1149 | ipmagic('name -opt foo bar') is equivalent to typing at the ipython |
|
1150 | 1150 | prompt: |
|
1151 | 1151 | |
|
1152 | 1152 | In[1]: %name -opt foo bar |
|
1153 | 1153 | |
|
1154 | 1154 | To call a magic without arguments, simply use ipmagic('name'). |
|
1155 | 1155 | |
|
1156 | 1156 | This provides a proper Python function to call IPython's magics in any |
|
1157 | 1157 | valid Python code you can type at the interpreter, including loops and |
|
1158 | 1158 | compound statements. It is added by IPython to the Python builtin |
|
1159 | 1159 | namespace upon initialization.""" |
|
1160 | 1160 | |
|
1161 | 1161 | args = arg_s.split(' ',1) |
|
1162 | 1162 | magic_name = args[0] |
|
1163 | 1163 | magic_name = magic_name.lstrip(self.ESC_MAGIC) |
|
1164 | 1164 | |
|
1165 | 1165 | try: |
|
1166 | 1166 | magic_args = args[1] |
|
1167 | 1167 | except IndexError: |
|
1168 | 1168 | magic_args = '' |
|
1169 | 1169 | fn = getattr(self,'magic_'+magic_name,None) |
|
1170 | 1170 | if fn is None: |
|
1171 | 1171 | error("Magic function `%s` not found." % magic_name) |
|
1172 | 1172 | else: |
|
1173 | 1173 | magic_args = self.var_expand(magic_args,1) |
|
1174 | 1174 | return fn(magic_args) |
|
1175 | 1175 | |
|
1176 | 1176 | def ipalias(self,arg_s): |
|
1177 | 1177 | """Call an alias by name. |
|
1178 | 1178 | |
|
1179 | 1179 | Input: a string containing the name of the alias to call and any |
|
1180 | 1180 | additional arguments to be passed to the magic. |
|
1181 | 1181 | |
|
1182 | 1182 | ipalias('name -opt foo bar') is equivalent to typing at the ipython |
|
1183 | 1183 | prompt: |
|
1184 | 1184 | |
|
1185 | 1185 | In[1]: name -opt foo bar |
|
1186 | 1186 | |
|
1187 | 1187 | To call an alias without arguments, simply use ipalias('name'). |
|
1188 | 1188 | |
|
1189 | 1189 | This provides a proper Python function to call IPython's aliases in any |
|
1190 | 1190 | valid Python code you can type at the interpreter, including loops and |
|
1191 | 1191 | compound statements. It is added by IPython to the Python builtin |
|
1192 | 1192 | namespace upon initialization.""" |
|
1193 | 1193 | |
|
1194 | 1194 | args = arg_s.split(' ',1) |
|
1195 | 1195 | alias_name = args[0] |
|
1196 | 1196 | try: |
|
1197 | 1197 | alias_args = args[1] |
|
1198 | 1198 | except IndexError: |
|
1199 | 1199 | alias_args = '' |
|
1200 | 1200 | if alias_name in self.alias_table: |
|
1201 | 1201 | self.call_alias(alias_name,alias_args) |
|
1202 | 1202 | else: |
|
1203 | 1203 | error("Alias `%s` not found." % alias_name) |
|
1204 | 1204 | |
|
1205 | 1205 | def ipsystem(self,arg_s): |
|
1206 | 1206 | """Make a system call, using IPython.""" |
|
1207 | 1207 | |
|
1208 | 1208 | self.system(arg_s) |
|
1209 | 1209 | |
|
1210 | 1210 | def complete(self,text): |
|
1211 | 1211 | """Return a sorted list of all possible completions on text. |
|
1212 | 1212 | |
|
1213 | 1213 | Inputs: |
|
1214 | 1214 | |
|
1215 | 1215 | - text: a string of text to be completed on. |
|
1216 | 1216 | |
|
1217 | 1217 | This is a wrapper around the completion mechanism, similar to what |
|
1218 | 1218 | readline does at the command line when the TAB key is hit. By |
|
1219 | 1219 | exposing it as a method, it can be used by other non-readline |
|
1220 | 1220 | environments (such as GUIs) for text completion. |
|
1221 | 1221 | |
|
1222 | 1222 | Simple usage example: |
|
1223 | 1223 | |
|
1224 | 1224 | In [7]: x = 'hello' |
|
1225 | 1225 | |
|
1226 | 1226 | In [8]: x |
|
1227 | 1227 | Out[8]: 'hello' |
|
1228 | 1228 | |
|
1229 | 1229 | In [9]: print x |
|
1230 | 1230 | hello |
|
1231 | 1231 | |
|
1232 | 1232 | In [10]: _ip.IP.complete('x.l') |
|
1233 | 1233 | Out[10]: ['x.ljust', 'x.lower', 'x.lstrip'] |
|
1234 | 1234 | """ |
|
1235 | 1235 | |
|
1236 | 1236 | complete = self.Completer.complete |
|
1237 | 1237 | state = 0 |
|
1238 | 1238 | # use a dict so we get unique keys, since ipyhton's multiple |
|
1239 | 1239 | # completers can return duplicates. When we make 2.4 a requirement, |
|
1240 | 1240 | # start using sets instead, which are faster. |
|
1241 | 1241 | comps = {} |
|
1242 | 1242 | while True: |
|
1243 | 1243 | newcomp = complete(text,state,line_buffer=text) |
|
1244 | 1244 | if newcomp is None: |
|
1245 | 1245 | break |
|
1246 | 1246 | comps[newcomp] = 1 |
|
1247 | 1247 | state += 1 |
|
1248 | 1248 | outcomps = comps.keys() |
|
1249 | 1249 | outcomps.sort() |
|
1250 | 1250 | #print "T:",text,"OC:",outcomps # dbg |
|
1251 | 1251 | #print "vars:",self.user_ns.keys() |
|
1252 | 1252 | return outcomps |
|
1253 | 1253 | |
|
1254 | 1254 | def set_completer_frame(self, frame=None): |
|
1255 | 1255 | if frame: |
|
1256 | 1256 | self.Completer.namespace = frame.f_locals |
|
1257 | 1257 | self.Completer.global_namespace = frame.f_globals |
|
1258 | 1258 | else: |
|
1259 | 1259 | self.Completer.namespace = self.user_ns |
|
1260 | 1260 | self.Completer.global_namespace = self.user_global_ns |
|
1261 | 1261 | |
|
1262 | 1262 | def init_auto_alias(self): |
|
1263 | 1263 | """Define some aliases automatically. |
|
1264 | 1264 | |
|
1265 | 1265 | These are ALL parameter-less aliases""" |
|
1266 | 1266 | |
|
1267 | 1267 | for alias,cmd in self.auto_alias: |
|
1268 | 1268 | self.getapi().defalias(alias,cmd) |
|
1269 | 1269 | |
|
1270 | 1270 | |
|
1271 | 1271 | def alias_table_validate(self,verbose=0): |
|
1272 | 1272 | """Update information about the alias table. |
|
1273 | 1273 | |
|
1274 | 1274 | In particular, make sure no Python keywords/builtins are in it.""" |
|
1275 | 1275 | |
|
1276 | 1276 | no_alias = self.no_alias |
|
1277 | 1277 | for k in self.alias_table.keys(): |
|
1278 | 1278 | if k in no_alias: |
|
1279 | 1279 | del self.alias_table[k] |
|
1280 | 1280 | if verbose: |
|
1281 | 1281 | print ("Deleting alias <%s>, it's a Python " |
|
1282 | 1282 | "keyword or builtin." % k) |
|
1283 | 1283 | |
|
1284 | 1284 | def set_autoindent(self,value=None): |
|
1285 | 1285 | """Set the autoindent flag, checking for readline support. |
|
1286 | 1286 | |
|
1287 | 1287 | If called with no arguments, it acts as a toggle.""" |
|
1288 | 1288 | |
|
1289 | 1289 | if not self.has_readline: |
|
1290 | 1290 | if os.name == 'posix': |
|
1291 | 1291 | warn("The auto-indent feature requires the readline library") |
|
1292 | 1292 | self.autoindent = 0 |
|
1293 | 1293 | return |
|
1294 | 1294 | if value is None: |
|
1295 | 1295 | self.autoindent = not self.autoindent |
|
1296 | 1296 | else: |
|
1297 | 1297 | self.autoindent = value |
|
1298 | 1298 | |
|
1299 | 1299 | def rc_set_toggle(self,rc_field,value=None): |
|
1300 | 1300 | """Set or toggle a field in IPython's rc config. structure. |
|
1301 | 1301 | |
|
1302 | 1302 | If called with no arguments, it acts as a toggle. |
|
1303 | 1303 | |
|
1304 | 1304 | If called with a non-existent field, the resulting AttributeError |
|
1305 | 1305 | exception will propagate out.""" |
|
1306 | 1306 | |
|
1307 | 1307 | rc_val = getattr(self.rc,rc_field) |
|
1308 | 1308 | if value is None: |
|
1309 | 1309 | value = not rc_val |
|
1310 | 1310 | setattr(self.rc,rc_field,value) |
|
1311 | 1311 | |
|
1312 | 1312 | def user_setup(self,ipythondir,rc_suffix,mode='install'): |
|
1313 | 1313 | """Install the user configuration directory. |
|
1314 | 1314 | |
|
1315 | 1315 | Note |
|
1316 | 1316 | ---- |
|
1317 | 1317 | DEPRECATED: use the top-level user_setup() function instead. |
|
1318 | 1318 | """ |
|
1319 | 1319 | return user_setup(ipythondir,rc_suffix,mode) |
|
1320 | 1320 | |
|
1321 | 1321 | def atexit_operations(self): |
|
1322 | 1322 | """This will be executed at the time of exit. |
|
1323 | 1323 | |
|
1324 | 1324 | Saving of persistent data should be performed here. """ |
|
1325 | 1325 | |
|
1326 | 1326 | #print '*** IPython exit cleanup ***' # dbg |
|
1327 | 1327 | # input history |
|
1328 | 1328 | self.savehist() |
|
1329 | 1329 | |
|
1330 | 1330 | # Cleanup all tempfiles left around |
|
1331 | 1331 | for tfile in self.tempfiles: |
|
1332 | 1332 | try: |
|
1333 | 1333 | os.unlink(tfile) |
|
1334 | 1334 | except OSError: |
|
1335 | 1335 | pass |
|
1336 | 1336 | |
|
1337 | 1337 | # Clear all user namespaces to release all references cleanly. |
|
1338 | 1338 | self.reset() |
|
1339 | 1339 | |
|
1340 | 1340 | # Run user hooks |
|
1341 | 1341 | self.hooks.shutdown_hook() |
|
1342 | 1342 | |
|
1343 | 1343 | def reset(self): |
|
1344 | 1344 | """Clear all internal namespaces. |
|
1345 | 1345 | |
|
1346 | 1346 | Note that this is much more aggressive than %reset, since it clears |
|
1347 | 1347 | fully all namespaces, as well as all input/output lists. |
|
1348 | 1348 | """ |
|
1349 | 1349 | for ns in self.ns_refs_table: |
|
1350 | 1350 | ns.clear() |
|
1351 | 1351 | |
|
1352 | 1352 | # Clear input and output histories |
|
1353 | 1353 | self.input_hist[:] = [] |
|
1354 | 1354 | self.input_hist_raw[:] = [] |
|
1355 | 1355 | self.output_hist.clear() |
|
1356 | 1356 | # Restore the user namespaces to minimal usability |
|
1357 | 1357 | self.init_namespaces() |
|
1358 | 1358 | |
|
1359 | 1359 | def savehist(self): |
|
1360 | 1360 | """Save input history to a file (via readline library).""" |
|
1361 | 1361 | |
|
1362 | 1362 | if not self.has_readline: |
|
1363 | 1363 | return |
|
1364 | 1364 | |
|
1365 | 1365 | try: |
|
1366 | 1366 | self.readline.write_history_file(self.histfile) |
|
1367 | 1367 | except: |
|
1368 | 1368 | print 'Unable to save IPython command history to file: ' + \ |
|
1369 | 1369 | `self.histfile` |
|
1370 | 1370 | |
|
1371 | 1371 | def reloadhist(self): |
|
1372 | 1372 | """Reload the input history from disk file.""" |
|
1373 | 1373 | |
|
1374 | 1374 | if self.has_readline: |
|
1375 | 1375 | try: |
|
1376 | 1376 | self.readline.clear_history() |
|
1377 | 1377 | self.readline.read_history_file(self.shell.histfile) |
|
1378 | 1378 | except AttributeError: |
|
1379 | 1379 | pass |
|
1380 | 1380 | |
|
1381 | 1381 | |
|
1382 | 1382 | def history_saving_wrapper(self, func): |
|
1383 | 1383 | """ Wrap func for readline history saving |
|
1384 | 1384 | |
|
1385 | 1385 | Convert func into callable that saves & restores |
|
1386 | 1386 | history around the call """ |
|
1387 | 1387 | |
|
1388 | 1388 | if not self.has_readline: |
|
1389 | 1389 | return func |
|
1390 | 1390 | |
|
1391 | 1391 | def wrapper(): |
|
1392 | 1392 | self.savehist() |
|
1393 | 1393 | try: |
|
1394 | 1394 | func() |
|
1395 | 1395 | finally: |
|
1396 | 1396 | readline.read_history_file(self.histfile) |
|
1397 | 1397 | return wrapper |
|
1398 | 1398 | |
|
1399 | 1399 | def pre_readline(self): |
|
1400 | 1400 | """readline hook to be used at the start of each line. |
|
1401 | 1401 | |
|
1402 | 1402 | Currently it handles auto-indent only.""" |
|
1403 | 1403 | |
|
1404 | 1404 | #debugx('self.indent_current_nsp','pre_readline:') |
|
1405 | 1405 | |
|
1406 | 1406 | if self.rl_do_indent: |
|
1407 | 1407 | self.readline.insert_text(self.indent_current_str()) |
|
1408 | 1408 | if self.rl_next_input is not None: |
|
1409 | 1409 | self.readline.insert_text(self.rl_next_input) |
|
1410 | 1410 | self.rl_next_input = None |
|
1411 | 1411 | |
|
1412 | 1412 | def init_readline(self): |
|
1413 | 1413 | """Command history completion/saving/reloading.""" |
|
1414 | 1414 | |
|
1415 | 1415 | |
|
1416 | 1416 | import IPython.rlineimpl as readline |
|
1417 | 1417 | |
|
1418 | 1418 | if not readline.have_readline: |
|
1419 | 1419 | self.has_readline = 0 |
|
1420 | 1420 | self.readline = None |
|
1421 | 1421 | # no point in bugging windows users with this every time: |
|
1422 | 1422 | warn('Readline services not available on this platform.') |
|
1423 | 1423 | else: |
|
1424 | 1424 | sys.modules['readline'] = readline |
|
1425 | 1425 | import atexit |
|
1426 | 1426 | from IPython.completer import IPCompleter |
|
1427 | 1427 | self.Completer = IPCompleter(self, |
|
1428 | 1428 | self.user_ns, |
|
1429 | 1429 | self.user_global_ns, |
|
1430 | 1430 | self.rc.readline_omit__names, |
|
1431 | 1431 | self.alias_table) |
|
1432 | 1432 | sdisp = self.strdispatchers.get('complete_command', StrDispatch()) |
|
1433 | 1433 | self.strdispatchers['complete_command'] = sdisp |
|
1434 | 1434 | self.Completer.custom_completers = sdisp |
|
1435 | 1435 | # Platform-specific configuration |
|
1436 | 1436 | if os.name == 'nt': |
|
1437 | 1437 | self.readline_startup_hook = readline.set_pre_input_hook |
|
1438 | 1438 | else: |
|
1439 | 1439 | self.readline_startup_hook = readline.set_startup_hook |
|
1440 | 1440 | |
|
1441 | 1441 | # Load user's initrc file (readline config) |
|
1442 | 1442 | # Or if libedit is used, load editrc. |
|
1443 | 1443 | inputrc_name = os.environ.get('INPUTRC') |
|
1444 | 1444 | if inputrc_name is None: |
|
1445 | 1445 | home_dir = get_home_dir() |
|
1446 | 1446 | if home_dir is not None: |
|
1447 | 1447 | inputrc_name = '.inputrc' |
|
1448 | 1448 | if readline.uses_libedit: |
|
1449 | 1449 | inputrc_name = '.editrc' |
|
1450 | 1450 | inputrc_name = os.path.join(home_dir, inputrc_name) |
|
1451 | 1451 | if os.path.isfile(inputrc_name): |
|
1452 | 1452 | try: |
|
1453 | 1453 | readline.read_init_file(inputrc_name) |
|
1454 | 1454 | except: |
|
1455 | 1455 | warn('Problems reading readline initialization file <%s>' |
|
1456 | 1456 | % inputrc_name) |
|
1457 | 1457 | |
|
1458 | 1458 | self.has_readline = 1 |
|
1459 | 1459 | self.readline = readline |
|
1460 | 1460 | # save this in sys so embedded copies can restore it properly |
|
1461 | 1461 | sys.ipcompleter = self.Completer.complete |
|
1462 | 1462 | self.set_completer() |
|
1463 | 1463 | |
|
1464 | 1464 | # Configure readline according to user's prefs |
|
1465 | 1465 | # This is only done if GNU readline is being used. If libedit |
|
1466 | 1466 | # is being used (as on Leopard) the readline config is |
|
1467 | 1467 | # not run as the syntax for libedit is different. |
|
1468 | 1468 | if not readline.uses_libedit: |
|
1469 | 1469 | for rlcommand in self.rc.readline_parse_and_bind: |
|
1470 | 1470 | #print "loading rl:",rlcommand # dbg |
|
1471 | 1471 | readline.parse_and_bind(rlcommand) |
|
1472 | 1472 | |
|
1473 | 1473 | # Remove some chars from the delimiters list. If we encounter |
|
1474 | 1474 | # unicode chars, discard them. |
|
1475 | 1475 | delims = readline.get_completer_delims().encode("ascii", "ignore") |
|
1476 | 1476 | delims = delims.translate(string._idmap, |
|
1477 | 1477 | self.rc.readline_remove_delims) |
|
1478 | 1478 | readline.set_completer_delims(delims) |
|
1479 | 1479 | # otherwise we end up with a monster history after a while: |
|
1480 | 1480 | readline.set_history_length(1000) |
|
1481 | 1481 | try: |
|
1482 | 1482 | #print '*** Reading readline history' # dbg |
|
1483 | 1483 | readline.read_history_file(self.histfile) |
|
1484 | 1484 | except IOError: |
|
1485 | 1485 | pass # It doesn't exist yet. |
|
1486 | 1486 | |
|
1487 | 1487 | atexit.register(self.atexit_operations) |
|
1488 | 1488 | del atexit |
|
1489 | 1489 | |
|
1490 | 1490 | # Configure auto-indent for all platforms |
|
1491 | 1491 | self.set_autoindent(self.rc.autoindent) |
|
1492 | 1492 | |
|
1493 | 1493 | def ask_yes_no(self,prompt,default=True): |
|
1494 | 1494 | if self.rc.quiet: |
|
1495 | 1495 | return True |
|
1496 | 1496 | return ask_yes_no(prompt,default) |
|
1497 | 1497 | |
|
1498 | 1498 | def new_main_mod(self,ns=None): |
|
1499 | 1499 | """Return a new 'main' module object for user code execution. |
|
1500 | 1500 | """ |
|
1501 | 1501 | main_mod = self._user_main_module |
|
1502 | 1502 | init_fakemod_dict(main_mod,ns) |
|
1503 | 1503 | return main_mod |
|
1504 | 1504 | |
|
1505 | 1505 | def cache_main_mod(self,ns,fname): |
|
1506 | 1506 | """Cache a main module's namespace. |
|
1507 | 1507 | |
|
1508 | 1508 | When scripts are executed via %run, we must keep a reference to the |
|
1509 | 1509 | namespace of their __main__ module (a FakeModule instance) around so |
|
1510 | 1510 | that Python doesn't clear it, rendering objects defined therein |
|
1511 | 1511 | useless. |
|
1512 | 1512 | |
|
1513 | 1513 | This method keeps said reference in a private dict, keyed by the |
|
1514 | 1514 | absolute path of the module object (which corresponds to the script |
|
1515 | 1515 | path). This way, for multiple executions of the same script we only |
|
1516 | 1516 | keep one copy of the namespace (the last one), thus preventing memory |
|
1517 | 1517 | leaks from old references while allowing the objects from the last |
|
1518 | 1518 | execution to be accessible. |
|
1519 | 1519 | |
|
1520 | 1520 | Note: we can not allow the actual FakeModule instances to be deleted, |
|
1521 | 1521 | because of how Python tears down modules (it hard-sets all their |
|
1522 | 1522 | references to None without regard for reference counts). This method |
|
1523 | 1523 | must therefore make a *copy* of the given namespace, to allow the |
|
1524 | 1524 | original module's __dict__ to be cleared and reused. |
|
1525 | 1525 | |
|
1526 | 1526 | |
|
1527 | 1527 | Parameters |
|
1528 | 1528 | ---------- |
|
1529 | 1529 | ns : a namespace (a dict, typically) |
|
1530 | 1530 | |
|
1531 | 1531 | fname : str |
|
1532 | 1532 | Filename associated with the namespace. |
|
1533 | 1533 | |
|
1534 | 1534 | Examples |
|
1535 | 1535 | -------- |
|
1536 | 1536 | |
|
1537 | 1537 | In [10]: import IPython |
|
1538 | 1538 | |
|
1539 | 1539 | In [11]: _ip.IP.cache_main_mod(IPython.__dict__,IPython.__file__) |
|
1540 | 1540 | |
|
1541 | 1541 | In [12]: IPython.__file__ in _ip.IP._main_ns_cache |
|
1542 | 1542 | Out[12]: True |
|
1543 | 1543 | """ |
|
1544 | 1544 | self._main_ns_cache[os.path.abspath(fname)] = ns.copy() |
|
1545 | 1545 | |
|
1546 | 1546 | def clear_main_mod_cache(self): |
|
1547 | 1547 | """Clear the cache of main modules. |
|
1548 | 1548 | |
|
1549 | 1549 | Mainly for use by utilities like %reset. |
|
1550 | 1550 | |
|
1551 | 1551 | Examples |
|
1552 | 1552 | -------- |
|
1553 | 1553 | |
|
1554 | 1554 | In [15]: import IPython |
|
1555 | 1555 | |
|
1556 | 1556 | In [16]: _ip.IP.cache_main_mod(IPython.__dict__,IPython.__file__) |
|
1557 | 1557 | |
|
1558 | 1558 | In [17]: len(_ip.IP._main_ns_cache) > 0 |
|
1559 | 1559 | Out[17]: True |
|
1560 | 1560 | |
|
1561 | 1561 | In [18]: _ip.IP.clear_main_mod_cache() |
|
1562 | 1562 | |
|
1563 | 1563 | In [19]: len(_ip.IP._main_ns_cache) == 0 |
|
1564 | 1564 | Out[19]: True |
|
1565 | 1565 | """ |
|
1566 | 1566 | self._main_ns_cache.clear() |
|
1567 | 1567 | |
|
1568 | 1568 | def _should_recompile(self,e): |
|
1569 | 1569 | """Utility routine for edit_syntax_error""" |
|
1570 | 1570 | |
|
1571 | 1571 | if e.filename in ('<ipython console>','<input>','<string>', |
|
1572 | 1572 | '<console>','<BackgroundJob compilation>', |
|
1573 | 1573 | None): |
|
1574 | 1574 | |
|
1575 | 1575 | return False |
|
1576 | 1576 | try: |
|
1577 | 1577 | if (self.rc.autoedit_syntax and |
|
1578 | 1578 | not self.ask_yes_no('Return to editor to correct syntax error? ' |
|
1579 | 1579 | '[Y/n] ','y')): |
|
1580 | 1580 | return False |
|
1581 | 1581 | except EOFError: |
|
1582 | 1582 | return False |
|
1583 | 1583 | |
|
1584 | 1584 | def int0(x): |
|
1585 | 1585 | try: |
|
1586 | 1586 | return int(x) |
|
1587 | 1587 | except TypeError: |
|
1588 | 1588 | return 0 |
|
1589 | 1589 | # always pass integer line and offset values to editor hook |
|
1590 | 1590 | try: |
|
1591 | 1591 | self.hooks.fix_error_editor(e.filename, |
|
1592 | 1592 | int0(e.lineno),int0(e.offset),e.msg) |
|
1593 | 1593 | except IPython.ipapi.TryNext: |
|
1594 | 1594 | warn('Could not open editor') |
|
1595 | 1595 | return False |
|
1596 | 1596 | return True |
|
1597 | 1597 | |
|
1598 | 1598 | def edit_syntax_error(self): |
|
1599 | 1599 | """The bottom half of the syntax error handler called in the main loop. |
|
1600 | 1600 | |
|
1601 | 1601 | Loop until syntax error is fixed or user cancels. |
|
1602 | 1602 | """ |
|
1603 | 1603 | |
|
1604 | 1604 | while self.SyntaxTB.last_syntax_error: |
|
1605 | 1605 | # copy and clear last_syntax_error |
|
1606 | 1606 | err = self.SyntaxTB.clear_err_state() |
|
1607 | 1607 | if not self._should_recompile(err): |
|
1608 | 1608 | return |
|
1609 | 1609 | try: |
|
1610 | 1610 | # may set last_syntax_error again if a SyntaxError is raised |
|
1611 | 1611 | self.safe_execfile(err.filename,self.user_ns) |
|
1612 | 1612 | except: |
|
1613 | 1613 | self.showtraceback() |
|
1614 | 1614 | else: |
|
1615 | 1615 | try: |
|
1616 | 1616 | f = file(err.filename) |
|
1617 | 1617 | try: |
|
1618 | 1618 | sys.displayhook(f.read()) |
|
1619 | 1619 | finally: |
|
1620 | 1620 | f.close() |
|
1621 | 1621 | except: |
|
1622 | 1622 | self.showtraceback() |
|
1623 | 1623 | |
|
1624 | 1624 | def showsyntaxerror(self, filename=None): |
|
1625 | 1625 | """Display the syntax error that just occurred. |
|
1626 | 1626 | |
|
1627 | 1627 | This doesn't display a stack trace because there isn't one. |
|
1628 | 1628 | |
|
1629 | 1629 | If a filename is given, it is stuffed in the exception instead |
|
1630 | 1630 | of what was there before (because Python's parser always uses |
|
1631 | 1631 | "<string>" when reading from a string). |
|
1632 | 1632 | """ |
|
1633 | 1633 | etype, value, last_traceback = sys.exc_info() |
|
1634 | 1634 | |
|
1635 | 1635 | # See note about these variables in showtraceback() below |
|
1636 | 1636 | sys.last_type = etype |
|
1637 | 1637 | sys.last_value = value |
|
1638 | 1638 | sys.last_traceback = last_traceback |
|
1639 | 1639 | |
|
1640 | 1640 | if filename and etype is SyntaxError: |
|
1641 | 1641 | # Work hard to stuff the correct filename in the exception |
|
1642 | 1642 | try: |
|
1643 | 1643 | msg, (dummy_filename, lineno, offset, line) = value |
|
1644 | 1644 | except: |
|
1645 | 1645 | # Not the format we expect; leave it alone |
|
1646 | 1646 | pass |
|
1647 | 1647 | else: |
|
1648 | 1648 | # Stuff in the right filename |
|
1649 | 1649 | try: |
|
1650 | 1650 | # Assume SyntaxError is a class exception |
|
1651 | 1651 | value = SyntaxError(msg, (filename, lineno, offset, line)) |
|
1652 | 1652 | except: |
|
1653 | 1653 | # If that failed, assume SyntaxError is a string |
|
1654 | 1654 | value = msg, (filename, lineno, offset, line) |
|
1655 | 1655 | self.SyntaxTB(etype,value,[]) |
|
1656 | 1656 | |
|
1657 | 1657 | def debugger(self,force=False): |
|
1658 | 1658 | """Call the pydb/pdb debugger. |
|
1659 | 1659 | |
|
1660 | 1660 | Keywords: |
|
1661 | 1661 | |
|
1662 | 1662 | - force(False): by default, this routine checks the instance call_pdb |
|
1663 | 1663 | flag and does not actually invoke the debugger if the flag is false. |
|
1664 | 1664 | The 'force' option forces the debugger to activate even if the flag |
|
1665 | 1665 | is false. |
|
1666 | 1666 | """ |
|
1667 | 1667 | |
|
1668 | 1668 | if not (force or self.call_pdb): |
|
1669 | 1669 | return |
|
1670 | 1670 | |
|
1671 | 1671 | if not hasattr(sys,'last_traceback'): |
|
1672 | 1672 | error('No traceback has been produced, nothing to debug.') |
|
1673 | 1673 | return |
|
1674 | 1674 | |
|
1675 | 1675 | # use pydb if available |
|
1676 | 1676 | if Debugger.has_pydb: |
|
1677 | 1677 | from pydb import pm |
|
1678 | 1678 | else: |
|
1679 | 1679 | # fallback to our internal debugger |
|
1680 | 1680 | pm = lambda : self.InteractiveTB.debugger(force=True) |
|
1681 | 1681 | self.history_saving_wrapper(pm)() |
|
1682 | 1682 | |
|
1683 | 1683 | def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None): |
|
1684 | 1684 | """Display the exception that just occurred. |
|
1685 | 1685 | |
|
1686 | 1686 | If nothing is known about the exception, this is the method which |
|
1687 | 1687 | should be used throughout the code for presenting user tracebacks, |
|
1688 | 1688 | rather than directly invoking the InteractiveTB object. |
|
1689 | 1689 | |
|
1690 | 1690 | A specific showsyntaxerror() also exists, but this method can take |
|
1691 | 1691 | care of calling it if needed, so unless you are explicitly catching a |
|
1692 | 1692 | SyntaxError exception, don't try to analyze the stack manually and |
|
1693 | 1693 | simply call this method.""" |
|
1694 | 1694 | |
|
1695 | 1695 | |
|
1696 | 1696 | # Though this won't be called by syntax errors in the input line, |
|
1697 | 1697 | # there may be SyntaxError cases whith imported code. |
|
1698 | 1698 | |
|
1699 | 1699 | try: |
|
1700 | 1700 | if exc_tuple is None: |
|
1701 | 1701 | etype, value, tb = sys.exc_info() |
|
1702 | 1702 | else: |
|
1703 | 1703 | etype, value, tb = exc_tuple |
|
1704 | 1704 | |
|
1705 | 1705 | if etype is SyntaxError: |
|
1706 | 1706 | self.showsyntaxerror(filename) |
|
1707 | 1707 | elif etype is IPython.ipapi.UsageError: |
|
1708 | 1708 | print "UsageError:", value |
|
1709 | 1709 | else: |
|
1710 | 1710 | # WARNING: these variables are somewhat deprecated and not |
|
1711 | 1711 | # necessarily safe to use in a threaded environment, but tools |
|
1712 | 1712 | # like pdb depend on their existence, so let's set them. If we |
|
1713 | 1713 | # find problems in the field, we'll need to revisit their use. |
|
1714 | 1714 | sys.last_type = etype |
|
1715 | 1715 | sys.last_value = value |
|
1716 | 1716 | sys.last_traceback = tb |
|
1717 | 1717 | |
|
1718 | 1718 | if etype in self.custom_exceptions: |
|
1719 | 1719 | self.CustomTB(etype,value,tb) |
|
1720 | 1720 | else: |
|
1721 | 1721 | self.InteractiveTB(etype,value,tb,tb_offset=tb_offset) |
|
1722 | 1722 | if self.InteractiveTB.call_pdb and self.has_readline: |
|
1723 | 1723 | # pdb mucks up readline, fix it back |
|
1724 | 1724 | self.set_completer() |
|
1725 | 1725 | except KeyboardInterrupt: |
|
1726 | 1726 | self.write("\nKeyboardInterrupt\n") |
|
1727 | 1727 | |
|
1728 | 1728 | def mainloop(self,banner=None): |
|
1729 | 1729 | """Creates the local namespace and starts the mainloop. |
|
1730 | 1730 | |
|
1731 | 1731 | If an optional banner argument is given, it will override the |
|
1732 | 1732 | internally created default banner.""" |
|
1733 | 1733 | |
|
1734 | 1734 | if self.rc.c: # Emulate Python's -c option |
|
1735 | 1735 | self.exec_init_cmd() |
|
1736 | 1736 | if banner is None: |
|
1737 | 1737 | if not self.rc.banner: |
|
1738 | 1738 | banner = '' |
|
1739 | 1739 | # banner is string? Use it directly! |
|
1740 | 1740 | elif isinstance(self.rc.banner,basestring): |
|
1741 | 1741 | banner = self.rc.banner |
|
1742 | 1742 | else: |
|
1743 | 1743 | banner = self.BANNER+self.banner2 |
|
1744 | 1744 | |
|
1745 | 1745 | # if you run stuff with -c <cmd>, raw hist is not updated |
|
1746 | 1746 | # ensure that it's in sync |
|
1747 | 1747 | if len(self.input_hist) != len (self.input_hist_raw): |
|
1748 | 1748 | self.input_hist_raw = InputList(self.input_hist) |
|
1749 | 1749 | |
|
1750 | 1750 | while 1: |
|
1751 | 1751 | try: |
|
1752 | 1752 | self.interact(banner) |
|
1753 | 1753 | #self.interact_with_readline() |
|
1754 | 1754 | |
|
1755 | 1755 | # XXX for testing of a readline-decoupled repl loop, call |
|
1756 | 1756 | # interact_with_readline above |
|
1757 | 1757 | |
|
1758 | 1758 | break |
|
1759 | 1759 | except KeyboardInterrupt: |
|
1760 | 1760 | # this should not be necessary, but KeyboardInterrupt |
|
1761 | 1761 | # handling seems rather unpredictable... |
|
1762 | 1762 | self.write("\nKeyboardInterrupt in interact()\n") |
|
1763 | 1763 | |
|
1764 | 1764 | def exec_init_cmd(self): |
|
1765 | 1765 | """Execute a command given at the command line. |
|
1766 | 1766 | |
|
1767 | 1767 | This emulates Python's -c option.""" |
|
1768 | 1768 | |
|
1769 | 1769 | #sys.argv = ['-c'] |
|
1770 | 1770 | self.push(self.prefilter(self.rc.c, False)) |
|
1771 | 1771 | if not self.rc.interact: |
|
1772 | 1772 | self.ask_exit() |
|
1773 | 1773 | |
|
1774 | 1774 | def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0): |
|
1775 | 1775 | """Embeds IPython into a running python program. |
|
1776 | 1776 | |
|
1777 | 1777 | Input: |
|
1778 | 1778 | |
|
1779 | 1779 | - header: An optional header message can be specified. |
|
1780 | 1780 | |
|
1781 | 1781 | - local_ns, global_ns: working namespaces. If given as None, the |
|
1782 | 1782 | IPython-initialized one is updated with __main__.__dict__, so that |
|
1783 | 1783 | program variables become visible but user-specific configuration |
|
1784 | 1784 | remains possible. |
|
1785 | 1785 | |
|
1786 | 1786 | - stack_depth: specifies how many levels in the stack to go to |
|
1787 | 1787 | looking for namespaces (when local_ns and global_ns are None). This |
|
1788 | 1788 | allows an intermediate caller to make sure that this function gets |
|
1789 | 1789 | the namespace from the intended level in the stack. By default (0) |
|
1790 | 1790 | it will get its locals and globals from the immediate caller. |
|
1791 | 1791 | |
|
1792 | 1792 | Warning: it's possible to use this in a program which is being run by |
|
1793 | 1793 | IPython itself (via %run), but some funny things will happen (a few |
|
1794 | 1794 | globals get overwritten). In the future this will be cleaned up, as |
|
1795 | 1795 | there is no fundamental reason why it can't work perfectly.""" |
|
1796 | 1796 | |
|
1797 | 1797 | # Get locals and globals from caller |
|
1798 | 1798 | if local_ns is None or global_ns is None: |
|
1799 | 1799 | call_frame = sys._getframe(stack_depth).f_back |
|
1800 | 1800 | |
|
1801 | 1801 | if local_ns is None: |
|
1802 | 1802 | local_ns = call_frame.f_locals |
|
1803 | 1803 | if global_ns is None: |
|
1804 | 1804 | global_ns = call_frame.f_globals |
|
1805 | 1805 | |
|
1806 | 1806 | # Update namespaces and fire up interpreter |
|
1807 | 1807 | |
|
1808 | 1808 | # The global one is easy, we can just throw it in |
|
1809 | 1809 | self.user_global_ns = global_ns |
|
1810 | 1810 | |
|
1811 | 1811 | # but the user/local one is tricky: ipython needs it to store internal |
|
1812 | 1812 | # data, but we also need the locals. We'll copy locals in the user |
|
1813 | 1813 | # one, but will track what got copied so we can delete them at exit. |
|
1814 | 1814 | # This is so that a later embedded call doesn't see locals from a |
|
1815 | 1815 | # previous call (which most likely existed in a separate scope). |
|
1816 | 1816 | local_varnames = local_ns.keys() |
|
1817 | 1817 | self.user_ns.update(local_ns) |
|
1818 | 1818 | #self.user_ns['local_ns'] = local_ns # dbg |
|
1819 | 1819 | |
|
1820 | 1820 | # Patch for global embedding to make sure that things don't overwrite |
|
1821 | 1821 | # user globals accidentally. Thanks to Richard <rxe@renre-europe.com> |
|
1822 | 1822 | # FIXME. Test this a bit more carefully (the if.. is new) |
|
1823 | 1823 | if local_ns is None and global_ns is None: |
|
1824 | 1824 | self.user_global_ns.update(__main__.__dict__) |
|
1825 | 1825 | |
|
1826 | 1826 | # make sure the tab-completer has the correct frame information, so it |
|
1827 | 1827 | # actually completes using the frame's locals/globals |
|
1828 | 1828 | self.set_completer_frame() |
|
1829 | 1829 | |
|
1830 | 1830 | # before activating the interactive mode, we need to make sure that |
|
1831 | 1831 | # all names in the builtin namespace needed by ipython point to |
|
1832 | 1832 | # ourselves, and not to other instances. |
|
1833 | 1833 | self.add_builtins() |
|
1834 | 1834 | |
|
1835 | 1835 | self.interact(header) |
|
1836 | 1836 | |
|
1837 | 1837 | # now, purge out the user namespace from anything we might have added |
|
1838 | 1838 | # from the caller's local namespace |
|
1839 | 1839 | delvar = self.user_ns.pop |
|
1840 | 1840 | for var in local_varnames: |
|
1841 | 1841 | delvar(var,None) |
|
1842 | 1842 | # and clean builtins we may have overridden |
|
1843 | 1843 | self.clean_builtins() |
|
1844 | 1844 | |
|
1845 | 1845 | def interact_prompt(self): |
|
1846 | 1846 | """ Print the prompt (in read-eval-print loop) |
|
1847 | 1847 | |
|
1848 | 1848 | Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not |
|
1849 | 1849 | used in standard IPython flow. |
|
1850 | 1850 | """ |
|
1851 | 1851 | if self.more: |
|
1852 | 1852 | try: |
|
1853 | 1853 | prompt = self.hooks.generate_prompt(True) |
|
1854 | 1854 | except: |
|
1855 | 1855 | self.showtraceback() |
|
1856 | 1856 | if self.autoindent: |
|
1857 | 1857 | self.rl_do_indent = True |
|
1858 | 1858 | |
|
1859 | 1859 | else: |
|
1860 | 1860 | try: |
|
1861 | 1861 | prompt = self.hooks.generate_prompt(False) |
|
1862 | 1862 | except: |
|
1863 | 1863 | self.showtraceback() |
|
1864 | 1864 | self.write(prompt) |
|
1865 | 1865 | |
|
1866 | 1866 | def interact_handle_input(self,line): |
|
1867 | 1867 | """ Handle the input line (in read-eval-print loop) |
|
1868 | 1868 | |
|
1869 | 1869 | Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not |
|
1870 | 1870 | used in standard IPython flow. |
|
1871 | 1871 | """ |
|
1872 | 1872 | if line.lstrip() == line: |
|
1873 | 1873 | self.shadowhist.add(line.strip()) |
|
1874 | 1874 | lineout = self.prefilter(line,self.more) |
|
1875 | 1875 | |
|
1876 | 1876 | if line.strip(): |
|
1877 | 1877 | if self.more: |
|
1878 | 1878 | self.input_hist_raw[-1] += '%s\n' % line |
|
1879 | 1879 | else: |
|
1880 | 1880 | self.input_hist_raw.append('%s\n' % line) |
|
1881 | 1881 | |
|
1882 | 1882 | |
|
1883 | 1883 | self.more = self.push(lineout) |
|
1884 | 1884 | if (self.SyntaxTB.last_syntax_error and |
|
1885 | 1885 | self.rc.autoedit_syntax): |
|
1886 | 1886 | self.edit_syntax_error() |
|
1887 | 1887 | |
|
1888 | 1888 | def interact_with_readline(self): |
|
1889 | 1889 | """ Demo of using interact_handle_input, interact_prompt |
|
1890 | 1890 | |
|
1891 | 1891 | This is the main read-eval-print loop. If you need to implement your own (e.g. for GUI), |
|
1892 | 1892 | it should work like this. |
|
1893 | 1893 | """ |
|
1894 | 1894 | self.readline_startup_hook(self.pre_readline) |
|
1895 | 1895 | while not self.exit_now: |
|
1896 | 1896 | self.interact_prompt() |
|
1897 | 1897 | if self.more: |
|
1898 | 1898 | self.rl_do_indent = True |
|
1899 | 1899 | else: |
|
1900 | 1900 | self.rl_do_indent = False |
|
1901 | 1901 | line = raw_input_original().decode(self.stdin_encoding) |
|
1902 | 1902 | self.interact_handle_input(line) |
|
1903 | 1903 | |
|
1904 | 1904 | |
|
1905 | 1905 | def interact(self, banner=None): |
|
1906 | 1906 | """Closely emulate the interactive Python console. |
|
1907 | 1907 | |
|
1908 | 1908 | The optional banner argument specify the banner to print |
|
1909 | 1909 | before the first interaction; by default it prints a banner |
|
1910 | 1910 | similar to the one printed by the real Python interpreter, |
|
1911 | 1911 | followed by the current class name in parentheses (so as not |
|
1912 | 1912 | to confuse this with the real interpreter -- since it's so |
|
1913 | 1913 | close!). |
|
1914 | 1914 | |
|
1915 | 1915 | """ |
|
1916 | 1916 | |
|
1917 | 1917 | if self.exit_now: |
|
1918 | 1918 | # batch run -> do not interact |
|
1919 | 1919 | return |
|
1920 | 1920 | cprt = 'Type "copyright", "credits" or "license" for more information.' |
|
1921 | 1921 | if banner is None: |
|
1922 | 1922 | self.write("Python %s on %s\n%s\n(%s)\n" % |
|
1923 | 1923 | (sys.version, sys.platform, cprt, |
|
1924 | 1924 | self.__class__.__name__)) |
|
1925 | 1925 | else: |
|
1926 | 1926 | self.write(banner) |
|
1927 | 1927 | |
|
1928 | 1928 | more = 0 |
|
1929 | 1929 | |
|
1930 | 1930 | # Mark activity in the builtins |
|
1931 | 1931 | __builtin__.__dict__['__IPYTHON__active'] += 1 |
|
1932 | 1932 | |
|
1933 | 1933 | if self.has_readline: |
|
1934 | 1934 | self.readline_startup_hook(self.pre_readline) |
|
1935 | 1935 | # exit_now is set by a call to %Exit or %Quit, through the |
|
1936 | 1936 | # ask_exit callback. |
|
1937 | 1937 | |
|
1938 | 1938 | while not self.exit_now: |
|
1939 | 1939 | self.hooks.pre_prompt_hook() |
|
1940 | 1940 | if more: |
|
1941 | 1941 | try: |
|
1942 | 1942 | prompt = self.hooks.generate_prompt(True) |
|
1943 | 1943 | except: |
|
1944 | 1944 | self.showtraceback() |
|
1945 | 1945 | if self.autoindent: |
|
1946 | 1946 | self.rl_do_indent = True |
|
1947 | 1947 | |
|
1948 | 1948 | else: |
|
1949 | 1949 | try: |
|
1950 | 1950 | prompt = self.hooks.generate_prompt(False) |
|
1951 | 1951 | except: |
|
1952 | 1952 | self.showtraceback() |
|
1953 | 1953 | try: |
|
1954 | 1954 | line = self.raw_input(prompt,more) |
|
1955 | 1955 | if self.exit_now: |
|
1956 | 1956 | # quick exit on sys.std[in|out] close |
|
1957 | 1957 | break |
|
1958 | 1958 | if self.autoindent: |
|
1959 | 1959 | self.rl_do_indent = False |
|
1960 | 1960 | |
|
1961 | 1961 | except KeyboardInterrupt: |
|
1962 | 1962 | #double-guard against keyboardinterrupts during kbdint handling |
|
1963 | 1963 | try: |
|
1964 | 1964 | self.write('\nKeyboardInterrupt\n') |
|
1965 | 1965 | self.resetbuffer() |
|
1966 | 1966 | # keep cache in sync with the prompt counter: |
|
1967 | 1967 | self.outputcache.prompt_count -= 1 |
|
1968 | 1968 | |
|
1969 | 1969 | if self.autoindent: |
|
1970 | 1970 | self.indent_current_nsp = 0 |
|
1971 | 1971 | more = 0 |
|
1972 | 1972 | except KeyboardInterrupt: |
|
1973 | 1973 | pass |
|
1974 | 1974 | except EOFError: |
|
1975 | 1975 | if self.autoindent: |
|
1976 | 1976 | self.rl_do_indent = False |
|
1977 | 1977 | self.readline_startup_hook(None) |
|
1978 | 1978 | self.write('\n') |
|
1979 | 1979 | self.exit() |
|
1980 | 1980 | except bdb.BdbQuit: |
|
1981 | 1981 | warn('The Python debugger has exited with a BdbQuit exception.\n' |
|
1982 | 1982 | 'Because of how pdb handles the stack, it is impossible\n' |
|
1983 | 1983 | 'for IPython to properly format this particular exception.\n' |
|
1984 | 1984 | 'IPython will resume normal operation.') |
|
1985 | 1985 | except: |
|
1986 | 1986 | # exceptions here are VERY RARE, but they can be triggered |
|
1987 | 1987 | # asynchronously by signal handlers, for example. |
|
1988 | 1988 | self.showtraceback() |
|
1989 | 1989 | else: |
|
1990 | 1990 | more = self.push(line) |
|
1991 | 1991 | if (self.SyntaxTB.last_syntax_error and |
|
1992 | 1992 | self.rc.autoedit_syntax): |
|
1993 | 1993 | self.edit_syntax_error() |
|
1994 | 1994 | |
|
1995 | 1995 | # We are off again... |
|
1996 | 1996 | __builtin__.__dict__['__IPYTHON__active'] -= 1 |
|
1997 | 1997 | |
|
1998 | 1998 | def excepthook(self, etype, value, tb): |
|
1999 | 1999 | """One more defense for GUI apps that call sys.excepthook. |
|
2000 | 2000 | |
|
2001 | 2001 | GUI frameworks like wxPython trap exceptions and call |
|
2002 | 2002 | sys.excepthook themselves. I guess this is a feature that |
|
2003 | 2003 | enables them to keep running after exceptions that would |
|
2004 | 2004 | otherwise kill their mainloop. This is a bother for IPython |
|
2005 | 2005 | which excepts to catch all of the program exceptions with a try: |
|
2006 | 2006 | except: statement. |
|
2007 | 2007 | |
|
2008 | 2008 | Normally, IPython sets sys.excepthook to a CrashHandler instance, so if |
|
2009 | 2009 | any app directly invokes sys.excepthook, it will look to the user like |
|
2010 | 2010 | IPython crashed. In order to work around this, we can disable the |
|
2011 | 2011 | CrashHandler and replace it with this excepthook instead, which prints a |
|
2012 | 2012 | regular traceback using our InteractiveTB. In this fashion, apps which |
|
2013 | 2013 | call sys.excepthook will generate a regular-looking exception from |
|
2014 | 2014 | IPython, and the CrashHandler will only be triggered by real IPython |
|
2015 | 2015 | crashes. |
|
2016 | 2016 | |
|
2017 | 2017 | This hook should be used sparingly, only in places which are not likely |
|
2018 | 2018 | to be true IPython errors. |
|
2019 | 2019 | """ |
|
2020 | 2020 | self.showtraceback((etype,value,tb),tb_offset=0) |
|
2021 | 2021 | |
|
2022 | 2022 | def expand_aliases(self,fn,rest): |
|
2023 | 2023 | """ Expand multiple levels of aliases: |
|
2024 | 2024 | |
|
2025 | 2025 | if: |
|
2026 | 2026 | |
|
2027 | 2027 | alias foo bar /tmp |
|
2028 | 2028 | alias baz foo |
|
2029 | 2029 | |
|
2030 | 2030 | then: |
|
2031 | 2031 | |
|
2032 | 2032 | baz huhhahhei -> bar /tmp huhhahhei |
|
2033 | 2033 | |
|
2034 | 2034 | """ |
|
2035 | 2035 | line = fn + " " + rest |
|
2036 | 2036 | |
|
2037 | 2037 | done = set() |
|
2038 | 2038 | while 1: |
|
2039 | 2039 | pre,fn,rest = prefilter.splitUserInput(line, |
|
2040 | 2040 | prefilter.shell_line_split) |
|
2041 | 2041 | if fn in self.alias_table: |
|
2042 | 2042 | if fn in done: |
|
2043 | 2043 | warn("Cyclic alias definition, repeated '%s'" % fn) |
|
2044 | 2044 | return "" |
|
2045 | 2045 | done.add(fn) |
|
2046 | 2046 | |
|
2047 | 2047 | l2 = self.transform_alias(fn,rest) |
|
2048 | 2048 | # dir -> dir |
|
2049 | 2049 | # print "alias",line, "->",l2 #dbg |
|
2050 | 2050 | if l2 == line: |
|
2051 | 2051 | break |
|
2052 | 2052 | # ls -> ls -F should not recurse forever |
|
2053 | 2053 | if l2.split(None,1)[0] == line.split(None,1)[0]: |
|
2054 | 2054 | line = l2 |
|
2055 | 2055 | break |
|
2056 | 2056 | |
|
2057 | 2057 | line=l2 |
|
2058 | 2058 | |
|
2059 | 2059 | |
|
2060 | 2060 | # print "al expand to",line #dbg |
|
2061 | 2061 | else: |
|
2062 | 2062 | break |
|
2063 | 2063 | |
|
2064 | 2064 | return line |
|
2065 | 2065 | |
|
2066 | 2066 | def transform_alias(self, alias,rest=''): |
|
2067 | 2067 | """ Transform alias to system command string. |
|
2068 | 2068 | """ |
|
2069 | 2069 | trg = self.alias_table[alias] |
|
2070 | 2070 | |
|
2071 | 2071 | nargs,cmd = trg |
|
2072 | 2072 | # print trg #dbg |
|
2073 | 2073 | if ' ' in cmd and os.path.isfile(cmd): |
|
2074 | 2074 | cmd = '"%s"' % cmd |
|
2075 | 2075 | |
|
2076 | 2076 | # Expand the %l special to be the user's input line |
|
2077 | 2077 | if cmd.find('%l') >= 0: |
|
2078 | 2078 | cmd = cmd.replace('%l',rest) |
|
2079 | 2079 | rest = '' |
|
2080 | 2080 | if nargs==0: |
|
2081 | 2081 | # Simple, argument-less aliases |
|
2082 | 2082 | cmd = '%s %s' % (cmd,rest) |
|
2083 | 2083 | else: |
|
2084 | 2084 | # Handle aliases with positional arguments |
|
2085 | 2085 | args = rest.split(None,nargs) |
|
2086 | 2086 | if len(args)< nargs: |
|
2087 | 2087 | error('Alias <%s> requires %s arguments, %s given.' % |
|
2088 | 2088 | (alias,nargs,len(args))) |
|
2089 | 2089 | return None |
|
2090 | 2090 | cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:])) |
|
2091 | 2091 | # Now call the macro, evaluating in the user's namespace |
|
2092 | 2092 | #print 'new command: <%r>' % cmd # dbg |
|
2093 | 2093 | return cmd |
|
2094 | 2094 | |
|
2095 | 2095 | def call_alias(self,alias,rest=''): |
|
2096 | 2096 | """Call an alias given its name and the rest of the line. |
|
2097 | 2097 | |
|
2098 | 2098 | This is only used to provide backwards compatibility for users of |
|
2099 | 2099 | ipalias(), use of which is not recommended for anymore.""" |
|
2100 | 2100 | |
|
2101 | 2101 | # Now call the macro, evaluating in the user's namespace |
|
2102 | 2102 | cmd = self.transform_alias(alias, rest) |
|
2103 | 2103 | try: |
|
2104 | 2104 | self.system(cmd) |
|
2105 | 2105 | except: |
|
2106 | 2106 | self.showtraceback() |
|
2107 | 2107 | |
|
2108 | 2108 | def indent_current_str(self): |
|
2109 | 2109 | """return the current level of indentation as a string""" |
|
2110 | 2110 | return self.indent_current_nsp * ' ' |
|
2111 | 2111 | |
|
2112 | 2112 | def autoindent_update(self,line): |
|
2113 | 2113 | """Keep track of the indent level.""" |
|
2114 | 2114 | |
|
2115 | 2115 | #debugx('line') |
|
2116 | 2116 | #debugx('self.indent_current_nsp') |
|
2117 | 2117 | if self.autoindent: |
|
2118 | 2118 | if line: |
|
2119 | 2119 | inisp = num_ini_spaces(line) |
|
2120 | 2120 | if inisp < self.indent_current_nsp: |
|
2121 | 2121 | self.indent_current_nsp = inisp |
|
2122 | 2122 | |
|
2123 | 2123 | if line[-1] == ':': |
|
2124 | 2124 | self.indent_current_nsp += 4 |
|
2125 | 2125 | elif dedent_re.match(line): |
|
2126 | 2126 | self.indent_current_nsp -= 4 |
|
2127 | 2127 | else: |
|
2128 | 2128 | self.indent_current_nsp = 0 |
|
2129 | 2129 | |
|
2130 | 2130 | def runlines(self,lines): |
|
2131 | 2131 | """Run a string of one or more lines of source. |
|
2132 | 2132 | |
|
2133 | 2133 | This method is capable of running a string containing multiple source |
|
2134 | 2134 | lines, as if they had been entered at the IPython prompt. Since it |
|
2135 | 2135 | exposes IPython's processing machinery, the given strings can contain |
|
2136 | 2136 | magic calls (%magic), special shell access (!cmd), etc.""" |
|
2137 | 2137 | |
|
2138 | 2138 | # We must start with a clean buffer, in case this is run from an |
|
2139 | 2139 | # interactive IPython session (via a magic, for example). |
|
2140 | 2140 | self.resetbuffer() |
|
2141 | 2141 | lines = lines.split('\n') |
|
2142 | 2142 | more = 0 |
|
2143 | 2143 | |
|
2144 | 2144 | for line in lines: |
|
2145 | 2145 | # skip blank lines so we don't mess up the prompt counter, but do |
|
2146 | 2146 | # NOT skip even a blank line if we are in a code block (more is |
|
2147 | 2147 | # true) |
|
2148 | 2148 | |
|
2149 | 2149 | if line or more: |
|
2150 | 2150 | # push to raw history, so hist line numbers stay in sync |
|
2151 | 2151 | self.input_hist_raw.append("# " + line + "\n") |
|
2152 | 2152 | more = self.push(self.prefilter(line,more)) |
|
2153 | 2153 | # IPython's runsource returns None if there was an error |
|
2154 | 2154 | # compiling the code. This allows us to stop processing right |
|
2155 | 2155 | # away, so the user gets the error message at the right place. |
|
2156 | 2156 | if more is None: |
|
2157 | 2157 | break |
|
2158 | 2158 | else: |
|
2159 | 2159 | self.input_hist_raw.append("\n") |
|
2160 | 2160 | # final newline in case the input didn't have it, so that the code |
|
2161 | 2161 | # actually does get executed |
|
2162 | 2162 | if more: |
|
2163 | 2163 | self.push('\n') |
|
2164 | 2164 | |
|
2165 | 2165 | def runsource(self, source, filename='<input>', symbol='single'): |
|
2166 | 2166 | """Compile and run some source in the interpreter. |
|
2167 | 2167 | |
|
2168 | 2168 | Arguments are as for compile_command(). |
|
2169 | 2169 | |
|
2170 | 2170 | One several things can happen: |
|
2171 | 2171 | |
|
2172 | 2172 | 1) The input is incorrect; compile_command() raised an |
|
2173 | 2173 | exception (SyntaxError or OverflowError). A syntax traceback |
|
2174 | 2174 | will be printed by calling the showsyntaxerror() method. |
|
2175 | 2175 | |
|
2176 | 2176 | 2) The input is incomplete, and more input is required; |
|
2177 | 2177 | compile_command() returned None. Nothing happens. |
|
2178 | 2178 | |
|
2179 | 2179 | 3) The input is complete; compile_command() returned a code |
|
2180 | 2180 | object. The code is executed by calling self.runcode() (which |
|
2181 | 2181 | also handles run-time exceptions, except for SystemExit). |
|
2182 | 2182 | |
|
2183 | 2183 | The return value is: |
|
2184 | 2184 | |
|
2185 | 2185 | - True in case 2 |
|
2186 | 2186 | |
|
2187 | 2187 | - False in the other cases, unless an exception is raised, where |
|
2188 | 2188 | None is returned instead. This can be used by external callers to |
|
2189 | 2189 | know whether to continue feeding input or not. |
|
2190 | 2190 | |
|
2191 | 2191 | The return value can be used to decide whether to use sys.ps1 or |
|
2192 | 2192 | sys.ps2 to prompt the next line.""" |
|
2193 | 2193 | |
|
2194 | 2194 | # if the source code has leading blanks, add 'if 1:\n' to it |
|
2195 | 2195 | # this allows execution of indented pasted code. It is tempting |
|
2196 | 2196 | # to add '\n' at the end of source to run commands like ' a=1' |
|
2197 | 2197 | # directly, but this fails for more complicated scenarios |
|
2198 | 2198 | source=source.encode(self.stdin_encoding) |
|
2199 | 2199 | if source[:1] in [' ', '\t']: |
|
2200 | 2200 | source = 'if 1:\n%s' % source |
|
2201 | 2201 | |
|
2202 | 2202 | try: |
|
2203 | 2203 | code = self.compile(source,filename,symbol) |
|
2204 | 2204 | except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError): |
|
2205 | 2205 | # Case 1 |
|
2206 | 2206 | self.showsyntaxerror(filename) |
|
2207 | 2207 | return None |
|
2208 | 2208 | |
|
2209 | 2209 | if code is None: |
|
2210 | 2210 | # Case 2 |
|
2211 | 2211 | return True |
|
2212 | 2212 | |
|
2213 | 2213 | # Case 3 |
|
2214 | 2214 | # We store the code object so that threaded shells and |
|
2215 | 2215 | # custom exception handlers can access all this info if needed. |
|
2216 | 2216 | # The source corresponding to this can be obtained from the |
|
2217 | 2217 | # buffer attribute as '\n'.join(self.buffer). |
|
2218 | 2218 | self.code_to_run = code |
|
2219 | 2219 | # now actually execute the code object |
|
2220 | 2220 | if self.runcode(code) == 0: |
|
2221 | 2221 | return False |
|
2222 | 2222 | else: |
|
2223 | 2223 | return None |
|
2224 | 2224 | |
|
2225 | 2225 | def runcode(self,code_obj): |
|
2226 | 2226 | """Execute a code object. |
|
2227 | 2227 | |
|
2228 | 2228 | When an exception occurs, self.showtraceback() is called to display a |
|
2229 | 2229 | traceback. |
|
2230 | 2230 | |
|
2231 | 2231 | Return value: a flag indicating whether the code to be run completed |
|
2232 | 2232 | successfully: |
|
2233 | 2233 | |
|
2234 | 2234 | - 0: successful execution. |
|
2235 | 2235 | - 1: an error occurred. |
|
2236 | 2236 | """ |
|
2237 | 2237 | |
|
2238 | 2238 | # Set our own excepthook in case the user code tries to call it |
|
2239 | 2239 | # directly, so that the IPython crash handler doesn't get triggered |
|
2240 | 2240 | old_excepthook,sys.excepthook = sys.excepthook, self.excepthook |
|
2241 | 2241 | |
|
2242 | 2242 | # we save the original sys.excepthook in the instance, in case config |
|
2243 | 2243 | # code (such as magics) needs access to it. |
|
2244 | 2244 | self.sys_excepthook = old_excepthook |
|
2245 | 2245 | outflag = 1 # happens in more places, so it's easier as default |
|
2246 | 2246 | try: |
|
2247 | 2247 | try: |
|
2248 | 2248 | self.hooks.pre_runcode_hook() |
|
2249 | 2249 | exec code_obj in self.user_global_ns, self.user_ns |
|
2250 | 2250 | finally: |
|
2251 | 2251 | # Reset our crash handler in place |
|
2252 | 2252 | sys.excepthook = old_excepthook |
|
2253 | 2253 | except SystemExit: |
|
2254 | 2254 | self.resetbuffer() |
|
2255 | 2255 | self.showtraceback() |
|
2256 | 2256 | warn("Type %exit or %quit to exit IPython " |
|
2257 | 2257 | "(%Exit or %Quit do so unconditionally).",level=1) |
|
2258 | 2258 | except self.custom_exceptions: |
|
2259 | 2259 | etype,value,tb = sys.exc_info() |
|
2260 | 2260 | self.CustomTB(etype,value,tb) |
|
2261 | 2261 | except: |
|
2262 | 2262 | self.showtraceback() |
|
2263 | 2263 | else: |
|
2264 | 2264 | outflag = 0 |
|
2265 | 2265 | if softspace(sys.stdout, 0): |
|
2266 | 2266 | |
|
2267 | 2267 | # Flush out code object which has been run (and source) |
|
2268 | 2268 | self.code_to_run = None |
|
2269 | 2269 | return outflag |
|
2270 | 2270 | |
|
2271 | 2271 | def push(self, line): |
|
2272 | 2272 | """Push a line to the interpreter. |
|
2273 | 2273 | |
|
2274 | 2274 | The line should not have a trailing newline; it may have |
|
2275 | 2275 | internal newlines. The line is appended to a buffer and the |
|
2276 | 2276 | interpreter's runsource() method is called with the |
|
2277 | 2277 | concatenated contents of the buffer as source. If this |
|
2278 | 2278 | indicates that the command was executed or invalid, the buffer |
|
2279 | 2279 | is reset; otherwise, the command is incomplete, and the buffer |
|
2280 | 2280 | is left as it was after the line was appended. The return |
|
2281 | 2281 | value is 1 if more input is required, 0 if the line was dealt |
|
2282 | 2282 | with in some way (this is the same as runsource()). |
|
2283 | 2283 | """ |
|
2284 | 2284 | |
|
2285 | 2285 | # autoindent management should be done here, and not in the |
|
2286 | 2286 | # interactive loop, since that one is only seen by keyboard input. We |
|
2287 | 2287 | # need this done correctly even for code run via runlines (which uses |
|
2288 | 2288 | # push). |
|
2289 | 2289 | |
|
2290 | 2290 | #print 'push line: <%s>' % line # dbg |
|
2291 | 2291 | for subline in line.splitlines(): |
|
2292 | 2292 | self.autoindent_update(subline) |
|
2293 | 2293 | self.buffer.append(line) |
|
2294 | 2294 | more = self.runsource('\n'.join(self.buffer), self.filename) |
|
2295 | 2295 | if not more: |
|
2296 | 2296 | self.resetbuffer() |
|
2297 | 2297 | return more |
|
2298 | 2298 | |
|
2299 | 2299 | def split_user_input(self, line): |
|
2300 | 2300 | # This is really a hold-over to support ipapi and some extensions |
|
2301 | 2301 | return prefilter.splitUserInput(line) |
|
2302 | 2302 | |
|
2303 | 2303 | def resetbuffer(self): |
|
2304 | 2304 | """Reset the input buffer.""" |
|
2305 | 2305 | self.buffer[:] = [] |
|
2306 | 2306 | |
|
2307 | 2307 | def raw_input(self,prompt='',continue_prompt=False): |
|
2308 | 2308 | """Write a prompt and read a line. |
|
2309 | 2309 | |
|
2310 | 2310 | The returned line does not include the trailing newline. |
|
2311 | 2311 | When the user enters the EOF key sequence, EOFError is raised. |
|
2312 | 2312 | |
|
2313 | 2313 | Optional inputs: |
|
2314 | 2314 | |
|
2315 | 2315 | - prompt(''): a string to be printed to prompt the user. |
|
2316 | 2316 | |
|
2317 | 2317 | - continue_prompt(False): whether this line is the first one or a |
|
2318 | 2318 | continuation in a sequence of inputs. |
|
2319 | 2319 | """ |
|
2320 | 2320 | |
|
2321 | 2321 | # Code run by the user may have modified the readline completer state. |
|
2322 | 2322 | # We must ensure that our completer is back in place. |
|
2323 | 2323 | if self.has_readline: |
|
2324 | 2324 | self.set_completer() |
|
2325 | 2325 | |
|
2326 | 2326 | try: |
|
2327 | 2327 | line = raw_input_original(prompt).decode(self.stdin_encoding) |
|
2328 | 2328 | except ValueError: |
|
2329 | 2329 | warn("\n********\nYou or a %run:ed script called sys.stdin.close()" |
|
2330 | 2330 | " or sys.stdout.close()!\nExiting IPython!") |
|
2331 | 2331 | self.ask_exit() |
|
2332 | 2332 | return "" |
|
2333 | 2333 | |
|
2334 | 2334 | # Try to be reasonably smart about not re-indenting pasted input more |
|
2335 | 2335 | # than necessary. We do this by trimming out the auto-indent initial |
|
2336 | 2336 | # spaces, if the user's actual input started itself with whitespace. |
|
2337 | 2337 | #debugx('self.buffer[-1]') |
|
2338 | 2338 | |
|
2339 | 2339 | if self.autoindent: |
|
2340 | 2340 | if num_ini_spaces(line) > self.indent_current_nsp: |
|
2341 | 2341 | line = line[self.indent_current_nsp:] |
|
2342 | 2342 | self.indent_current_nsp = 0 |
|
2343 | 2343 | |
|
2344 | 2344 | # store the unfiltered input before the user has any chance to modify |
|
2345 | 2345 | # it. |
|
2346 | 2346 | if line.strip(): |
|
2347 | 2347 | if continue_prompt: |
|
2348 | 2348 | self.input_hist_raw[-1] += '%s\n' % line |
|
2349 | 2349 | if self.has_readline: # and some config option is set? |
|
2350 | 2350 | try: |
|
2351 | 2351 | histlen = self.readline.get_current_history_length() |
|
2352 | 2352 | if histlen > 1: |
|
2353 | 2353 | newhist = self.input_hist_raw[-1].rstrip() |
|
2354 | 2354 | self.readline.remove_history_item(histlen-1) |
|
2355 | 2355 | self.readline.replace_history_item(histlen-2, |
|
2356 | 2356 | newhist.encode(self.stdin_encoding)) |
|
2357 | 2357 | except AttributeError: |
|
2358 | 2358 | pass # re{move,place}_history_item are new in 2.4. |
|
2359 | 2359 | else: |
|
2360 | 2360 | self.input_hist_raw.append('%s\n' % line) |
|
2361 | 2361 | # only entries starting at first column go to shadow history |
|
2362 | 2362 | if line.lstrip() == line: |
|
2363 | 2363 | self.shadowhist.add(line.strip()) |
|
2364 | 2364 | elif not continue_prompt: |
|
2365 | 2365 | self.input_hist_raw.append('\n') |
|
2366 | 2366 | try: |
|
2367 | 2367 | lineout = self.prefilter(line,continue_prompt) |
|
2368 | 2368 | except: |
|
2369 | 2369 | # blanket except, in case a user-defined prefilter crashes, so it |
|
2370 | 2370 | # can't take all of ipython with it. |
|
2371 | 2371 | self.showtraceback() |
|
2372 | 2372 | return '' |
|
2373 | 2373 | else: |
|
2374 | 2374 | return lineout |
|
2375 | 2375 | |
|
2376 | 2376 | def _prefilter(self, line, continue_prompt): |
|
2377 | 2377 | """Calls different preprocessors, depending on the form of line.""" |
|
2378 | 2378 | |
|
2379 | 2379 | # All handlers *must* return a value, even if it's blank (''). |
|
2380 | 2380 | |
|
2381 | 2381 | # Lines are NOT logged here. Handlers should process the line as |
|
2382 | 2382 | # needed, update the cache AND log it (so that the input cache array |
|
2383 | 2383 | # stays synced). |
|
2384 | 2384 | |
|
2385 | 2385 | #..................................................................... |
|
2386 | 2386 | # Code begins |
|
2387 | 2387 | |
|
2388 | 2388 | #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg |
|
2389 | 2389 | |
|
2390 | 2390 | # save the line away in case we crash, so the post-mortem handler can |
|
2391 | 2391 | # record it |
|
2392 | 2392 | self._last_input_line = line |
|
2393 | 2393 | |
|
2394 | 2394 | #print '***line: <%s>' % line # dbg |
|
2395 | 2395 | |
|
2396 | 2396 | if not line: |
|
2397 | 2397 | # Return immediately on purely empty lines, so that if the user |
|
2398 | 2398 | # previously typed some whitespace that started a continuation |
|
2399 | 2399 | # prompt, he can break out of that loop with just an empty line. |
|
2400 | 2400 | # This is how the default python prompt works. |
|
2401 | 2401 | |
|
2402 | 2402 | # Only return if the accumulated input buffer was just whitespace! |
|
2403 | 2403 | if ''.join(self.buffer).isspace(): |
|
2404 | 2404 | self.buffer[:] = [] |
|
2405 | 2405 | return '' |
|
2406 | 2406 | |
|
2407 | 2407 | line_info = prefilter.LineInfo(line, continue_prompt) |
|
2408 | 2408 | |
|
2409 | 2409 | # the input history needs to track even empty lines |
|
2410 | 2410 | stripped = line.strip() |
|
2411 | 2411 | |
|
2412 | 2412 | if not stripped: |
|
2413 | 2413 | if not continue_prompt: |
|
2414 | 2414 | self.outputcache.prompt_count -= 1 |
|
2415 | 2415 | return self.handle_normal(line_info) |
|
2416 | 2416 | |
|
2417 | 2417 | # print '***cont',continue_prompt # dbg |
|
2418 | 2418 | # special handlers are only allowed for single line statements |
|
2419 | 2419 | if continue_prompt and not self.rc.multi_line_specials: |
|
2420 | 2420 | return self.handle_normal(line_info) |
|
2421 | 2421 | |
|
2422 | 2422 | |
|
2423 | 2423 | # See whether any pre-existing handler can take care of it |
|
2424 | 2424 | rewritten = self.hooks.input_prefilter(stripped) |
|
2425 | 2425 | if rewritten != stripped: # ok, some prefilter did something |
|
2426 | 2426 | rewritten = line_info.pre + rewritten # add indentation |
|
2427 | 2427 | return self.handle_normal(prefilter.LineInfo(rewritten, |
|
2428 | 2428 | continue_prompt)) |
|
2429 | 2429 | |
|
2430 | 2430 | #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg |
|
2431 | 2431 | |
|
2432 | 2432 | return prefilter.prefilter(line_info, self) |
|
2433 | 2433 | |
|
2434 | 2434 | |
|
2435 | 2435 | def _prefilter_dumb(self, line, continue_prompt): |
|
2436 | 2436 | """simple prefilter function, for debugging""" |
|
2437 | 2437 | return self.handle_normal(line,continue_prompt) |
|
2438 | 2438 | |
|
2439 | 2439 | |
|
2440 | 2440 | def multiline_prefilter(self, line, continue_prompt): |
|
2441 | 2441 | """ Run _prefilter for each line of input |
|
2442 | 2442 | |
|
2443 | 2443 | Covers cases where there are multiple lines in the user entry, |
|
2444 | 2444 | which is the case when the user goes back to a multiline history |
|
2445 | 2445 | entry and presses enter. |
|
2446 | 2446 | |
|
2447 | 2447 | """ |
|
2448 | 2448 | out = [] |
|
2449 | 2449 | for l in line.rstrip('\n').split('\n'): |
|
2450 | 2450 | out.append(self._prefilter(l, continue_prompt)) |
|
2451 | 2451 | return '\n'.join(out) |
|
2452 | 2452 | |
|
2453 | 2453 | # Set the default prefilter() function (this can be user-overridden) |
|
2454 | 2454 | prefilter = multiline_prefilter |
|
2455 | 2455 | |
|
2456 | 2456 | def handle_normal(self,line_info): |
|
2457 | 2457 | """Handle normal input lines. Use as a template for handlers.""" |
|
2458 | 2458 | |
|
2459 | 2459 | # With autoindent on, we need some way to exit the input loop, and I |
|
2460 | 2460 | # don't want to force the user to have to backspace all the way to |
|
2461 | 2461 | # clear the line. The rule will be in this case, that either two |
|
2462 | 2462 | # lines of pure whitespace in a row, or a line of pure whitespace but |
|
2463 | 2463 | # of a size different to the indent level, will exit the input loop. |
|
2464 | 2464 | line = line_info.line |
|
2465 | 2465 | continue_prompt = line_info.continue_prompt |
|
2466 | 2466 | |
|
2467 | 2467 | if (continue_prompt and self.autoindent and line.isspace() and |
|
2468 | 2468 | (0 < abs(len(line) - self.indent_current_nsp) <= 2 or |
|
2469 | 2469 | (self.buffer[-1]).isspace() )): |
|
2470 | 2470 | line = '' |
|
2471 | 2471 | |
|
2472 | 2472 | self.log(line,line,continue_prompt) |
|
2473 | 2473 | return line |
|
2474 | 2474 | |
|
2475 | 2475 | def handle_alias(self,line_info): |
|
2476 | 2476 | """Handle alias input lines. """ |
|
2477 | 2477 | tgt = self.alias_table[line_info.iFun] |
|
2478 | 2478 | # print "=>",tgt #dbg |
|
2479 | 2479 | if callable(tgt): |
|
2480 | 2480 | if '$' in line_info.line: |
|
2481 | 2481 | call_meth = '(_ip, _ip.itpl(%s))' |
|
2482 | 2482 | else: |
|
2483 | 2483 | call_meth = '(_ip,%s)' |
|
2484 | 2484 | line_out = ("%s_sh.%s" + call_meth) % (line_info.preWhitespace, |
|
2485 | 2485 | line_info.iFun, |
|
2486 | 2486 | make_quoted_expr(line_info.line)) |
|
2487 | 2487 | else: |
|
2488 | 2488 | transformed = self.expand_aliases(line_info.iFun,line_info.theRest) |
|
2489 | 2489 | |
|
2490 | 2490 | # pre is needed, because it carries the leading whitespace. Otherwise |
|
2491 | 2491 | # aliases won't work in indented sections. |
|
2492 | 2492 | line_out = '%s_ip.system(%s)' % (line_info.preWhitespace, |
|
2493 | 2493 | make_quoted_expr( transformed )) |
|
2494 | 2494 | |
|
2495 | 2495 | self.log(line_info.line,line_out,line_info.continue_prompt) |
|
2496 | 2496 | #print 'line out:',line_out # dbg |
|
2497 | 2497 | return line_out |
|
2498 | 2498 | |
|
2499 | 2499 | def handle_shell_escape(self, line_info): |
|
2500 | 2500 | """Execute the line in a shell, empty return value""" |
|
2501 | 2501 | #print 'line in :', `line` # dbg |
|
2502 | 2502 | line = line_info.line |
|
2503 | 2503 | if line.lstrip().startswith('!!'): |
|
2504 | 2504 | # rewrite LineInfo's line, iFun and theRest to properly hold the |
|
2505 | 2505 | # call to %sx and the actual command to be executed, so |
|
2506 | 2506 | # handle_magic can work correctly. Note that this works even if |
|
2507 | 2507 | # the line is indented, so it handles multi_line_specials |
|
2508 | 2508 | # properly. |
|
2509 | 2509 | new_rest = line.lstrip()[2:] |
|
2510 | 2510 | line_info.line = '%ssx %s' % (self.ESC_MAGIC,new_rest) |
|
2511 | 2511 | line_info.iFun = 'sx' |
|
2512 | 2512 | line_info.theRest = new_rest |
|
2513 | 2513 | return self.handle_magic(line_info) |
|
2514 | 2514 | else: |
|
2515 | 2515 | cmd = line.lstrip().lstrip('!') |
|
2516 | 2516 | line_out = '%s_ip.system(%s)' % (line_info.preWhitespace, |
|
2517 | 2517 | make_quoted_expr(cmd)) |
|
2518 | 2518 | # update cache/log and return |
|
2519 | 2519 | self.log(line,line_out,line_info.continue_prompt) |
|
2520 | 2520 | return line_out |
|
2521 | 2521 | |
|
2522 | 2522 | def handle_magic(self, line_info): |
|
2523 | 2523 | """Execute magic functions.""" |
|
2524 | 2524 | iFun = line_info.iFun |
|
2525 | 2525 | theRest = line_info.theRest |
|
2526 | 2526 | cmd = '%s_ip.magic(%s)' % (line_info.preWhitespace, |
|
2527 | 2527 | make_quoted_expr(iFun + " " + theRest)) |
|
2528 | 2528 | self.log(line_info.line,cmd,line_info.continue_prompt) |
|
2529 | 2529 | #print 'in handle_magic, cmd=<%s>' % cmd # dbg |
|
2530 | 2530 | return cmd |
|
2531 | 2531 | |
|
2532 | 2532 | def handle_auto(self, line_info): |
|
2533 | 2533 | """Hande lines which can be auto-executed, quoting if requested.""" |
|
2534 | 2534 | |
|
2535 | 2535 | line = line_info.line |
|
2536 | 2536 | iFun = line_info.iFun |
|
2537 | 2537 | theRest = line_info.theRest |
|
2538 | 2538 | pre = line_info.pre |
|
2539 | 2539 | continue_prompt = line_info.continue_prompt |
|
2540 | 2540 | obj = line_info.ofind(self)['obj'] |
|
2541 | 2541 | |
|
2542 | 2542 | #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg |
|
2543 | 2543 | |
|
2544 | 2544 | # This should only be active for single-line input! |
|
2545 | 2545 | if continue_prompt: |
|
2546 | 2546 | self.log(line,line,continue_prompt) |
|
2547 | 2547 | return line |
|
2548 | 2548 | |
|
2549 | 2549 | force_auto = isinstance(obj, IPython.ipapi.IPyAutocall) |
|
2550 | 2550 | auto_rewrite = True |
|
2551 | 2551 | |
|
2552 | 2552 | if pre == self.ESC_QUOTE: |
|
2553 | 2553 | # Auto-quote splitting on whitespace |
|
2554 | 2554 | newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) ) |
|
2555 | 2555 | elif pre == self.ESC_QUOTE2: |
|
2556 | 2556 | # Auto-quote whole string |
|
2557 | 2557 | newcmd = '%s("%s")' % (iFun,theRest) |
|
2558 | 2558 | elif pre == self.ESC_PAREN: |
|
2559 | 2559 | newcmd = '%s(%s)' % (iFun,",".join(theRest.split())) |
|
2560 | 2560 | else: |
|
2561 | 2561 | # Auto-paren. |
|
2562 | 2562 | # We only apply it to argument-less calls if the autocall |
|
2563 | 2563 | # parameter is set to 2. We only need to check that autocall is < |
|
2564 | 2564 | # 2, since this function isn't called unless it's at least 1. |
|
2565 | 2565 | if not theRest and (self.rc.autocall < 2) and not force_auto: |
|
2566 | 2566 | newcmd = '%s %s' % (iFun,theRest) |
|
2567 | 2567 | auto_rewrite = False |
|
2568 | 2568 | else: |
|
2569 | 2569 | if not force_auto and theRest.startswith('['): |
|
2570 | 2570 | if hasattr(obj,'__getitem__'): |
|
2571 | 2571 | # Don't autocall in this case: item access for an object |
|
2572 | 2572 | # which is BOTH callable and implements __getitem__. |
|
2573 | 2573 | newcmd = '%s %s' % (iFun,theRest) |
|
2574 | 2574 | auto_rewrite = False |
|
2575 | 2575 | else: |
|
2576 | 2576 | # if the object doesn't support [] access, go ahead and |
|
2577 | 2577 | # autocall |
|
2578 | 2578 | newcmd = '%s(%s)' % (iFun.rstrip(),theRest) |
|
2579 | 2579 | elif theRest.endswith(';'): |
|
2580 | 2580 | newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1]) |
|
2581 | 2581 | else: |
|
2582 | 2582 | newcmd = '%s(%s)' % (iFun.rstrip(), theRest) |
|
2583 | 2583 | |
|
2584 | 2584 | if auto_rewrite: |
|
2585 | 2585 | rw = self.outputcache.prompt1.auto_rewrite() + newcmd |
|
2586 | 2586 | |
|
2587 | 2587 | try: |
|
2588 | 2588 | # plain ascii works better w/ pyreadline, on some machines, so |
|
2589 | 2589 | # we use it and only print uncolored rewrite if we have unicode |
|
2590 | 2590 | rw = str(rw) |
|
2591 | 2591 | print >>Term.cout, rw |
|
2592 | 2592 | except UnicodeEncodeError: |
|
2593 | 2593 | print "-------------->" + newcmd |
|
2594 | 2594 | |
|
2595 | 2595 | # log what is now valid Python, not the actual user input (without the |
|
2596 | 2596 | # final newline) |
|
2597 | 2597 | self.log(line,newcmd,continue_prompt) |
|
2598 | 2598 | return newcmd |
|
2599 | 2599 | |
|
2600 | 2600 | def handle_help(self, line_info): |
|
2601 | 2601 | """Try to get some help for the object. |
|
2602 | 2602 | |
|
2603 | 2603 | obj? or ?obj -> basic information. |
|
2604 | 2604 | obj?? or ??obj -> more details. |
|
2605 | 2605 | """ |
|
2606 | 2606 | |
|
2607 | 2607 | line = line_info.line |
|
2608 | 2608 | # We need to make sure that we don't process lines which would be |
|
2609 | 2609 | # otherwise valid python, such as "x=1 # what?" |
|
2610 | 2610 | try: |
|
2611 | 2611 | codeop.compile_command(line) |
|
2612 | 2612 | except SyntaxError: |
|
2613 | 2613 | # We should only handle as help stuff which is NOT valid syntax |
|
2614 | 2614 | if line[0]==self.ESC_HELP: |
|
2615 | 2615 | line = line[1:] |
|
2616 | 2616 | elif line[-1]==self.ESC_HELP: |
|
2617 | 2617 | line = line[:-1] |
|
2618 | 2618 | self.log(line,'#?'+line,line_info.continue_prompt) |
|
2619 | 2619 | if line: |
|
2620 | 2620 | #print 'line:<%r>' % line # dbg |
|
2621 | 2621 | self.magic_pinfo(line) |
|
2622 | 2622 | else: |
|
2623 | 2623 | page(self.usage,screen_lines=self.rc.screen_length) |
|
2624 | 2624 | return '' # Empty string is needed here! |
|
2625 | 2625 | except: |
|
2626 | 2626 | # Pass any other exceptions through to the normal handler |
|
2627 | 2627 | return self.handle_normal(line_info) |
|
2628 | 2628 | else: |
|
2629 | 2629 | # If the code compiles ok, we should handle it normally |
|
2630 | 2630 | return self.handle_normal(line_info) |
|
2631 | 2631 | |
|
2632 | 2632 | def getapi(self): |
|
2633 | 2633 | """ Get an IPApi object for this shell instance |
|
2634 | 2634 | |
|
2635 | 2635 | Getting an IPApi object is always preferable to accessing the shell |
|
2636 | 2636 | directly, but this holds true especially for extensions. |
|
2637 | 2637 | |
|
2638 | 2638 | It should always be possible to implement an extension with IPApi |
|
2639 | 2639 | alone. If not, contact maintainer to request an addition. |
|
2640 | 2640 | |
|
2641 | 2641 | """ |
|
2642 | 2642 | return self.api |
|
2643 | 2643 | |
|
2644 | 2644 | def handle_emacs(self, line_info): |
|
2645 | 2645 | """Handle input lines marked by python-mode.""" |
|
2646 | 2646 | |
|
2647 | 2647 | # Currently, nothing is done. Later more functionality can be added |
|
2648 | 2648 | # here if needed. |
|
2649 | 2649 | |
|
2650 | 2650 | # The input cache shouldn't be updated |
|
2651 | 2651 | return line_info.line |
|
2652 | 2652 | |
|
2653 | 2653 | |
|
2654 | 2654 | def mktempfile(self,data=None): |
|
2655 | 2655 | """Make a new tempfile and return its filename. |
|
2656 | 2656 | |
|
2657 | 2657 | This makes a call to tempfile.mktemp, but it registers the created |
|
2658 | 2658 | filename internally so ipython cleans it up at exit time. |
|
2659 | 2659 | |
|
2660 | 2660 | Optional inputs: |
|
2661 | 2661 | |
|
2662 | 2662 | - data(None): if data is given, it gets written out to the temp file |
|
2663 | 2663 | immediately, and the file is closed again.""" |
|
2664 | 2664 | |
|
2665 | 2665 | filename = tempfile.mktemp('.py','ipython_edit_') |
|
2666 | 2666 | self.tempfiles.append(filename) |
|
2667 | 2667 | |
|
2668 | 2668 | if data: |
|
2669 | 2669 | tmp_file = open(filename,'w') |
|
2670 | 2670 | tmp_file.write(data) |
|
2671 | 2671 | tmp_file.close() |
|
2672 | 2672 | return filename |
|
2673 | 2673 | |
|
2674 | 2674 | def write(self,data): |
|
2675 | 2675 | """Write a string to the default output""" |
|
2676 | 2676 | Term.cout.write(data) |
|
2677 | 2677 | |
|
2678 | 2678 | def write_err(self,data): |
|
2679 | 2679 | """Write a string to the default error output""" |
|
2680 | 2680 | Term.cerr.write(data) |
|
2681 | 2681 | |
|
2682 | 2682 | def ask_exit(self): |
|
2683 | 2683 | """ Call for exiting. Can be overiden and used as a callback. """ |
|
2684 | 2684 | self.exit_now = True |
|
2685 | 2685 | |
|
2686 | 2686 | def exit(self): |
|
2687 | 2687 | """Handle interactive exit. |
|
2688 | 2688 | |
|
2689 | 2689 | This method calls the ask_exit callback.""" |
|
2690 | 2690 | |
|
2691 | 2691 | if self.rc.confirm_exit: |
|
2692 | 2692 | if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'): |
|
2693 | 2693 | self.ask_exit() |
|
2694 | 2694 | else: |
|
2695 | 2695 | self.ask_exit() |
|
2696 | 2696 | |
|
2697 | 2697 | def safe_execfile(self,fname,*where,**kw): |
|
2698 | 2698 | """A safe version of the builtin execfile(). |
|
2699 | 2699 | |
|
2700 | 2700 | This version will never throw an exception, and knows how to handle |
|
2701 | 2701 | ipython logs as well. |
|
2702 | 2702 | |
|
2703 | 2703 | :Parameters: |
|
2704 | 2704 | fname : string |
|
2705 | 2705 | Name of the file to be executed. |
|
2706 | 2706 | |
|
2707 | 2707 | where : tuple |
|
2708 | 2708 | One or two namespaces, passed to execfile() as (globals,locals). |
|
2709 | 2709 | If only one is given, it is passed as both. |
|
2710 | 2710 | |
|
2711 | 2711 | :Keywords: |
|
2712 | 2712 | islog : boolean (False) |
|
2713 | 2713 | |
|
2714 | 2714 | quiet : boolean (True) |
|
2715 | 2715 | |
|
2716 | 2716 | exit_ignore : boolean (False) |
|
2717 | 2717 | """ |
|
2718 | 2718 | |
|
2719 | 2719 | def syspath_cleanup(): |
|
2720 | 2720 | """Internal cleanup routine for sys.path.""" |
|
2721 | 2721 | if add_dname: |
|
2722 | 2722 | try: |
|
2723 | 2723 | sys.path.remove(dname) |
|
2724 | 2724 | except ValueError: |
|
2725 | 2725 | # For some reason the user has already removed it, ignore. |
|
2726 | 2726 | pass |
|
2727 | 2727 | |
|
2728 | 2728 | fname = os.path.expanduser(fname) |
|
2729 | 2729 | |
|
2730 | 2730 | # Find things also in current directory. This is needed to mimic the |
|
2731 | 2731 | # behavior of running a script from the system command line, where |
|
2732 | 2732 | # Python inserts the script's directory into sys.path |
|
2733 | 2733 | dname = os.path.dirname(os.path.abspath(fname)) |
|
2734 | 2734 | add_dname = False |
|
2735 | 2735 | if dname not in sys.path: |
|
2736 | 2736 | sys.path.insert(0,dname) |
|
2737 | 2737 | add_dname = True |
|
2738 | 2738 | |
|
2739 | 2739 | try: |
|
2740 | 2740 | xfile = open(fname) |
|
2741 | 2741 | except: |
|
2742 | 2742 | print >> Term.cerr, \ |
|
2743 | 2743 | 'Could not open file <%s> for safe execution.' % fname |
|
2744 | 2744 | syspath_cleanup() |
|
2745 | 2745 | return None |
|
2746 | 2746 | |
|
2747 | 2747 | kw.setdefault('islog',0) |
|
2748 | 2748 | kw.setdefault('quiet',1) |
|
2749 | 2749 | kw.setdefault('exit_ignore',0) |
|
2750 | 2750 | |
|
2751 | 2751 | first = xfile.readline() |
|
2752 | 2752 | loghead = str(self.loghead_tpl).split('\n',1)[0].strip() |
|
2753 | 2753 | xfile.close() |
|
2754 | 2754 | # line by line execution |
|
2755 | 2755 | if first.startswith(loghead) or kw['islog']: |
|
2756 | 2756 | print 'Loading log file <%s> one line at a time...' % fname |
|
2757 | 2757 | if kw['quiet']: |
|
2758 | 2758 | stdout_save = sys.stdout |
|
2759 | 2759 | sys.stdout = StringIO.StringIO() |
|
2760 | 2760 | try: |
|
2761 | 2761 | globs,locs = where[0:2] |
|
2762 | 2762 | except: |
|
2763 | 2763 | try: |
|
2764 | 2764 | globs = locs = where[0] |
|
2765 | 2765 | except: |
|
2766 | 2766 | globs = locs = globals() |
|
2767 | 2767 | badblocks = [] |
|
2768 | 2768 | |
|
2769 | 2769 | # we also need to identify indented blocks of code when replaying |
|
2770 | 2770 | # logs and put them together before passing them to an exec |
|
2771 | 2771 | # statement. This takes a bit of regexp and look-ahead work in the |
|
2772 | 2772 | # file. It's easiest if we swallow the whole thing in memory |
|
2773 | 2773 | # first, and manually walk through the lines list moving the |
|
2774 | 2774 | # counter ourselves. |
|
2775 | 2775 | indent_re = re.compile('\s+\S') |
|
2776 | 2776 | xfile = open(fname) |
|
2777 | 2777 | filelines = xfile.readlines() |
|
2778 | 2778 | xfile.close() |
|
2779 | 2779 | nlines = len(filelines) |
|
2780 | 2780 | lnum = 0 |
|
2781 | 2781 | while lnum < nlines: |
|
2782 | 2782 | line = filelines[lnum] |
|
2783 | 2783 | lnum += 1 |
|
2784 | 2784 | # don't re-insert logger status info into cache |
|
2785 | 2785 | if line.startswith('#log#'): |
|
2786 | 2786 | continue |
|
2787 | 2787 | else: |
|
2788 | 2788 | # build a block of code (maybe a single line) for execution |
|
2789 | 2789 | block = line |
|
2790 | 2790 | try: |
|
2791 | 2791 | next = filelines[lnum] # lnum has already incremented |
|
2792 | 2792 | except: |
|
2793 | 2793 | next = None |
|
2794 | 2794 | while next and indent_re.match(next): |
|
2795 | 2795 | block += next |
|
2796 | 2796 | lnum += 1 |
|
2797 | 2797 | try: |
|
2798 | 2798 | next = filelines[lnum] |
|
2799 | 2799 | except: |
|
2800 | 2800 | next = None |
|
2801 | 2801 | # now execute the block of one or more lines |
|
2802 | 2802 | try: |
|
2803 | 2803 | exec block in globs,locs |
|
2804 | 2804 | except SystemExit: |
|
2805 | 2805 | pass |
|
2806 | 2806 | except: |
|
2807 | 2807 | badblocks.append(block.rstrip()) |
|
2808 | 2808 | if kw['quiet']: # restore stdout |
|
2809 | 2809 | sys.stdout.close() |
|
2810 | 2810 | sys.stdout = stdout_save |
|
2811 | 2811 | print 'Finished replaying log file <%s>' % fname |
|
2812 | 2812 | if badblocks: |
|
2813 | 2813 | print >> sys.stderr, ('\nThe following lines/blocks in file ' |
|
2814 | 2814 | '<%s> reported errors:' % fname) |
|
2815 | 2815 | |
|
2816 | 2816 | for badline in badblocks: |
|
2817 | 2817 | print >> sys.stderr, badline |
|
2818 | 2818 | else: # regular file execution |
|
2819 | 2819 | try: |
|
2820 | 2820 | if sys.platform == 'win32' and sys.version_info < (2,5,1): |
|
2821 | 2821 | # Work around a bug in Python for Windows. The bug was |
|
2822 | 2822 | # fixed in in Python 2.5 r54159 and 54158, but that's still |
|
2823 | 2823 | # SVN Python as of March/07. For details, see: |
|
2824 | 2824 | # http://projects.scipy.org/ipython/ipython/ticket/123 |
|
2825 | 2825 | try: |
|
2826 | 2826 | globs,locs = where[0:2] |
|
2827 | 2827 | except: |
|
2828 | 2828 | try: |
|
2829 | 2829 | globs = locs = where[0] |
|
2830 | 2830 | except: |
|
2831 | 2831 | globs = locs = globals() |
|
2832 | 2832 | exec file(fname) in globs,locs |
|
2833 | 2833 | else: |
|
2834 | 2834 | execfile(fname,*where) |
|
2835 | 2835 | except SyntaxError: |
|
2836 | 2836 | self.showsyntaxerror() |
|
2837 | 2837 | warn('Failure executing file: <%s>' % fname) |
|
2838 | 2838 | except SystemExit,status: |
|
2839 | 2839 | # Code that correctly sets the exit status flag to success (0) |
|
2840 | 2840 | # shouldn't be bothered with a traceback. Note that a plain |
|
2841 | 2841 | # sys.exit() does NOT set the message to 0 (it's empty) so that |
|
2842 | 2842 | # will still get a traceback. Note that the structure of the |
|
2843 | 2843 | # SystemExit exception changed between Python 2.4 and 2.5, so |
|
2844 | 2844 | # the checks must be done in a version-dependent way. |
|
2845 | 2845 | show = False |
|
2846 | 2846 | |
|
2847 | 2847 | if sys.version_info[:2] > (2,5): |
|
2848 | 2848 | if status.message!=0 and not kw['exit_ignore']: |
|
2849 | 2849 | show = True |
|
2850 | 2850 | else: |
|
2851 | 2851 | if status.code and not kw['exit_ignore']: |
|
2852 | 2852 | show = True |
|
2853 | 2853 | if show: |
|
2854 | 2854 | self.showtraceback() |
|
2855 | 2855 | warn('Failure executing file: <%s>' % fname) |
|
2856 | 2856 | except: |
|
2857 | 2857 | self.showtraceback() |
|
2858 | 2858 | warn('Failure executing file: <%s>' % fname) |
|
2859 | 2859 | |
|
2860 | 2860 | syspath_cleanup() |
|
2861 | 2861 | |
|
2862 | 2862 | #************************* end of file <iplib.py> ***************************** |
|
1 | NO CONTENT: file renamed from IPython/background_jobs.py to IPython/lib/backgroundjobs.py |
@@ -1,300 +1,300 b'' | |||
|
1 | 1 | # -*- coding: utf-8 -*- |
|
2 | 2 | """IPython Test Suite Runner. |
|
3 | 3 | |
|
4 | 4 | This module provides a main entry point to a user script to test IPython |
|
5 | 5 | itself from the command line. There are two ways of running this script: |
|
6 | 6 | |
|
7 | 7 | 1. With the syntax `iptest all`. This runs our entire test suite by |
|
8 | 8 | calling this script (with different arguments) or trial recursively. This |
|
9 | 9 | causes modules and package to be tested in different processes, using nose |
|
10 | 10 | or trial where appropriate. |
|
11 | 11 | 2. With the regular nose syntax, like `iptest -vvs IPython`. In this form |
|
12 | 12 | the script simply calls nose, but with special command line flags and |
|
13 | 13 | plugins loaded. |
|
14 | 14 | |
|
15 | 15 | For now, this script requires that both nose and twisted are installed. This |
|
16 | 16 | will change in the future. |
|
17 | 17 | """ |
|
18 | 18 | |
|
19 | 19 | #----------------------------------------------------------------------------- |
|
20 | 20 | # Module imports |
|
21 | 21 | #----------------------------------------------------------------------------- |
|
22 | 22 | |
|
23 | 23 | import os |
|
24 | 24 | import os.path as path |
|
25 | 25 | import sys |
|
26 | 26 | import subprocess |
|
27 | 27 | import time |
|
28 | 28 | import warnings |
|
29 | 29 | |
|
30 | 30 | import nose.plugins.builtin |
|
31 | 31 | from nose.core import TestProgram |
|
32 | 32 | |
|
33 | 33 | from IPython.platutils import find_cmd |
|
34 | 34 | from IPython.testing.plugin.ipdoctest import IPythonDoctest |
|
35 | 35 | |
|
36 | 36 | pjoin = path.join |
|
37 | 37 | |
|
38 | 38 | #----------------------------------------------------------------------------- |
|
39 | 39 | # Logic for skipping doctests |
|
40 | 40 | #----------------------------------------------------------------------------- |
|
41 | 41 | |
|
42 | 42 | def test_for(mod): |
|
43 | 43 | """Test to see if mod is importable.""" |
|
44 | 44 | try: |
|
45 | 45 | __import__(mod) |
|
46 | 46 | except ImportError: |
|
47 | 47 | return False |
|
48 | 48 | else: |
|
49 | 49 | return True |
|
50 | 50 | |
|
51 | 51 | have_curses = test_for('_curses') |
|
52 | 52 | have_wx = test_for('wx') |
|
53 | 53 | have_zi = test_for('zope.interface') |
|
54 | 54 | have_twisted = test_for('twisted') |
|
55 | 55 | have_foolscap = test_for('foolscap') |
|
56 | 56 | have_objc = test_for('objc') |
|
57 | 57 | have_pexpect = test_for('pexpect') |
|
58 | 58 | |
|
59 | 59 | # For the IPythonDoctest plugin, we need to exclude certain patterns that cause |
|
60 | 60 | # testing problems. We should strive to minimize the number of skipped |
|
61 | 61 | # modules, since this means untested code. As the testing machinery |
|
62 | 62 | # solidifies, this list should eventually become empty. |
|
63 | 63 | EXCLUDE = [pjoin('IPython', 'external'), |
|
64 | 64 | pjoin('IPython', 'frontend', 'process', 'winprocess.py'), |
|
65 | 65 | pjoin('IPython_doctest_plugin'), |
|
66 | 66 | pjoin('IPython', 'Gnuplot'), |
|
67 | 67 | pjoin('IPython', 'Extensions', 'ipy_'), |
|
68 | 68 | pjoin('IPython', 'Extensions', 'clearcmd'), |
|
69 | 69 | pjoin('IPython', 'Extensions', 'PhysicalQInteractive'), |
|
70 | 70 | pjoin('IPython', 'Extensions', 'scitedirector'), |
|
71 | 71 | pjoin('IPython', 'Extensions', 'numeric_formats'), |
|
72 | 72 | pjoin('IPython', 'testing', 'attic'), |
|
73 | 73 | pjoin('IPython', 'testing', 'tutils'), |
|
74 | 74 | pjoin('IPython', 'testing', 'tools'), |
|
75 | 75 | pjoin('IPython', 'testing', 'mkdoctests') |
|
76 | 76 | ] |
|
77 | 77 | |
|
78 | 78 | if not have_wx: |
|
79 | 79 | EXCLUDE.append(pjoin('IPython', 'Extensions', 'igrid')) |
|
80 | 80 | EXCLUDE.append(pjoin('IPython', 'gui')) |
|
81 | 81 | EXCLUDE.append(pjoin('IPython', 'frontend', 'wx')) |
|
82 | 82 | |
|
83 | 83 | if not have_objc: |
|
84 | 84 | EXCLUDE.append(pjoin('IPython', 'frontend', 'cocoa')) |
|
85 | 85 | |
|
86 | 86 | if not have_curses: |
|
87 | 87 | EXCLUDE.append(pjoin('IPython', 'Extensions', 'ibrowse')) |
|
88 | 88 | |
|
89 | 89 | if not sys.platform == 'win32': |
|
90 | 90 | EXCLUDE.append(pjoin('IPython', 'platutils_win32')) |
|
91 | 91 | |
|
92 | 92 | # These have to be skipped on win32 because the use echo, rm, cd, etc. |
|
93 | 93 | # See ticket https://bugs.launchpad.net/bugs/366982 |
|
94 | 94 | if sys.platform == 'win32': |
|
95 | 95 | EXCLUDE.append(pjoin('IPython', 'testing', 'plugin', 'test_exampleip')) |
|
96 | 96 | EXCLUDE.append(pjoin('IPython', 'testing', 'plugin', 'dtexample')) |
|
97 | 97 | |
|
98 | 98 | if not os.name == 'posix': |
|
99 | 99 | EXCLUDE.append(pjoin('IPython', 'platutils_posix')) |
|
100 | 100 | |
|
101 | 101 | if not have_pexpect: |
|
102 | 102 | EXCLUDE.append(pjoin('IPython', 'irunner')) |
|
103 | 103 | |
|
104 | 104 | # This is needed for the reg-exp to match on win32 in the ipdoctest plugin. |
|
105 | 105 | if sys.platform == 'win32': |
|
106 | 106 | EXCLUDE = [s.replace('\\','\\\\') for s in EXCLUDE] |
|
107 | 107 | |
|
108 | 108 | |
|
109 | 109 | #----------------------------------------------------------------------------- |
|
110 | 110 | # Functions and classes |
|
111 | 111 | #----------------------------------------------------------------------------- |
|
112 | 112 | |
|
113 | 113 | def run_iptest(): |
|
114 | 114 | """Run the IPython test suite using nose. |
|
115 | 115 | |
|
116 | 116 | This function is called when this script is **not** called with the form |
|
117 | 117 | `iptest all`. It simply calls nose with appropriate command line flags |
|
118 | 118 | and accepts all of the standard nose arguments. |
|
119 | 119 | """ |
|
120 | 120 | |
|
121 | 121 | warnings.filterwarnings('ignore', |
|
122 | 122 | 'This will be removed soon. Use IPython.testing.util instead') |
|
123 | 123 | |
|
124 | 124 | argv = sys.argv + [ |
|
125 | 125 | # Loading ipdoctest causes problems with Twisted. |
|
126 | 126 | # I am removing this as a temporary fix to get the |
|
127 | 127 | # test suite back into working shape. Our nose |
|
128 | 128 | # plugin needs to be gone through with a fine |
|
129 | 129 | # toothed comb to find what is causing the problem. |
|
130 | 130 | '--with-ipdoctest', |
|
131 | 131 | '--ipdoctest-tests','--ipdoctest-extension=txt', |
|
132 | 132 | '--detailed-errors', |
|
133 | 133 | |
|
134 | 134 | # We add --exe because of setuptools' imbecility (it |
|
135 | 135 | # blindly does chmod +x on ALL files). Nose does the |
|
136 | 136 | # right thing and it tries to avoid executables, |
|
137 | 137 | # setuptools unfortunately forces our hand here. This |
|
138 | 138 | # has been discussed on the distutils list and the |
|
139 | 139 | # setuptools devs refuse to fix this problem! |
|
140 | 140 | '--exe', |
|
141 | 141 | ] |
|
142 | 142 | |
|
143 | 143 | # Detect if any tests were required by explicitly calling an IPython |
|
144 | 144 | # submodule or giving a specific path |
|
145 | 145 | has_tests = False |
|
146 | 146 | for arg in sys.argv: |
|
147 | 147 | if 'IPython' in arg or arg.endswith('.py') or \ |
|
148 | 148 | (':' in arg and '.py' in arg): |
|
149 | 149 | has_tests = True |
|
150 | 150 | break |
|
151 | 151 | |
|
152 | 152 | # If nothing was specifically requested, test full IPython |
|
153 | 153 | if not has_tests: |
|
154 | 154 | argv.append('IPython') |
|
155 | 155 | |
|
156 | 156 | # Construct list of plugins, omitting the existing doctest plugin, which |
|
157 | 157 | # ours replaces (and extends). |
|
158 | 158 | plugins = [IPythonDoctest(EXCLUDE)] |
|
159 | 159 | for p in nose.plugins.builtin.plugins: |
|
160 | 160 | plug = p() |
|
161 | 161 | if plug.name == 'doctest': |
|
162 | 162 | continue |
|
163 | 163 | |
|
164 | 164 | #print '*** adding plugin:',plug.name # dbg |
|
165 | 165 | plugins.append(plug) |
|
166 | 166 | |
|
167 | 167 | TestProgram(argv=argv,plugins=plugins) |
|
168 | 168 | |
|
169 | 169 | |
|
170 | 170 | class IPTester(object): |
|
171 | 171 | """Call that calls iptest or trial in a subprocess. |
|
172 | 172 | """ |
|
173 | 173 | def __init__(self,runner='iptest',params=None): |
|
174 | 174 | """ """ |
|
175 | 175 | if runner == 'iptest': |
|
176 | 176 | self.runner = ['iptest','-v'] |
|
177 | 177 | else: |
|
178 | 178 | self.runner = [find_cmd('trial')] |
|
179 | 179 | if params is None: |
|
180 | 180 | params = [] |
|
181 | 181 | if isinstance(params,str): |
|
182 | 182 | params = [params] |
|
183 | 183 | self.params = params |
|
184 | 184 | |
|
185 | 185 | # Assemble call |
|
186 | 186 | self.call_args = self.runner+self.params |
|
187 | 187 | |
|
188 | 188 | def run(self): |
|
189 | 189 | """Run the stored commands""" |
|
190 | 190 | return subprocess.call(self.call_args) |
|
191 | 191 | |
|
192 | 192 | |
|
193 | 193 | def make_runners(): |
|
194 | 194 | """Define the modules and packages that need to be tested. |
|
195 | 195 | """ |
|
196 | 196 | |
|
197 | 197 | # This omits additional top-level modules that should not be doctested. |
|
198 | 198 | # XXX: Shell.py is also ommited because of a bug in the skip_doctest |
|
199 | 199 | # decorator. See ticket https://bugs.launchpad.net/bugs/366209 |
|
200 | 200 | top_mod = \ |
|
201 |
['background |
|
|
201 | ['backgroundjobs.py', 'coloransi.py', 'completer.py', 'ConfigLoader.py', | |
|
202 | 202 | 'CrashHandler.py', 'Debugger.py', 'deep_reload.py', 'demo.py', |
|
203 | 203 | 'DPyGetOpt.py', 'dtutils.py', 'excolors.py', 'FakeModule.py', |
|
204 | 204 | 'generics.py', 'genutils.py', 'history.py', 'hooks.py', 'ipapi.py', |
|
205 | 205 | 'iplib.py', 'ipmaker.py', 'ipstruct.py', 'Itpl.py', |
|
206 | 206 | 'Logger.py', 'macro.py', 'Magic.py', 'OInspect.py', |
|
207 | 207 | 'OutputTrap.py', 'platutils.py', 'prefilter.py', 'Prompts.py', |
|
208 | 208 | 'PyColorize.py', 'Release.py', 'rlineimpl.py', 'shadowns.py', |
|
209 | 209 | 'shellglobals.py', 'strdispatch.py', 'twshell.py', |
|
210 | 210 | 'ultraTB.py', 'upgrade_dir.py', 'usage.py', 'wildcard.py', |
|
211 | 211 | # See note above for why this is skipped |
|
212 | 212 | # 'Shell.py', |
|
213 | 213 | 'winconsole.py'] |
|
214 | 214 | |
|
215 | 215 | if have_pexpect: |
|
216 | 216 | top_mod.append('irunner.py') |
|
217 | 217 | |
|
218 | 218 | if sys.platform == 'win32': |
|
219 | 219 | top_mod.append('platutils_win32.py') |
|
220 | 220 | elif os.name == 'posix': |
|
221 | 221 | top_mod.append('platutils_posix.py') |
|
222 | 222 | else: |
|
223 | 223 | top_mod.append('platutils_dummy.py') |
|
224 | 224 | |
|
225 | 225 | # These are tested by nose, so skip IPython.kernel |
|
226 | 226 | top_pack = ['config','Extensions','frontend', |
|
227 | 227 | 'testing','tests','tools','UserConfig'] |
|
228 | 228 | |
|
229 | 229 | if have_wx: |
|
230 | 230 | top_pack.append('gui') |
|
231 | 231 | |
|
232 | 232 | modules = ['IPython.%s' % m[:-3] for m in top_mod ] |
|
233 | 233 | packages = ['IPython.%s' % m for m in top_pack ] |
|
234 | 234 | |
|
235 | 235 | # Make runners |
|
236 | 236 | runners = dict(zip(top_pack, [IPTester(params=v) for v in packages])) |
|
237 | 237 | |
|
238 | 238 | # Test IPython.kernel using trial if twisted is installed |
|
239 | 239 | if have_zi and have_twisted and have_foolscap: |
|
240 | 240 | runners['trial'] = IPTester('trial',['IPython']) |
|
241 | 241 | |
|
242 | 242 | runners['modules'] = IPTester(params=modules) |
|
243 | 243 | |
|
244 | 244 | return runners |
|
245 | 245 | |
|
246 | 246 | |
|
247 | 247 | def run_iptestall(): |
|
248 | 248 | """Run the entire IPython test suite by calling nose and trial. |
|
249 | 249 | |
|
250 | 250 | This function constructs :class:`IPTester` instances for all IPython |
|
251 | 251 | modules and package and then runs each of them. This causes the modules |
|
252 | 252 | and packages of IPython to be tested each in their own subprocess using |
|
253 | 253 | nose or twisted.trial appropriately. |
|
254 | 254 | """ |
|
255 | 255 | runners = make_runners() |
|
256 | 256 | # Run all test runners, tracking execution time |
|
257 | 257 | failed = {} |
|
258 | 258 | t_start = time.time() |
|
259 | 259 | for name,runner in runners.iteritems(): |
|
260 | 260 | print '*'*77 |
|
261 | 261 | print 'IPython test set:',name |
|
262 | 262 | res = runner.run() |
|
263 | 263 | if res: |
|
264 | 264 | failed[name] = res |
|
265 | 265 | t_end = time.time() |
|
266 | 266 | t_tests = t_end - t_start |
|
267 | 267 | nrunners = len(runners) |
|
268 | 268 | nfail = len(failed) |
|
269 | 269 | # summarize results |
|
270 | 270 | |
|
271 | 271 | print '*'*77 |
|
272 | 272 | print 'Ran %s test sets in %.3fs' % (nrunners, t_tests) |
|
273 | 273 | |
|
274 | 274 | if not failed: |
|
275 | 275 | print 'OK' |
|
276 | 276 | else: |
|
277 | 277 | # If anything went wrong, point out what command to rerun manually to |
|
278 | 278 | # see the actual errors and individual summary |
|
279 | 279 | print 'ERROR - %s out of %s test sets failed.' % (nfail, nrunners) |
|
280 | 280 | for name in failed: |
|
281 | 281 | failed_runner = runners[name] |
|
282 | 282 | print '-'*40 |
|
283 | 283 | print 'Runner failed:',name |
|
284 | 284 | print 'You may wish to rerun this one individually, with:' |
|
285 | 285 | print ' '.join(failed_runner.call_args) |
|
286 | 286 | |
|
287 | 287 | |
|
288 | 288 | |
|
289 | 289 | def main(): |
|
290 | 290 | if len(sys.argv) == 1: |
|
291 | 291 | run_iptestall() |
|
292 | 292 | else: |
|
293 | 293 | if sys.argv[1] == 'all': |
|
294 | 294 | run_iptestall() |
|
295 | 295 | else: |
|
296 | 296 | run_iptest() |
|
297 | 297 | |
|
298 | 298 | |
|
299 | 299 | if __name__ == '__main__': |
|
300 | 300 | main() No newline at end of file |
@@ -1,239 +1,238 b'' | |||
|
1 | 1 | ============================= |
|
2 | 2 | IPython module reorganization |
|
3 | 3 | ============================= |
|
4 | 4 | |
|
5 | 5 | Currently, IPython has many top-level modules that serve many different purposes. |
|
6 | 6 | The lack of organization make it very difficult for developers to work on IPython |
|
7 | 7 | and understand its design. This document contains notes about how we will reorganize |
|
8 | 8 | the modules into sub-packages. |
|
9 | 9 | |
|
10 | 10 | .. warning:: |
|
11 | 11 | |
|
12 | 12 | This effort will possibly break third party packages that use IPython as |
|
13 | 13 | a library or hack on the IPython internals. |
|
14 | 14 | |
|
15 | 15 | .. warning:: |
|
16 | 16 | |
|
17 | 17 | This effort will result in the removal from IPython of certain modules |
|
18 | 18 | that are not used anymore, don't currently work, are unmaintained, etc. |
|
19 | 19 | |
|
20 | 20 | |
|
21 | 21 | Current subpackges |
|
22 | 22 | ================== |
|
23 | 23 | |
|
24 | 24 | IPython currently has the following sub-packages: |
|
25 | 25 | |
|
26 | 26 | * :mod:`IPython.config` |
|
27 | 27 | |
|
28 | 28 | * :mod:`IPython.Extensions` |
|
29 | 29 | |
|
30 | 30 | * :mod:`IPython.external` |
|
31 | 31 | |
|
32 | 32 | * :mod:`IPython.frontend` |
|
33 | 33 | |
|
34 | 34 | * :mod:`IPython.gui` |
|
35 | 35 | |
|
36 | 36 | * :mod:`IPython.kernel` |
|
37 | 37 | |
|
38 | 38 | * :mod:`IPython.testing` |
|
39 | 39 | |
|
40 | 40 | * :mod:`IPython.tests` |
|
41 | 41 | |
|
42 | 42 | * :mod:`IPython.tools` |
|
43 | 43 | |
|
44 | 44 | * :mod:`IPython.UserConfig` |
|
45 | 45 | |
|
46 | 46 | New Subpackages to be created |
|
47 | 47 | ============================= |
|
48 | 48 | |
|
49 | 49 | We propose to create the following new sub-packages: |
|
50 | 50 | |
|
51 | 51 | * :mod:`IPython.core`. This sub-package will contain the core of the IPython |
|
52 | 52 | interpreter, but none of its extended capabilities. |
|
53 | 53 | |
|
54 | 54 | * :mod:`IPython.lib`. IPython has many extended capabilities that are not part |
|
55 | 55 | of the IPython core. These things will go here. Any better names than |
|
56 | 56 | :mod:`IPython.lib`? |
|
57 | 57 | |
|
58 | 58 | * :mod:`IPython.utils`. This sub-package will contain anything that might |
|
59 | 59 | eventually be found in the Python standard library, like things in |
|
60 | 60 | :mod:`genutils`. Each sub-module in this sub-package should contain |
|
61 | 61 | functions and classes that serve a single purpose. |
|
62 | 62 | |
|
63 | 63 | * :mod:`IPython.deathrow`. This is for code that is untested and/or rotting |
|
64 | 64 | and needs to be removed from IPython. Eventually all this code will either |
|
65 | 65 | i) be revived by someone willing to maintain it with tests and docs and |
|
66 | 66 | re-included into IPython or 2) be removed from IPython proper, but put into |
|
67 | 67 | a separate top-level (not IPython) package that we keep around. No new code |
|
68 | 68 | will be allowed here. |
|
69 | 69 | |
|
70 | 70 | * :mod:`IPython.quarantine`. This is for code that doesn't meet IPython's |
|
71 | 71 | standards, but that we plan on keeping. To be moved out of this sub-package |
|
72 | 72 | a module needs to have a maintainer, tests and documentation. |
|
73 | 73 | |
|
74 | 74 | Prodecure |
|
75 | 75 | ========= |
|
76 | 76 | |
|
77 | 77 | 1. Move the file to its new location with its new name. |
|
78 | 78 | 2. Rename all import statements to reflect the change. |
|
79 | 79 | 3. Run PyFlakes on each changes module. |
|
80 | 80 | 3. Add tests/test_imports.py to test it. |
|
81 | 81 | |
|
82 | 82 | Need to modify iptests to properly skip modules that are no longer top |
|
83 | 83 | level modules. |
|
84 | 84 | |
|
85 | 85 | Where things will be moved |
|
86 | 86 | ========================== |
|
87 | 87 | |
|
88 |
* :file:`ColorANSI.py`. Move to :file:`IPython/ |
|
|
89 | :mod:`IPython.lib` or :mod:`IPython.python`? | |
|
88 | * :file:`ColorANSI.py`. Move to :file:`IPython/utils/coloransi.py`. | |
|
90 | 89 | |
|
91 | 90 | * :file:`ConfigLoader.py`. Move to :file:`IPython/config/configloader.py`. |
|
92 | 91 | |
|
93 | 92 | * :file:`CrashHandler.py`. Move to :file:`IPython/core/crashhandler`. |
|
94 | 93 | |
|
95 | 94 | * :file:`DPyGetOpt.py`. Move to :mod:`IPython.sandbox` and replace with newer options parser. |
|
96 | 95 | |
|
97 | 96 | * :file:`Debugger.py`. Move to :file:`IPython/core/debugger.py`. |
|
98 | 97 | |
|
99 | 98 | * :file:`Extensions`. This needs to be gone through separately. Minimally, |
|
100 | 99 | the package should be renamed to :file:`extensions`. |
|
101 | 100 | |
|
102 | 101 | * :file:`FakeModule.py`. Move to :file:`IPython/core/fakemodule.py`. |
|
103 | 102 | |
|
104 | 103 | * :file:`Gnuplot2.py`. Move to :file:`IPython.sandbox`. |
|
105 | 104 | |
|
106 | 105 | * :file:`GnuplotInteractive.py`. Move to :file:`IPython.sandbox`. |
|
107 | 106 | |
|
108 | 107 | * :file:`GnuplotRuntime.py`. Move to :file:`IPython.sandbox`. |
|
109 | 108 | |
|
110 | 109 | * :file:`Itpl.py`. Remove. Version already in :file:`IPython.external`. |
|
111 | 110 | |
|
112 | 111 | * :file:`Logger.py`. Move to :file:`IPython/core/logger.py`. |
|
113 | 112 | |
|
114 | 113 | * :file:`Magic.py`. Move to :file:`IPython/core/magic.py`. |
|
115 | 114 | |
|
116 | 115 | * :file:`OInspect.py`. Move to :file:`IPython/core/oinspect.py`. |
|
117 | 116 | |
|
118 | 117 | * :file:`OutputTrap.py`. Move to :file:`IPython/core/outputtrap.py`. |
|
119 | 118 | |
|
120 | 119 | * :file:`Prompts.py`. Move to :file:`IPython/core/prompts.py` or |
|
121 | 120 | :file:`IPython/frontend/prompts.py`. |
|
122 | 121 | |
|
123 | 122 | * :file:`PyColorize.py`. Replace with pygments? If not, move to |
|
124 | 123 | :file:`IPython/core/pycolorize.py`. Maybe move to :mod:`IPython.lib` or |
|
125 | 124 | :mod:`IPython.python`? |
|
126 | 125 | |
|
127 | 126 | * :file:`Release.py`. Move to ??? or remove? |
|
128 | 127 | |
|
129 | 128 | * :file:`Shell.py`. Move to :file:`IPython.core.shell.py` or |
|
130 | 129 | :file:`IPython/frontend/shell.py`. |
|
131 | 130 | |
|
132 | 131 | * :file:`UserConfig`. Move to a subdirectory of :file:`IPython.config`. |
|
133 | 132 | |
|
134 | 133 | * :file:`background_jobs.py`. Move to :file:`IPython/lib/backgroundjobs.py`. |
|
135 | 134 | |
|
136 | 135 | * :file:`completer.py`. Move to :file:`IPython/core/completer.py`. |
|
137 | 136 | |
|
138 | 137 | * :file:`config`. Good where it is! |
|
139 | 138 | |
|
140 | 139 | * :file:`deep_reload.py`. Move to :file:`IPython/lib/deepreload.py`. |
|
141 | 140 | |
|
142 | 141 | * :file:`demo.py`. Move to :file:`IPython/lib/demo.py`. |
|
143 | 142 | |
|
144 | 143 | * :file:`dtutils.py`. Remove or move to :file:`IPython.testing` or |
|
145 | 144 | :file:`IPython.lib`. |
|
146 | 145 | |
|
147 | 146 | * :file:`excolors.py`. Move to :file:`IPython.core` or :file:`IPython.config`. |
|
148 | 147 | Maybe move to :mod:`IPython.lib` or :mod:`IPython.python`? |
|
149 | 148 | |
|
150 | 149 | * :file:`external`. Good where it is! |
|
151 | 150 | |
|
152 | 151 | * :file:`frontend`. Good where it is! |
|
153 | 152 | |
|
154 | 153 | * :file:`generics.py`. Move to :file:`IPython.python`. |
|
155 | 154 | |
|
156 | 155 | * :file:`genutils.py`. Move to :file:`IPython.python` and break up into different |
|
157 | 156 | modules. |
|
158 | 157 | |
|
159 | 158 | * :file:`gui`. Eventually this should be moved to a subdir of |
|
160 | 159 | :file:`IPython.frontend`. |
|
161 | 160 | |
|
162 | 161 | * :file:`history.py`. Move to :file:`IPython.core`. |
|
163 | 162 | |
|
164 | 163 | * :file:`hooks.py`. Move to :file:`IPython.core`. |
|
165 | 164 | |
|
166 | 165 | * :file:`ipapi.py`. Move to :file:`IPython.core`. |
|
167 | 166 | |
|
168 | 167 | * :file:`iplib.py`. Move to :file:`IPython.core`. |
|
169 | 168 | |
|
170 | 169 | * :file:`ipmaker.py`: Move to :file:`IPython.core`. |
|
171 | 170 | |
|
172 | 171 | * :file:`ipstruct.py`. Move to :file:`IPython.python`. |
|
173 | 172 | |
|
174 | 173 | * :file:`irunner.py`. Move to :file:`IPython.scripts`. |
|
175 | 174 | |
|
176 | 175 | * :file:`kernel`. Good where it is. |
|
177 | 176 | |
|
178 | 177 | * :file:`macro.py`. Move to :file:`IPython.core`. |
|
179 | 178 | |
|
180 | 179 | * :file:`numutils.py`. Move to :file:`IPython.sandbox`. |
|
181 | 180 | |
|
182 | 181 | * :file:`platutils.py`. Move to :file:`IPython.python`. |
|
183 | 182 | |
|
184 | 183 | * :file:`platutils_dummy.py`. Move to :file:`IPython.python`. |
|
185 | 184 | |
|
186 | 185 | * :file:`platutils_posix.py`. Move to :file:`IPython.python`. |
|
187 | 186 | |
|
188 | 187 | * :file:`platutils_win32.py`. Move to :file:`IPython.python`. |
|
189 | 188 | |
|
190 | 189 | * :file:`prefilter.py`: Move to :file:`IPython.core`. |
|
191 | 190 | |
|
192 | 191 | * :file:`rlineimpl.py`. Move to :file:`IPython.core`. |
|
193 | 192 | |
|
194 | 193 | * :file:`shadowns.py`. Move to :file:`IPython.core`. |
|
195 | 194 | |
|
196 | 195 | * :file:`shellglobals.py`. Move to :file:`IPython.core`. |
|
197 | 196 | |
|
198 | 197 | * :file:`strdispatch.py`. Move to :file:`IPython.python`. |
|
199 | 198 | |
|
200 | 199 | * :file:`testing`. Good where it is. |
|
201 | 200 | |
|
202 | 201 | * :file:`tests`. Good where it is. |
|
203 | 202 | |
|
204 | 203 | * :file:`tools`. Things in here need to be looked at and moved elsewhere like |
|
205 | 204 | :file:`IPython.python`. |
|
206 | 205 | |
|
207 | 206 | * :file:`twshell.py`. Move to :file:`IPython.sandbox`. |
|
208 | 207 | |
|
209 | 208 | * :file:`ultraTB.py`. Move to :file:`IPython/core/ultratb.py`. |
|
210 | 209 | |
|
211 | 210 | * :file:`upgrade_dir.py`. Move to :file:`IPython/python/upgradedir.py`. |
|
212 | 211 | |
|
213 | 212 | * :file:`usage.py`. Move to :file:`IPython.core`. |
|
214 | 213 | |
|
215 | 214 | * :file:`wildcard.py`. Move to :file:`IPython.python` or :file:`IPython.core`. |
|
216 | 215 | |
|
217 | 216 | * :file:`winconsole.py`. Move to :file:`IPython.lib`. |
|
218 | 217 | |
|
219 | 218 | Other things |
|
220 | 219 | ============ |
|
221 | 220 | |
|
222 | 221 | When these files are moved around, a number of other things will happen at the same time: |
|
223 | 222 | |
|
224 | 223 | 1. Test files will be created for each module in IPython. Minimally, all |
|
225 | 224 | modules will be imported as a part of the test. This will serve as a |
|
226 | 225 | test of the module reorganization. These tests will be put into new |
|
227 | 226 | :file:`tests` subdirectories that each package will have. |
|
228 | 227 | |
|
229 | 228 | 2. PyFlakes and other code checkers will be run to look for problems. |
|
230 | 229 | |
|
231 | 230 | 3. Modules will be renamed to comply with PEP 8 naming conventions: all |
|
232 | 231 | lowercase and no special characters like ``-`` or ``_``. |
|
233 | 232 | |
|
234 | 233 | 4. Existing tests will be moved to the appropriate :file:`tests` |
|
235 | 234 | subdirectories. |
|
236 | 235 | |
|
237 | 236 | |
|
238 | 237 | |
|
239 | 238 |
General Comments 0
You need to be logged in to leave comments.
Login now