Show More
The requested changes are too big and content was truncated. Show full diff
@@ -1,2579 +1,2592 b'' | |||
|
1 | 1 | # -*- coding: utf-8 -*- |
|
2 | 2 | """Magic functions for InteractiveShell. |
|
3 | 3 | |
|
4 |
$Id: Magic.py 96 |
|
|
4 | $Id: Magic.py 962 2005-12-28 18:04:59Z fperez $""" | |
|
5 | 5 | |
|
6 | 6 | #***************************************************************************** |
|
7 | 7 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and |
|
8 | 8 | # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu> |
|
9 | 9 | # |
|
10 | 10 | # Distributed under the terms of the BSD License. The full license is in |
|
11 | 11 | # the file COPYING, distributed as part of this software. |
|
12 | 12 | #***************************************************************************** |
|
13 | 13 | |
|
14 | 14 | #**************************************************************************** |
|
15 | 15 | # Modules and globals |
|
16 | 16 | |
|
17 | 17 | from IPython import Release |
|
18 | 18 | __author__ = '%s <%s>\n%s <%s>' % \ |
|
19 | 19 | ( Release.authors['Janko'] + Release.authors['Fernando'] ) |
|
20 | 20 | __license__ = Release.license |
|
21 | 21 | |
|
22 | 22 | # Python standard modules |
|
23 | 23 | import __builtin__ |
|
24 | 24 | import bdb |
|
25 | 25 | import inspect |
|
26 | 26 | import os |
|
27 | 27 | import pdb |
|
28 | 28 | import pydoc |
|
29 | 29 | import sys |
|
30 | 30 | import re |
|
31 | 31 | import tempfile |
|
32 | 32 | import time |
|
33 | 33 | from cStringIO import StringIO |
|
34 | 34 | from getopt import getopt |
|
35 | 35 | from pprint import pprint, pformat |
|
36 | 36 | |
|
37 | 37 | # profile isn't bundled by default in Debian for license reasons |
|
38 | 38 | try: |
|
39 | 39 | import profile,pstats |
|
40 | 40 | except ImportError: |
|
41 | 41 | profile = pstats = None |
|
42 | 42 | |
|
43 | 43 | # Homebrewed |
|
44 | 44 | from IPython import Debugger, OInspect, wildcard |
|
45 | 45 | from IPython.FakeModule import FakeModule |
|
46 | 46 | from IPython.Itpl import Itpl, itpl, printpl,itplns |
|
47 | 47 | from IPython.PyColorize import Parser |
|
48 | 48 | from IPython.Struct import Struct |
|
49 | 49 | from IPython.genutils import * |
|
50 | 50 | |
|
51 | 51 | # Globals to be set later by Magic constructor |
|
52 | 52 | MAGIC_PREFIX = '' |
|
53 | 53 | MAGIC_ESCAPE = '' |
|
54 | 54 | |
|
55 | 55 | #*************************************************************************** |
|
56 | 56 | # Utility functions |
|
57 | 57 | def magic2python(cmd): |
|
58 | 58 | """Convert a command string of magic syntax to valid Python code.""" |
|
59 | 59 | |
|
60 | 60 | if cmd.startswith('#'+MAGIC_ESCAPE) or \ |
|
61 | 61 | cmd.startswith(MAGIC_ESCAPE): |
|
62 | 62 | if cmd[0]=='#': |
|
63 | 63 | cmd = cmd[1:] |
|
64 | 64 | # we need to return the proper line end later |
|
65 | 65 | if cmd[-1] == '\n': |
|
66 | 66 | endl = '\n' |
|
67 | 67 | else: |
|
68 | 68 | endl = '' |
|
69 | 69 | try: |
|
70 | 70 | func,args = cmd[1:].split(' ',1) |
|
71 | 71 | except: |
|
72 | 72 | func,args = cmd[1:].rstrip(),'' |
|
73 | 73 | args = args.replace('"','\\"').replace("'","\\'").rstrip() |
|
74 | 74 | return '%s%s ("%s")%s' % (MAGIC_PREFIX,func,args,endl) |
|
75 | 75 | else: |
|
76 | 76 | return cmd |
|
77 | 77 | |
|
78 | 78 | def on_off(tag): |
|
79 | 79 | """Return an ON/OFF string for a 1/0 input. Simple utility function.""" |
|
80 | 80 | return ['OFF','ON'][tag] |
|
81 | 81 | |
|
82 | 82 | |
|
83 | 83 | #**************************************************************************** |
|
84 | 84 | # Utility classes |
|
85 | 85 | class Macro: |
|
86 | 86 | """Simple class to store the value of macros as strings. |
|
87 | 87 | |
|
88 | 88 | This allows us to later exec them by checking when something is an |
|
89 | 89 | instance of this class.""" |
|
90 | 90 | |
|
91 | 91 | def __init__(self,cmds): |
|
92 | 92 | """Build a macro from a list of commands.""" |
|
93 | 93 | |
|
94 | 94 | # Since the list may include multi-line entries, first make sure that |
|
95 | 95 | # they've been all broken up before passing it to magic2python |
|
96 | 96 | cmdlist = map(magic2python,''.join(cmds).split('\n')) |
|
97 | 97 | self.value = '\n'.join(cmdlist) |
|
98 | 98 | |
|
99 | 99 | def __str__(self): |
|
100 | 100 | return self.value |
|
101 | 101 | |
|
102 | 102 | #*************************************************************************** |
|
103 | 103 | # Main class implementing Magic functionality |
|
104 | 104 | class Magic: |
|
105 | 105 | """Magic functions for InteractiveShell. |
|
106 | 106 | |
|
107 | 107 | Shell functions which can be reached as %function_name. All magic |
|
108 | 108 | functions should accept a string, which they can parse for their own |
|
109 | 109 | needs. This can make some functions easier to type, eg `%cd ../` |
|
110 | 110 | vs. `%cd("../")` |
|
111 | 111 | |
|
112 | 112 | ALL definitions MUST begin with the prefix magic_. The user won't need it |
|
113 | 113 | at the command line, but it is is needed in the definition. """ |
|
114 | 114 | |
|
115 | 115 | # class globals |
|
116 | 116 | auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.', |
|
117 | 117 | 'Automagic is ON, % prefix NOT needed for magic functions.'] |
|
118 | 118 | |
|
119 | 119 | #...................................................................... |
|
120 | 120 | # some utility functions |
|
121 | 121 | |
|
122 | 122 | def __init__(self,shell): |
|
123 | 123 | # XXX This is hackish, clean up later to avoid these messy globals |
|
124 | 124 | global MAGIC_PREFIX, MAGIC_ESCAPE |
|
125 | 125 | |
|
126 | 126 | self.options_table = {} |
|
127 | 127 | MAGIC_PREFIX = shell.name+'.magic_' |
|
128 | 128 | MAGIC_ESCAPE = shell.ESC_MAGIC |
|
129 | 129 | if profile is None: |
|
130 | 130 | self.magic_prun = self.profile_missing_notice |
|
131 | 131 | |
|
132 | 132 | def profile_missing_notice(self, *args, **kwargs): |
|
133 | 133 | error("""\ |
|
134 | 134 | The profile module could not be found. If you are a Debian user, |
|
135 | 135 | it has been removed from the standard Debian package because of its non-free |
|
136 | 136 | license. To use profiling, please install"python2.3-profiler" from non-free.""") |
|
137 | 137 | |
|
138 | 138 | def default_option(self,fn,optstr): |
|
139 | 139 | """Make an entry in the options_table for fn, with value optstr""" |
|
140 | 140 | |
|
141 | 141 | if fn not in self.lsmagic(): |
|
142 | 142 | error("%s is not a magic function" % fn) |
|
143 | 143 | self.options_table[fn] = optstr |
|
144 | 144 | |
|
145 | 145 | def lsmagic(self): |
|
146 | 146 | """Return a list of currently available magic functions. |
|
147 | 147 | |
|
148 | 148 | Gives a list of the bare names after mangling (['ls','cd', ...], not |
|
149 | 149 | ['magic_ls','magic_cd',...]""" |
|
150 | 150 | |
|
151 | 151 | # FIXME. This needs a cleanup, in the way the magics list is built. |
|
152 | 152 | |
|
153 | 153 | # magics in class definition |
|
154 | 154 | class_magic = lambda fn: fn.startswith('magic_') and \ |
|
155 | 155 | callable(Magic.__dict__[fn]) |
|
156 | 156 | # in instance namespace (run-time user additions) |
|
157 | 157 | inst_magic = lambda fn: fn.startswith('magic_') and \ |
|
158 | 158 | callable(self.__dict__[fn]) |
|
159 | 159 | # and bound magics by user (so they can access self): |
|
160 | 160 | inst_bound_magic = lambda fn: fn.startswith('magic_') and \ |
|
161 | 161 | callable(self.__class__.__dict__[fn]) |
|
162 | 162 | magics = filter(class_magic,Magic.__dict__.keys()) + \ |
|
163 | 163 | filter(inst_magic,self.__dict__.keys()) + \ |
|
164 | 164 | filter(inst_bound_magic,self.__class__.__dict__.keys()) |
|
165 | 165 | out = [] |
|
166 | 166 | for fn in magics: |
|
167 | 167 | out.append(fn.replace('magic_','',1)) |
|
168 | 168 | out.sort() |
|
169 | 169 | return out |
|
170 | 170 | |
|
171 | 171 | def set_shell(self,shell): |
|
172 | 172 | self.shell = shell |
|
173 | 173 | self.alias_table = shell.alias_table |
|
174 | 174 | |
|
175 | 175 | def extract_input_slices(self,slices): |
|
176 | 176 | """Return as a string a set of input history slices. |
|
177 | 177 | |
|
178 | 178 | The set of slices is given as a list of strings (like ['1','4:8','9'], |
|
179 | 179 | since this function is for use by magic functions which get their |
|
180 | 180 | arguments as strings.""" |
|
181 | 181 | |
|
182 | 182 | cmds = [] |
|
183 | 183 | for chunk in slices: |
|
184 | 184 | if ':' in chunk: |
|
185 | 185 | ini,fin = map(int,chunk.split(':')) |
|
186 | 186 | else: |
|
187 | 187 | ini = int(chunk) |
|
188 | 188 | fin = ini+1 |
|
189 | 189 | cmds.append(self.shell.input_hist[ini:fin]) |
|
190 | 190 | return cmds |
|
191 | 191 | |
|
192 | 192 | def _ofind(self,oname): |
|
193 | 193 | """Find an object in the available namespaces. |
|
194 | 194 | |
|
195 | 195 | self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic |
|
196 | 196 | |
|
197 | 197 | Has special code to detect magic functions. |
|
198 | 198 | """ |
|
199 | 199 | |
|
200 | 200 | oname = oname.strip() |
|
201 | 201 | |
|
202 | 202 | # Namespaces to search in: |
|
203 | 203 | user_ns = self.shell.user_ns |
|
204 | 204 | internal_ns = self.shell.internal_ns |
|
205 | 205 | builtin_ns = __builtin__.__dict__ |
|
206 | 206 | alias_ns = self.shell.alias_table |
|
207 | 207 | |
|
208 | 208 | # Put them in a list. The order is important so that we find things in |
|
209 | 209 | # the same order that Python finds them. |
|
210 | 210 | namespaces = [ ('Interactive',user_ns), |
|
211 | 211 | ('IPython internal',internal_ns), |
|
212 | 212 | ('Python builtin',builtin_ns), |
|
213 | 213 | ('Alias',alias_ns), |
|
214 | 214 | ] |
|
215 | 215 | |
|
216 | 216 | # initialize results to 'null' |
|
217 | 217 | found = 0; obj = None; ospace = None; ds = None; |
|
218 | 218 | ismagic = 0; isalias = 0 |
|
219 | 219 | |
|
220 | 220 | # Look for the given name by splitting it in parts. If the head is |
|
221 | 221 | # found, then we look for all the remaining parts as members, and only |
|
222 | 222 | # declare success if we can find them all. |
|
223 | 223 | oname_parts = oname.split('.') |
|
224 | 224 | oname_head, oname_rest = oname_parts[0],oname_parts[1:] |
|
225 | 225 | for nsname,ns in namespaces: |
|
226 | 226 | try: |
|
227 | 227 | obj = ns[oname_head] |
|
228 | 228 | except KeyError: |
|
229 | 229 | continue |
|
230 | 230 | else: |
|
231 | 231 | for part in oname_rest: |
|
232 | 232 | try: |
|
233 | 233 | obj = getattr(obj,part) |
|
234 | 234 | except: |
|
235 | 235 | # Blanket except b/c some badly implemented objects |
|
236 | 236 | # allow __getattr__ to raise exceptions other than |
|
237 | 237 | # AttributeError, which then crashes IPython. |
|
238 | 238 | break |
|
239 | 239 | else: |
|
240 | 240 | # If we finish the for loop (no break), we got all members |
|
241 | 241 | found = 1 |
|
242 | 242 | ospace = nsname |
|
243 | 243 | if ns == alias_ns: |
|
244 | 244 | isalias = 1 |
|
245 | 245 | break # namespace loop |
|
246 | 246 | |
|
247 | 247 | # Try to see if it's magic |
|
248 | 248 | if not found: |
|
249 | 249 | if oname.startswith(self.shell.ESC_MAGIC): |
|
250 | 250 | oname = oname[1:] |
|
251 | 251 | obj = getattr(self,'magic_'+oname,None) |
|
252 | 252 | if obj is not None: |
|
253 | 253 | found = 1 |
|
254 | 254 | ospace = 'IPython internal' |
|
255 | 255 | ismagic = 1 |
|
256 | 256 | |
|
257 | 257 | # Last try: special-case some literals like '', [], {}, etc: |
|
258 | 258 | if not found and oname_head in ["''",'""','[]','{}','()']: |
|
259 | 259 | obj = eval(oname_head) |
|
260 | 260 | found = 1 |
|
261 | 261 | ospace = 'Interactive' |
|
262 | 262 | |
|
263 | 263 | return {'found':found, 'obj':obj, 'namespace':ospace, |
|
264 | 264 | 'ismagic':ismagic, 'isalias':isalias} |
|
265 | 265 | |
|
266 | 266 | def arg_err(self,func): |
|
267 | 267 | """Print docstring if incorrect arguments were passed""" |
|
268 | 268 | print 'Error in arguments:' |
|
269 | 269 | print OInspect.getdoc(func) |
|
270 | 270 | |
|
271 | 271 | |
|
272 | 272 | def format_latex(self,str): |
|
273 | 273 | """Format a string for latex inclusion.""" |
|
274 | 274 | |
|
275 | 275 | # Characters that need to be escaped for latex: |
|
276 | 276 | escape_re = re.compile(r'(%|_|\$)',re.MULTILINE) |
|
277 | 277 | # Magic command names as headers: |
|
278 | 278 | cmd_name_re = re.compile(r'^(%s.*?):' % self.shell.ESC_MAGIC, |
|
279 | 279 | re.MULTILINE) |
|
280 | 280 | # Magic commands |
|
281 | 281 | cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % self.shell.ESC_MAGIC, |
|
282 | 282 | re.MULTILINE) |
|
283 | 283 | # Paragraph continue |
|
284 | 284 | par_re = re.compile(r'\\$',re.MULTILINE) |
|
285 | 285 | |
|
286 | 286 | str = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',str) |
|
287 | 287 | str = cmd_re.sub(r'\\texttt{\g<cmd>}',str) |
|
288 | 288 | str = par_re.sub(r'\\\\',str) |
|
289 | 289 | str = escape_re.sub(r'\\\1',str) |
|
290 | 290 | return str |
|
291 | 291 | |
|
292 | 292 | def format_screen(self,str): |
|
293 | 293 | """Format a string for screen printing. |
|
294 | 294 | |
|
295 | 295 | This removes some latex-type format codes.""" |
|
296 | 296 | # Paragraph continue |
|
297 | 297 | par_re = re.compile(r'\\$',re.MULTILINE) |
|
298 | 298 | str = par_re.sub('',str) |
|
299 | 299 | return str |
|
300 | 300 | |
|
301 | 301 | def parse_options(self,arg_str,opt_str,*long_opts,**kw): |
|
302 | 302 | """Parse options passed to an argument string. |
|
303 | 303 | |
|
304 | 304 | The interface is similar to that of getopt(), but it returns back a |
|
305 | 305 | Struct with the options as keys and the stripped argument string still |
|
306 | 306 | as a string. |
|
307 | 307 | |
|
308 | 308 | arg_str is quoted as a true sys.argv vector by using shlex.split. |
|
309 | 309 | This allows us to easily expand variables, glob files, quote |
|
310 | 310 | arguments, etc. |
|
311 | 311 | |
|
312 | 312 | Options: |
|
313 | 313 | -mode: default 'string'. If given as 'list', the argument string is |
|
314 | 314 | returned as a list (split on whitespace) instead of a string. |
|
315 | 315 | |
|
316 | 316 | -list_all: put all option values in lists. Normally only options |
|
317 | 317 | appearing more than once are put in a list.""" |
|
318 | 318 | |
|
319 | 319 | # inject default options at the beginning of the input line |
|
320 | 320 | caller = sys._getframe(1).f_code.co_name.replace('magic_','') |
|
321 | 321 | arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str) |
|
322 | 322 | |
|
323 | 323 | mode = kw.get('mode','string') |
|
324 | 324 | if mode not in ['string','list']: |
|
325 | 325 | raise ValueError,'incorrect mode given: %s' % mode |
|
326 | 326 | # Get options |
|
327 | 327 | list_all = kw.get('list_all',0) |
|
328 | 328 | |
|
329 | 329 | # Check if we have more than one argument to warrant extra processing: |
|
330 | 330 | odict = {} # Dictionary with options |
|
331 | 331 | args = arg_str.split() |
|
332 | 332 | if len(args) >= 1: |
|
333 | 333 | # If the list of inputs only has 0 or 1 thing in it, there's no |
|
334 | 334 | # need to look for options |
|
335 | 335 | argv = shlex_split(arg_str) |
|
336 | 336 | # Do regular option processing |
|
337 | 337 | opts,args = getopt(argv,opt_str,*long_opts) |
|
338 | 338 | for o,a in opts: |
|
339 | 339 | if o.startswith('--'): |
|
340 | 340 | o = o[2:] |
|
341 | 341 | else: |
|
342 | 342 | o = o[1:] |
|
343 | 343 | try: |
|
344 | 344 | odict[o].append(a) |
|
345 | 345 | except AttributeError: |
|
346 | 346 | odict[o] = [odict[o],a] |
|
347 | 347 | except KeyError: |
|
348 | 348 | if list_all: |
|
349 | 349 | odict[o] = [a] |
|
350 | 350 | else: |
|
351 | 351 | odict[o] = a |
|
352 | 352 | |
|
353 | 353 | # Prepare opts,args for return |
|
354 | 354 | opts = Struct(odict) |
|
355 | 355 | if mode == 'string': |
|
356 | 356 | args = ' '.join(args) |
|
357 | 357 | |
|
358 | 358 | return opts,args |
|
359 | 359 | |
|
360 | 360 | #...................................................................... |
|
361 | 361 | # And now the actual magic functions |
|
362 | 362 | |
|
363 | 363 | # Functions for IPython shell work (vars,funcs, config, etc) |
|
364 | 364 | def magic_lsmagic(self, parameter_s = ''): |
|
365 | 365 | """List currently available magic functions.""" |
|
366 | 366 | mesc = self.shell.ESC_MAGIC |
|
367 | 367 | print 'Available magic functions:\n'+mesc+\ |
|
368 | 368 | (' '+mesc).join(self.lsmagic()) |
|
369 | 369 | print '\n' + Magic.auto_status[self.shell.rc.automagic] |
|
370 | 370 | return None |
|
371 | 371 | |
|
372 | 372 | def magic_magic(self, parameter_s = ''): |
|
373 | 373 | """Print information about the magic function system.""" |
|
374 | 374 | |
|
375 | 375 | mode = '' |
|
376 | 376 | try: |
|
377 | 377 | if parameter_s.split()[0] == '-latex': |
|
378 | 378 | mode = 'latex' |
|
379 | 379 | except: |
|
380 | 380 | pass |
|
381 | 381 | |
|
382 | 382 | magic_docs = [] |
|
383 | 383 | for fname in self.lsmagic(): |
|
384 | 384 | mname = 'magic_' + fname |
|
385 | 385 | for space in (Magic,self,self.__class__): |
|
386 | 386 | try: |
|
387 | 387 | fn = space.__dict__[mname] |
|
388 | 388 | except KeyError: |
|
389 | 389 | pass |
|
390 | 390 | else: |
|
391 | 391 | break |
|
392 | 392 | magic_docs.append('%s%s:\n\t%s\n' %(self.shell.ESC_MAGIC, |
|
393 | 393 | fname,fn.__doc__)) |
|
394 | 394 | magic_docs = ''.join(magic_docs) |
|
395 | 395 | |
|
396 | 396 | if mode == 'latex': |
|
397 | 397 | print self.format_latex(magic_docs) |
|
398 | 398 | return |
|
399 | 399 | else: |
|
400 | 400 | magic_docs = self.format_screen(magic_docs) |
|
401 | 401 | |
|
402 | 402 | outmsg = """ |
|
403 | 403 | IPython's 'magic' functions |
|
404 | 404 | =========================== |
|
405 | 405 | |
|
406 | 406 | The magic function system provides a series of functions which allow you to |
|
407 | 407 | control the behavior of IPython itself, plus a lot of system-type |
|
408 | 408 | features. All these functions are prefixed with a % character, but parameters |
|
409 | 409 | are given without parentheses or quotes. |
|
410 | 410 | |
|
411 | 411 | NOTE: If you have 'automagic' enabled (via the command line option or with the |
|
412 | 412 | %automagic function), you don't need to type in the % explicitly. By default, |
|
413 | 413 | IPython ships with automagic on, so you should only rarely need the % escape. |
|
414 | 414 | |
|
415 | 415 | Example: typing '%cd mydir' (without the quotes) changes you working directory |
|
416 | 416 | to 'mydir', if it exists. |
|
417 | 417 | |
|
418 | 418 | You can define your own magic functions to extend the system. See the supplied |
|
419 | 419 | ipythonrc and example-magic.py files for details (in your ipython |
|
420 | 420 | configuration directory, typically $HOME/.ipython/). |
|
421 | 421 | |
|
422 | 422 | You can also define your own aliased names for magic functions. In your |
|
423 | 423 | ipythonrc file, placing a line like: |
|
424 | 424 | |
|
425 | 425 | execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile |
|
426 | 426 | |
|
427 | 427 | will define %pf as a new name for %profile. |
|
428 | 428 | |
|
429 | 429 | You can also call magics in code using the ipmagic() function, which IPython |
|
430 | 430 | automatically adds to the builtin namespace. Type 'ipmagic?' for details. |
|
431 | 431 | |
|
432 | 432 | For a list of the available magic functions, use %lsmagic. For a description |
|
433 | 433 | of any of them, type %magic_name?, e.g. '%cd?'. |
|
434 | 434 | |
|
435 | 435 | Currently the magic system has the following functions:\n""" |
|
436 | 436 | |
|
437 | 437 | mesc = self.shell.ESC_MAGIC |
|
438 | 438 | outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):" |
|
439 | 439 | "\n\n%s%s\n\n%s" % (outmsg, |
|
440 | 440 | magic_docs,mesc,mesc, |
|
441 | 441 | (' '+mesc).join(self.lsmagic()), |
|
442 | 442 | Magic.auto_status[self.shell.rc.automagic] ) ) |
|
443 | 443 | |
|
444 | 444 | page(outmsg,screen_lines=self.shell.rc.screen_length) |
|
445 | 445 | |
|
446 | 446 | def magic_automagic(self, parameter_s = ''): |
|
447 | 447 | """Make magic functions callable without having to type the initial %. |
|
448 | 448 | |
|
449 | 449 | Toggles on/off (when off, you must call it as %automagic, of |
|
450 | 450 | course). Note that magic functions have lowest priority, so if there's |
|
451 | 451 | a variable whose name collides with that of a magic fn, automagic |
|
452 | 452 | won't work for that function (you get the variable instead). However, |
|
453 | 453 | if you delete the variable (del var), the previously shadowed magic |
|
454 | 454 | function becomes visible to automagic again.""" |
|
455 | 455 | |
|
456 | 456 | rc = self.shell.rc |
|
457 | 457 | rc.automagic = not rc.automagic |
|
458 | 458 | print '\n' + Magic.auto_status[rc.automagic] |
|
459 | 459 | |
|
460 | 460 | def magic_autocall(self, parameter_s = ''): |
|
461 | 461 | """Make functions callable without having to type parentheses. |
|
462 | 462 | |
|
463 | 463 | This toggles the autocall command line option on and off.""" |
|
464 | 464 | |
|
465 | 465 | rc = self.shell.rc |
|
466 | 466 | rc.autocall = not rc.autocall |
|
467 | 467 | print "Automatic calling is:",['OFF','ON'][rc.autocall] |
|
468 | 468 | |
|
469 | 469 | def magic_autoindent(self, parameter_s = ''): |
|
470 | 470 | """Toggle autoindent on/off (if available).""" |
|
471 | 471 | |
|
472 | 472 | self.shell.set_autoindent() |
|
473 | 473 | print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent] |
|
474 | 474 | |
|
475 | 475 | def magic_system_verbose(self, parameter_s = ''): |
|
476 | 476 | """Toggle verbose printing of system calls on/off.""" |
|
477 | 477 | |
|
478 | 478 | self.shell.rc_set_toggle('system_verbose') |
|
479 | 479 | print "System verbose printing is:",\ |
|
480 | 480 | ['OFF','ON'][self.shell.rc.system_verbose] |
|
481 | 481 | |
|
482 | 482 | def magic_history(self, parameter_s = ''): |
|
483 | 483 | """Print input history (_i<n> variables), with most recent last. |
|
484 | 484 | |
|
485 | 485 | %history [-n] -> print at most 40 inputs (some may be multi-line)\\ |
|
486 | 486 | %history [-n] n -> print at most n inputs\\ |
|
487 | 487 | %history [-n] n1 n2 -> print inputs between n1 and n2 (n2 not included)\\ |
|
488 | 488 | |
|
489 | 489 | Each input's number <n> is shown, and is accessible as the |
|
490 | 490 | automatically generated variable _i<n>. Multi-line statements are |
|
491 | 491 | printed starting at a new line for easy copy/paste. |
|
492 | 492 | |
|
493 | 493 | If option -n is used, input numbers are not printed. This is useful if |
|
494 | 494 | you want to get a printout of many lines which can be directly pasted |
|
495 | 495 | into a text editor. |
|
496 | 496 | |
|
497 | 497 | This feature is only available if numbered prompts are in use.""" |
|
498 | 498 | |
|
499 | 499 | if not self.do_full_cache: |
|
500 | 500 | print 'This feature is only available if numbered prompts are in use.' |
|
501 | 501 | return |
|
502 | 502 | opts,args = self.parse_options(parameter_s,'n',mode='list') |
|
503 | 503 | |
|
504 | 504 | default_length = 40 |
|
505 | 505 | if len(args) == 0: |
|
506 | 506 | final = self.outputcache.prompt_count |
|
507 | 507 | init = max(1,final-default_length) |
|
508 | 508 | elif len(args) == 1: |
|
509 | 509 | final = self.outputcache.prompt_count |
|
510 | 510 | init = max(1,final-int(args[0])) |
|
511 | 511 | elif len(args) == 2: |
|
512 | 512 | init,final = map(int,args) |
|
513 | 513 | else: |
|
514 | 514 | warn('%hist takes 0, 1 or 2 arguments separated by spaces.') |
|
515 | 515 | print self.magic_hist.__doc__ |
|
516 | 516 | return |
|
517 | 517 | width = len(str(final)) |
|
518 | 518 | line_sep = ['','\n'] |
|
519 | 519 | input_hist = self.shell.input_hist |
|
520 | 520 | print_nums = not opts.has_key('n') |
|
521 | 521 | for in_num in range(init,final): |
|
522 | 522 | inline = input_hist[in_num] |
|
523 | 523 | multiline = inline.count('\n') > 1 |
|
524 | 524 | if print_nums: |
|
525 | 525 | print str(in_num).ljust(width)+':'+ line_sep[multiline], |
|
526 | 526 | if inline.startswith('#'+self.shell.ESC_MAGIC) or \ |
|
527 | 527 | inline.startswith('#!'): |
|
528 | 528 | print inline[1:], |
|
529 | 529 | else: |
|
530 | 530 | print inline, |
|
531 | 531 | |
|
532 | 532 | def magic_hist(self, parameter_s=''): |
|
533 | 533 | """Alternate name for %history.""" |
|
534 | 534 | return self.magic_history(parameter_s) |
|
535 | 535 | |
|
536 | 536 | def magic_p(self, parameter_s=''): |
|
537 | 537 | """Just a short alias for Python's 'print'.""" |
|
538 | 538 | exec 'print ' + parameter_s in self.shell.user_ns |
|
539 | 539 | |
|
540 | 540 | def magic_r(self, parameter_s=''): |
|
541 | 541 | """Repeat previous input. |
|
542 | 542 | |
|
543 | 543 | If given an argument, repeats the previous command which starts with |
|
544 | 544 | the same string, otherwise it just repeats the previous input. |
|
545 | 545 | |
|
546 | 546 | Shell escaped commands (with ! as first character) are not recognized |
|
547 | 547 | by this system, only pure python code and magic commands. |
|
548 | 548 | """ |
|
549 | 549 | |
|
550 | 550 | start = parameter_s.strip() |
|
551 | 551 | esc_magic = self.shell.ESC_MAGIC |
|
552 | 552 | # Identify magic commands even if automagic is on (which means |
|
553 | 553 | # the in-memory version is different from that typed by the user). |
|
554 | 554 | if self.shell.rc.automagic: |
|
555 | 555 | start_magic = esc_magic+start |
|
556 | 556 | else: |
|
557 | 557 | start_magic = start |
|
558 | 558 | # Look through the input history in reverse |
|
559 | 559 | for n in range(len(self.shell.input_hist)-2,0,-1): |
|
560 | 560 | input = self.shell.input_hist[n] |
|
561 | 561 | # skip plain 'r' lines so we don't recurse to infinity |
|
562 | 562 | if input != 'ipmagic("r")\n' and \ |
|
563 | 563 | (input.startswith(start) or input.startswith(start_magic)): |
|
564 | 564 | #print 'match',`input` # dbg |
|
565 | 565 | if input.startswith(esc_magic): |
|
566 | 566 | input = magic2python(input) |
|
567 | 567 | #print 'modified',`input` # dbg |
|
568 | 568 | print 'Executing:',input, |
|
569 | 569 | exec input in self.shell.user_ns |
|
570 | 570 | return |
|
571 | 571 | print 'No previous input matching `%s` found.' % start |
|
572 | 572 | |
|
573 | 573 | def magic_page(self, parameter_s=''): |
|
574 | 574 | """Pretty print the object and display it through a pager. |
|
575 | 575 | |
|
576 | 576 | If no parameter is given, use _ (last output).""" |
|
577 | 577 | # After a function contributed by Olivier Aubert, slightly modified. |
|
578 | 578 | |
|
579 | 579 | oname = parameter_s and parameter_s or '_' |
|
580 | 580 | info = self._ofind(oname) |
|
581 | 581 | if info['found']: |
|
582 | 582 | page(pformat(info['obj'])) |
|
583 | 583 | else: |
|
584 | 584 | print 'Object `%s` not found' % oname |
|
585 | 585 | |
|
586 | 586 | def magic_profile(self, parameter_s=''): |
|
587 | 587 | """Print your currently active IPyhton profile.""" |
|
588 | 588 | if self.shell.rc.profile: |
|
589 | 589 | printpl('Current IPython profile: $self.shell.rc.profile.') |
|
590 | 590 | else: |
|
591 | 591 | print 'No profile active.' |
|
592 | 592 | |
|
593 | 593 | def _inspect(self,meth,oname,**kw): |
|
594 | 594 | """Generic interface to the inspector system. |
|
595 | 595 | |
|
596 | 596 | This function is meant to be called by pdef, pdoc & friends.""" |
|
597 | 597 | |
|
598 | 598 | oname = oname.strip() |
|
599 | 599 | info = Struct(self._ofind(oname)) |
|
600 | 600 | if info.found: |
|
601 | 601 | pmethod = getattr(self.shell.inspector,meth) |
|
602 | 602 | formatter = info.ismagic and self.format_screen or None |
|
603 | 603 | if meth == 'pdoc': |
|
604 | 604 | pmethod(info.obj,oname,formatter) |
|
605 | 605 | elif meth == 'pinfo': |
|
606 | 606 | pmethod(info.obj,oname,formatter,info,**kw) |
|
607 | 607 | else: |
|
608 | 608 | pmethod(info.obj,oname) |
|
609 | 609 | else: |
|
610 | 610 | print 'Object `%s` not found.' % oname |
|
611 | 611 | return 'not found' # so callers can take other action |
|
612 | 612 | |
|
613 | 613 | def magic_pdef(self, parameter_s=''): |
|
614 | 614 | """Print the definition header for any callable object. |
|
615 | 615 | |
|
616 | 616 | If the object is a class, print the constructor information.""" |
|
617 | 617 | self._inspect('pdef',parameter_s) |
|
618 | 618 | |
|
619 | 619 | def magic_pdoc(self, parameter_s=''): |
|
620 | 620 | """Print the docstring for an object. |
|
621 | 621 | |
|
622 | 622 | If the given object is a class, it will print both the class and the |
|
623 | 623 | constructor docstrings.""" |
|
624 | 624 | self._inspect('pdoc',parameter_s) |
|
625 | 625 | |
|
626 | 626 | def magic_psource(self, parameter_s=''): |
|
627 | 627 | """Print (or run through pager) the source code for an object.""" |
|
628 | 628 | self._inspect('psource',parameter_s) |
|
629 | 629 | |
|
630 | 630 | def magic_pfile(self, parameter_s=''): |
|
631 | 631 | """Print (or run through pager) the file where an object is defined. |
|
632 | 632 | |
|
633 | 633 | The file opens at the line where the object definition begins. IPython |
|
634 | 634 | will honor the environment variable PAGER if set, and otherwise will |
|
635 | 635 | do its best to print the file in a convenient form. |
|
636 | 636 | |
|
637 | 637 | If the given argument is not an object currently defined, IPython will |
|
638 | 638 | try to interpret it as a filename (automatically adding a .py extension |
|
639 | 639 | if needed). You can thus use %pfile as a syntax highlighting code |
|
640 | 640 | viewer.""" |
|
641 | 641 | |
|
642 | 642 | # first interpret argument as an object name |
|
643 | 643 | out = self._inspect('pfile',parameter_s) |
|
644 | 644 | # if not, try the input as a filename |
|
645 | 645 | if out == 'not found': |
|
646 | 646 | try: |
|
647 | 647 | filename = get_py_filename(parameter_s) |
|
648 | 648 | except IOError,msg: |
|
649 | 649 | print msg |
|
650 | 650 | return |
|
651 | 651 | page(self.shell.inspector.format(file(filename).read())) |
|
652 | 652 | |
|
653 | 653 | def magic_pinfo(self, parameter_s=''): |
|
654 | 654 | """Provide detailed information about an object. |
|
655 | 655 | |
|
656 | 656 | '%pinfo object' is just a synonym for object? or ?object.""" |
|
657 | 657 | |
|
658 | 658 | #print 'pinfo par: <%s>' % parameter_s # dbg |
|
659 | 659 | |
|
660 | 660 | # detail_level: 0 -> obj? , 1 -> obj?? |
|
661 | 661 | detail_level = 0 |
|
662 | 662 | # We need to detect if we got called as 'pinfo pinfo foo', which can |
|
663 | 663 | # happen if the user types 'pinfo foo?' at the cmd line. |
|
664 | 664 | pinfo,qmark1,oname,qmark2 = \ |
|
665 | 665 | re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups() |
|
666 | 666 | if pinfo or qmark1 or qmark2: |
|
667 | 667 | detail_level = 1 |
|
668 | 668 | if "*" in oname: |
|
669 | 669 | self.magic_psearch(oname) |
|
670 | 670 | else: |
|
671 | 671 | self._inspect('pinfo',oname,detail_level=detail_level) |
|
672 | 672 | |
|
673 | 673 | def magic_psearch(self, parameter_s=''): |
|
674 | 674 | """Search for object in namespaces by wildcard. |
|
675 | 675 | |
|
676 | 676 | %psearch [options] PATTERN [OBJECT TYPE] |
|
677 | 677 | |
|
678 | 678 | Note: ? can be used as a synonym for %psearch, at the beginning or at |
|
679 | 679 | the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the |
|
680 | 680 | rest of the command line must be unchanged (options come first), so |
|
681 | 681 | for example the following forms are equivalent |
|
682 | 682 | |
|
683 | 683 | %psearch -i a* function |
|
684 | 684 | -i a* function? |
|
685 | 685 | ?-i a* function |
|
686 | 686 | |
|
687 | 687 | Arguments: |
|
688 | 688 | |
|
689 | 689 | PATTERN |
|
690 | 690 | |
|
691 | 691 | where PATTERN is a string containing * as a wildcard similar to its |
|
692 | 692 | use in a shell. The pattern is matched in all namespaces on the |
|
693 | 693 | search path. By default objects starting with a single _ are not |
|
694 | 694 | matched, many IPython generated objects have a single |
|
695 | 695 | underscore. The default is case insensitive matching. Matching is |
|
696 | 696 | also done on the attributes of objects and not only on the objects |
|
697 | 697 | in a module. |
|
698 | 698 | |
|
699 | 699 | [OBJECT TYPE] |
|
700 | 700 | |
|
701 | 701 | Is the name of a python type from the types module. The name is |
|
702 | 702 | given in lowercase without the ending type, ex. StringType is |
|
703 | 703 | written string. By adding a type here only objects matching the |
|
704 | 704 | given type are matched. Using all here makes the pattern match all |
|
705 | 705 | types (this is the default). |
|
706 | 706 | |
|
707 | 707 | Options: |
|
708 | 708 | |
|
709 | 709 | -a: makes the pattern match even objects whose names start with a |
|
710 | 710 | single underscore. These names are normally ommitted from the |
|
711 | 711 | search. |
|
712 | 712 | |
|
713 | 713 | -i/-c: make the pattern case insensitive/sensitive. If neither of |
|
714 | 714 | these options is given, the default is read from your ipythonrc |
|
715 | 715 | file. The option name which sets this value is |
|
716 | 716 | 'wildcards_case_sensitive'. If this option is not specified in your |
|
717 | 717 | ipythonrc file, IPython's internal default is to do a case sensitive |
|
718 | 718 | search. |
|
719 | 719 | |
|
720 | 720 | -e/-s NAMESPACE: exclude/search a given namespace. The pattern you |
|
721 | 721 | specifiy can be searched in any of the following namespaces: |
|
722 | 722 | 'builtin', 'user', 'user_global','internal', 'alias', where |
|
723 | 723 | 'builtin' and 'user' are the search defaults. Note that you should |
|
724 | 724 | not use quotes when specifying namespaces. |
|
725 | 725 | |
|
726 | 726 | 'Builtin' contains the python module builtin, 'user' contains all |
|
727 | 727 | user data, 'alias' only contain the shell aliases and no python |
|
728 | 728 | objects, 'internal' contains objects used by IPython. The |
|
729 | 729 | 'user_global' namespace is only used by embedded IPython instances, |
|
730 | 730 | and it contains module-level globals. You can add namespaces to the |
|
731 | 731 | search with -s or exclude them with -e (these options can be given |
|
732 | 732 | more than once). |
|
733 | 733 | |
|
734 | 734 | Examples: |
|
735 | 735 | |
|
736 | 736 | %psearch a* -> objects beginning with an a |
|
737 | 737 | %psearch -e builtin a* -> objects NOT in the builtin space starting in a |
|
738 | 738 | %psearch a* function -> all functions beginning with an a |
|
739 | 739 | %psearch re.e* -> objects beginning with an e in module re |
|
740 | 740 | %psearch r*.e* -> objects that start with e in modules starting in r |
|
741 | 741 | %psearch r*.* string -> all strings in modules beginning with r |
|
742 | 742 | |
|
743 | 743 | Case sensitve search: |
|
744 | 744 | |
|
745 | 745 | %psearch -c a* list all object beginning with lower case a |
|
746 | 746 | |
|
747 | 747 | Show objects beginning with a single _: |
|
748 | 748 | |
|
749 | 749 | %psearch -a _* list objects beginning with a single underscore""" |
|
750 | 750 | |
|
751 | 751 | # default namespaces to be searched |
|
752 | 752 | def_search = ['user','builtin'] |
|
753 | 753 | |
|
754 | 754 | # Process options/args |
|
755 | 755 | opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True) |
|
756 | 756 | opt = opts.get |
|
757 | 757 | shell = self.shell |
|
758 | 758 | psearch = shell.inspector.psearch |
|
759 | 759 | |
|
760 | 760 | # select case options |
|
761 | 761 | if opts.has_key('i'): |
|
762 | 762 | ignore_case = True |
|
763 | 763 | elif opts.has_key('c'): |
|
764 | 764 | ignore_case = False |
|
765 | 765 | else: |
|
766 | 766 | ignore_case = not shell.rc.wildcards_case_sensitive |
|
767 | 767 | |
|
768 | 768 | # Build list of namespaces to search from user options |
|
769 | 769 | def_search.extend(opt('s',[])) |
|
770 | 770 | ns_exclude = ns_exclude=opt('e',[]) |
|
771 | 771 | ns_search = [nm for nm in def_search if nm not in ns_exclude] |
|
772 | 772 | |
|
773 | 773 | # Call the actual search |
|
774 | 774 | try: |
|
775 | 775 | psearch(args,shell.ns_table,ns_search, |
|
776 | 776 | show_all=opt('a'),ignore_case=ignore_case) |
|
777 | 777 | except: |
|
778 | 778 | shell.showtraceback() |
|
779 | 779 | |
|
780 | 780 | def magic_who_ls(self, parameter_s=''): |
|
781 | 781 | """Return a sorted list of all interactive variables. |
|
782 | 782 | |
|
783 | 783 | If arguments are given, only variables of types matching these |
|
784 | 784 | arguments are returned.""" |
|
785 | 785 | |
|
786 | 786 | user_ns = self.shell.user_ns |
|
787 | 787 | out = [] |
|
788 | 788 | typelist = parameter_s.split() |
|
789 | 789 | for i in self.shell.user_ns.keys(): |
|
790 | 790 | if not (i.startswith('_') or i.startswith('_i')) \ |
|
791 | 791 | and not (self.internal_ns.has_key(i) or |
|
792 | 792 | self.user_config_ns.has_key(i)): |
|
793 | 793 | if typelist: |
|
794 | 794 | if type(user_ns[i]).__name__ in typelist: |
|
795 | 795 | out.append(i) |
|
796 | 796 | else: |
|
797 | 797 | out.append(i) |
|
798 | 798 | out.sort() |
|
799 | 799 | return out |
|
800 | 800 | |
|
801 | 801 | def magic_who(self, parameter_s=''): |
|
802 | 802 | """Print all interactive variables, with some minimal formatting. |
|
803 | 803 | |
|
804 | 804 | If any arguments are given, only variables whose type matches one of |
|
805 | 805 | these are printed. For example: |
|
806 | 806 | |
|
807 | 807 | %who function str |
|
808 | 808 | |
|
809 | 809 | will only list functions and strings, excluding all other types of |
|
810 | 810 | variables. To find the proper type names, simply use type(var) at a |
|
811 | 811 | command line to see how python prints type names. For example: |
|
812 | 812 | |
|
813 | 813 | In [1]: type('hello')\\ |
|
814 | 814 | Out[1]: <type 'str'> |
|
815 | 815 | |
|
816 | 816 | indicates that the type name for strings is 'str'. |
|
817 | 817 | |
|
818 | 818 | %who always excludes executed names loaded through your configuration |
|
819 | 819 | file and things which are internal to IPython. |
|
820 | 820 | |
|
821 | 821 | This is deliberate, as typically you may load many modules and the |
|
822 | 822 | purpose of %who is to show you only what you've manually defined.""" |
|
823 | 823 | |
|
824 | 824 | varlist = self.magic_who_ls(parameter_s) |
|
825 | 825 | if not varlist: |
|
826 | 826 | print 'Interactive namespace is empty.' |
|
827 | 827 | return |
|
828 | 828 | |
|
829 | 829 | # if we have variables, move on... |
|
830 | 830 | |
|
831 | 831 | # stupid flushing problem: when prompts have no separators, stdout is |
|
832 | 832 | # getting lost. I'm starting to think this is a python bug. I'm having |
|
833 | 833 | # to force a flush with a print because even a sys.stdout.flush |
|
834 | 834 | # doesn't seem to do anything! |
|
835 | 835 | |
|
836 | 836 | count = 0 |
|
837 | 837 | for i in varlist: |
|
838 | 838 | print i+'\t', |
|
839 | 839 | count += 1 |
|
840 | 840 | if count > 8: |
|
841 | 841 | count = 0 |
|
842 | 842 | |
|
843 | 843 | sys.stdout.flush() # FIXME. Why the hell isn't this flushing??? |
|
844 | 844 | |
|
845 | 845 | print # well, this does force a flush at the expense of an extra \n |
|
846 | 846 | |
|
847 | 847 | def magic_whos(self, parameter_s=''): |
|
848 | 848 | """Like %who, but gives some extra information about each variable. |
|
849 | 849 | |
|
850 | 850 | The same type filtering of %who can be applied here. |
|
851 | 851 | |
|
852 | 852 | For all variables, the type is printed. Additionally it prints: |
|
853 | 853 | |
|
854 | 854 | - For {},[],(): their length. |
|
855 | 855 | |
|
856 | 856 | - For Numeric arrays, a summary with shape, number of elements, |
|
857 | 857 | typecode and size in memory. |
|
858 | 858 | |
|
859 | 859 | - Everything else: a string representation, snipping their middle if |
|
860 | 860 | too long.""" |
|
861 | 861 | |
|
862 | 862 | varnames = self.magic_who_ls(parameter_s) |
|
863 | 863 | if not varnames: |
|
864 | 864 | print 'Interactive namespace is empty.' |
|
865 | 865 | return |
|
866 | 866 | |
|
867 | 867 | # if we have variables, move on... |
|
868 | 868 | |
|
869 | 869 | # for these types, show len() instead of data: |
|
870 | 870 | seq_types = [types.DictType,types.ListType,types.TupleType] |
|
871 | 871 | |
|
872 | 872 | # for Numeric arrays, display summary info |
|
873 | 873 | try: |
|
874 | 874 | import Numeric |
|
875 | 875 | except ImportError: |
|
876 | 876 | array_type = None |
|
877 | 877 | else: |
|
878 | 878 | array_type = Numeric.ArrayType.__name__ |
|
879 | 879 | |
|
880 | 880 | # Find all variable names and types so we can figure out column sizes |
|
881 | 881 | get_vars = lambda i: self.shell.user_ns[i] |
|
882 | 882 | type_name = lambda v: type(v).__name__ |
|
883 | 883 | varlist = map(get_vars,varnames) |
|
884 | 884 | typelist = map(type_name,varlist) |
|
885 | 885 | # column labels and # of spaces as separator |
|
886 | 886 | varlabel = 'Variable' |
|
887 | 887 | typelabel = 'Type' |
|
888 | 888 | datalabel = 'Data/Info' |
|
889 | 889 | colsep = 3 |
|
890 | 890 | # variable format strings |
|
891 | 891 | vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)" |
|
892 | 892 | vfmt_short = '$vstr[:25]<...>$vstr[-25:]' |
|
893 | 893 | aformat = "%s: %s elems, type `%s`, %s bytes" |
|
894 | 894 | # find the size of the columns to format the output nicely |
|
895 | 895 | varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep |
|
896 | 896 | typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep |
|
897 | 897 | # table header |
|
898 | 898 | print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \ |
|
899 | 899 | ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1) |
|
900 | 900 | # and the table itself |
|
901 | 901 | kb = 1024 |
|
902 | 902 | Mb = 1048576 # kb**2 |
|
903 | 903 | for vname,var,vtype in zip(varnames,varlist,typelist): |
|
904 | 904 | print itpl(vformat), |
|
905 | 905 | if vtype in seq_types: |
|
906 | 906 | print len(var) |
|
907 | 907 | elif vtype==array_type: |
|
908 | 908 | vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1] |
|
909 | 909 | vsize = Numeric.size(var) |
|
910 | 910 | vbytes = vsize*var.itemsize() |
|
911 | 911 | if vbytes < 100000: |
|
912 | 912 | print aformat % (vshape,vsize,var.typecode(),vbytes) |
|
913 | 913 | else: |
|
914 | 914 | print aformat % (vshape,vsize,var.typecode(),vbytes), |
|
915 | 915 | if vbytes < Mb: |
|
916 | 916 | print '(%s kb)' % (vbytes/kb,) |
|
917 | 917 | else: |
|
918 | 918 | print '(%s Mb)' % (vbytes/Mb,) |
|
919 | 919 | else: |
|
920 | 920 | vstr = str(var) |
|
921 | 921 | if len(vstr) < 50: |
|
922 | 922 | print vstr |
|
923 | 923 | else: |
|
924 | 924 | printpl(vfmt_short) |
|
925 | 925 | |
|
926 | 926 | def magic_reset(self, parameter_s=''): |
|
927 | 927 | """Resets the namespace by removing all names defined by the user. |
|
928 | 928 | |
|
929 | 929 | Input/Output history are left around in case you need them.""" |
|
930 | 930 | |
|
931 | 931 | ans = raw_input( |
|
932 | 932 | "Once deleted, variables cannot be recovered. Proceed (y/n)? ") |
|
933 | 933 | if not ans.lower() == 'y': |
|
934 | 934 | print 'Nothing done.' |
|
935 | 935 | return |
|
936 | 936 | user_ns = self.shell.user_ns |
|
937 | 937 | for i in self.magic_who_ls(): |
|
938 | 938 | del(user_ns[i]) |
|
939 | 939 | |
|
940 | 940 | def magic_config(self,parameter_s=''): |
|
941 | 941 | """Show IPython's internal configuration.""" |
|
942 | 942 | |
|
943 | 943 | page('Current configuration structure:\n'+ |
|
944 | 944 | pformat(self.shell.rc.dict())) |
|
945 | 945 | |
|
946 | 946 | def magic_logstart(self,parameter_s=''): |
|
947 | 947 | """Start logging anywhere in a session. |
|
948 | 948 | |
|
949 | 949 | %logstart [log_name [log_mode]] |
|
950 | 950 | |
|
951 | 951 | If no name is given, it defaults to a file named 'ipython.log' in your |
|
952 | 952 | current directory, in 'rotate' mode (see below). |
|
953 | 953 | |
|
954 | 954 | '%logstart name' saves to file 'name' in 'backup' mode. It saves your |
|
955 | 955 | history up to that point and then continues logging. |
|
956 | 956 | |
|
957 | 957 | %logstart takes a second optional parameter: logging mode. This can be one |
|
958 | 958 | of (note that the modes are given unquoted):\\ |
|
959 | 959 | over: overwrite existing log.\\ |
|
960 | 960 | backup: rename (if exists) to name~ and start name.\\ |
|
961 | 961 | append: well, that says it.\\ |
|
962 | 962 | rotate: create rotating logs name.1~, name.2~, etc. |
|
963 | 963 | """ |
|
964 | 964 | |
|
965 | 965 | #FIXME. This function should all be moved to the Logger class. |
|
966 | 966 | |
|
967 | 967 | valid_modes = qw('over backup append rotate') |
|
968 | 968 | if self.LOG: |
|
969 | 969 | print 'Logging is already in place. Logfile:',self.LOG |
|
970 | 970 | return |
|
971 | 971 | |
|
972 | 972 | par = parameter_s.strip() |
|
973 | 973 | if not par: |
|
974 | 974 | logname = self.LOGDEF |
|
975 | 975 | logmode = 'rotate' # use rotate for the auto-generated logs |
|
976 | 976 | else: |
|
977 | 977 | try: |
|
978 | 978 | logname,logmode = par.split() |
|
979 | 979 | except: |
|
980 | 980 | try: |
|
981 | 981 | logname = par |
|
982 | 982 | logmode = 'backup' |
|
983 | 983 | except: |
|
984 | 984 | warn('Usage: %log [log_name [log_mode]]') |
|
985 | 985 | return |
|
986 | 986 | if not logmode in valid_modes: |
|
987 | 987 | warn('Logging NOT activated.\n' |
|
988 | 988 | 'Usage: %log [log_name [log_mode]]\n' |
|
989 | 989 | 'Valid modes: '+str(valid_modes)) |
|
990 | 990 | return |
|
991 | 991 | |
|
992 | 992 | # If we made it this far, I think we're ok: |
|
993 | 993 | print 'Activating auto-logging.' |
|
994 | 994 | print 'Current session state plus future input saved to:',logname |
|
995 | 995 | print 'Logging mode: ',logmode |
|
996 | 996 | # put logname into rc struct as if it had been called on the command line, |
|
997 | 997 | # so it ends up saved in the log header |
|
998 | 998 | # Save it in case we need to restore it... |
|
999 | 999 | old_logfile = self.shell.rc.opts.get('logfile','') |
|
1000 | 1000 | logname = os.path.expanduser(logname) |
|
1001 | 1001 | self.shell.rc.opts.logfile = logname |
|
1002 | 1002 | self.LOGMODE = logmode # FIXME: this should be set through a function. |
|
1003 | 1003 | try: |
|
1004 | 1004 | header = str(self.LOGHEAD) |
|
1005 | 1005 | self.create_log(header,logname) |
|
1006 | 1006 | self.logstart(header,logname) |
|
1007 | 1007 | except: |
|
1008 | 1008 | self.LOG = '' # we are NOT logging, something went wrong |
|
1009 | 1009 | self.shell.rc.opts.logfile = old_logfile |
|
1010 | 1010 | warn("Couldn't start log: "+str(sys.exc_info()[1])) |
|
1011 | 1011 | else: # log input history up to this point |
|
1012 | 1012 | self.logfile.write(self.shell.user_ns['_ih'][1:]) |
|
1013 | 1013 | self.logfile.flush() |
|
1014 | 1014 | |
|
1015 | 1015 | def magic_logoff(self,parameter_s=''): |
|
1016 | 1016 | """Temporarily stop logging. |
|
1017 | 1017 | |
|
1018 | 1018 | You must have previously started logging.""" |
|
1019 | 1019 | self.switch_log(0) |
|
1020 | 1020 | |
|
1021 | 1021 | def magic_logon(self,parameter_s=''): |
|
1022 | 1022 | """Restart logging. |
|
1023 | 1023 | |
|
1024 | 1024 | This function is for restarting logging which you've temporarily |
|
1025 | 1025 | stopped with %logoff. For starting logging for the first time, you |
|
1026 | 1026 | must use the %logstart function, which allows you to specify an |
|
1027 | 1027 | optional log filename.""" |
|
1028 | 1028 | |
|
1029 | 1029 | self.switch_log(1) |
|
1030 | 1030 | |
|
1031 | 1031 | def magic_logstate(self,parameter_s=''): |
|
1032 | 1032 | """Print the status of the logging system.""" |
|
1033 | 1033 | |
|
1034 | 1034 | self.logstate() |
|
1035 | 1035 | |
|
1036 | 1036 | def magic_pdb(self, parameter_s=''): |
|
1037 | 1037 | """Control the calling of the pdb interactive debugger. |
|
1038 | 1038 | |
|
1039 | 1039 | Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without |
|
1040 | 1040 | argument it works as a toggle. |
|
1041 | 1041 | |
|
1042 | 1042 | When an exception is triggered, IPython can optionally call the |
|
1043 | 1043 | interactive pdb debugger after the traceback printout. %pdb toggles |
|
1044 | 1044 | this feature on and off.""" |
|
1045 | 1045 | |
|
1046 | 1046 | par = parameter_s.strip().lower() |
|
1047 | 1047 | |
|
1048 | 1048 | if par: |
|
1049 | 1049 | try: |
|
1050 | 1050 | pdb = {'off':0,'0':0,'on':1,'1':1}[par] |
|
1051 | 1051 | except KeyError: |
|
1052 | 1052 | print 'Incorrect argument. Use on/1, off/0 or nothing for a toggle.' |
|
1053 | 1053 | return |
|
1054 | 1054 | else: |
|
1055 | 1055 | self.shell.InteractiveTB.call_pdb = pdb |
|
1056 | 1056 | else: |
|
1057 | 1057 | self.shell.InteractiveTB.call_pdb = 1 - self.shell.InteractiveTB.call_pdb |
|
1058 | 1058 | print 'Automatic pdb calling has been turned',\ |
|
1059 | 1059 | on_off(self.shell.InteractiveTB.call_pdb) |
|
1060 | 1060 | |
|
1061 | 1061 | |
|
1062 | 1062 | def magic_prun(self, parameter_s ='',user_mode=1, |
|
1063 | 1063 | opts=None,arg_lst=None,prog_ns=None): |
|
1064 | 1064 | |
|
1065 | 1065 | """Run a statement through the python code profiler. |
|
1066 | 1066 | |
|
1067 | 1067 | Usage:\\ |
|
1068 | 1068 | %prun [options] statement |
|
1069 | 1069 | |
|
1070 | 1070 | The given statement (which doesn't require quote marks) is run via the |
|
1071 | 1071 | python profiler in a manner similar to the profile.run() function. |
|
1072 | 1072 | Namespaces are internally managed to work correctly; profile.run |
|
1073 | 1073 | cannot be used in IPython because it makes certain assumptions about |
|
1074 | 1074 | namespaces which do not hold under IPython. |
|
1075 | 1075 | |
|
1076 | 1076 | Options: |
|
1077 | 1077 | |
|
1078 | 1078 | -l <limit>: you can place restrictions on what or how much of the |
|
1079 | 1079 | profile gets printed. The limit value can be: |
|
1080 | 1080 | |
|
1081 | 1081 | * A string: only information for function names containing this string |
|
1082 | 1082 | is printed. |
|
1083 | 1083 | |
|
1084 | 1084 | * An integer: only these many lines are printed. |
|
1085 | 1085 | |
|
1086 | 1086 | * A float (between 0 and 1): this fraction of the report is printed |
|
1087 | 1087 | (for example, use a limit of 0.4 to see the topmost 40% only). |
|
1088 | 1088 | |
|
1089 | 1089 | You can combine several limits with repeated use of the option. For |
|
1090 | 1090 | example, '-l __init__ -l 5' will print only the topmost 5 lines of |
|
1091 | 1091 | information about class constructors. |
|
1092 | 1092 | |
|
1093 | 1093 | -r: return the pstats.Stats object generated by the profiling. This |
|
1094 | 1094 | object has all the information about the profile in it, and you can |
|
1095 | 1095 | later use it for further analysis or in other functions. |
|
1096 | 1096 | |
|
1097 | 1097 | Since magic functions have a particular form of calling which prevents |
|
1098 | 1098 | you from writing something like:\\ |
|
1099 | 1099 | In [1]: p = %prun -r print 4 # invalid!\\ |
|
1100 | 1100 | you must instead use IPython's automatic variables to assign this:\\ |
|
1101 | 1101 | In [1]: %prun -r print 4 \\ |
|
1102 | 1102 | Out[1]: <pstats.Stats instance at 0x8222cec>\\ |
|
1103 | 1103 | In [2]: stats = _ |
|
1104 | 1104 | |
|
1105 | 1105 | If you really need to assign this value via an explicit function call, |
|
1106 | 1106 | you can always tap directly into the true name of the magic function |
|
1107 | 1107 | by using the ipmagic function (which IPython automatically adds to the |
|
1108 | 1108 | builtins):\\ |
|
1109 | 1109 | In [3]: stats = ipmagic('prun','-r print 4') |
|
1110 | 1110 | |
|
1111 | 1111 | You can type ipmagic? for more details on ipmagic. |
|
1112 | 1112 | |
|
1113 | 1113 | -s <key>: sort profile by given key. You can provide more than one key |
|
1114 | 1114 | by using the option several times: '-s key1 -s key2 -s key3...'. The |
|
1115 | 1115 | default sorting key is 'time'. |
|
1116 | 1116 | |
|
1117 | 1117 | The following is copied verbatim from the profile documentation |
|
1118 | 1118 | referenced below: |
|
1119 | 1119 | |
|
1120 | 1120 | When more than one key is provided, additional keys are used as |
|
1121 | 1121 | secondary criteria when the there is equality in all keys selected |
|
1122 | 1122 | before them. |
|
1123 | 1123 | |
|
1124 | 1124 | Abbreviations can be used for any key names, as long as the |
|
1125 | 1125 | abbreviation is unambiguous. The following are the keys currently |
|
1126 | 1126 | defined: |
|
1127 | 1127 | |
|
1128 | 1128 | Valid Arg Meaning\\ |
|
1129 | 1129 | "calls" call count\\ |
|
1130 | 1130 | "cumulative" cumulative time\\ |
|
1131 | 1131 | "file" file name\\ |
|
1132 | 1132 | "module" file name\\ |
|
1133 | 1133 | "pcalls" primitive call count\\ |
|
1134 | 1134 | "line" line number\\ |
|
1135 | 1135 | "name" function name\\ |
|
1136 | 1136 | "nfl" name/file/line\\ |
|
1137 | 1137 | "stdname" standard name\\ |
|
1138 | 1138 | "time" internal time |
|
1139 | 1139 | |
|
1140 | 1140 | Note that all sorts on statistics are in descending order (placing |
|
1141 | 1141 | most time consuming items first), where as name, file, and line number |
|
1142 | 1142 | searches are in ascending order (i.e., alphabetical). The subtle |
|
1143 | 1143 | distinction between "nfl" and "stdname" is that the standard name is a |
|
1144 | 1144 | sort of the name as printed, which means that the embedded line |
|
1145 | 1145 | numbers get compared in an odd way. For example, lines 3, 20, and 40 |
|
1146 | 1146 | would (if the file names were the same) appear in the string order |
|
1147 | 1147 | "20" "3" and "40". In contrast, "nfl" does a numeric compare of the |
|
1148 | 1148 | line numbers. In fact, sort_stats("nfl") is the same as |
|
1149 | 1149 | sort_stats("name", "file", "line"). |
|
1150 | 1150 | |
|
1151 | 1151 | -T <filename>: save profile results as shown on screen to a text |
|
1152 | 1152 | file. The profile is still shown on screen. |
|
1153 | 1153 | |
|
1154 | 1154 | -D <filename>: save (via dump_stats) profile statistics to given |
|
1155 | 1155 | filename. This data is in a format understod by the pstats module, and |
|
1156 | 1156 | is generated by a call to the dump_stats() method of profile |
|
1157 | 1157 | objects. The profile is still shown on screen. |
|
1158 | 1158 | |
|
1159 | 1159 | If you want to run complete programs under the profiler's control, use |
|
1160 | 1160 | '%run -p [prof_opts] filename.py [args to program]' where prof_opts |
|
1161 | 1161 | contains profiler specific options as described here. |
|
1162 | 1162 | |
|
1163 | 1163 | You can read the complete documentation for the profile module with:\\ |
|
1164 | 1164 | In [1]: import profile; profile.help() """ |
|
1165 | 1165 | |
|
1166 | 1166 | opts_def = Struct(D=[''],l=[],s=['time'],T=['']) |
|
1167 | 1167 | # protect user quote marks |
|
1168 | 1168 | parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'") |
|
1169 | 1169 | |
|
1170 | 1170 | if user_mode: # regular user call |
|
1171 | 1171 | opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:', |
|
1172 | 1172 | list_all=1) |
|
1173 | 1173 | namespace = self.shell.user_ns |
|
1174 | 1174 | else: # called to run a program by %run -p |
|
1175 | 1175 | try: |
|
1176 | 1176 | filename = get_py_filename(arg_lst[0]) |
|
1177 | 1177 | except IOError,msg: |
|
1178 | 1178 | error(msg) |
|
1179 | 1179 | return |
|
1180 | 1180 | |
|
1181 | 1181 | arg_str = 'execfile(filename,prog_ns)' |
|
1182 | 1182 | namespace = locals() |
|
1183 | 1183 | |
|
1184 | 1184 | opts.merge(opts_def) |
|
1185 | 1185 | |
|
1186 | 1186 | prof = profile.Profile() |
|
1187 | 1187 | try: |
|
1188 | 1188 | prof = prof.runctx(arg_str,namespace,namespace) |
|
1189 | 1189 | sys_exit = '' |
|
1190 | 1190 | except SystemExit: |
|
1191 | 1191 | sys_exit = """*** SystemExit exception caught in code being profiled.""" |
|
1192 | 1192 | |
|
1193 | 1193 | stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s) |
|
1194 | 1194 | |
|
1195 | 1195 | lims = opts.l |
|
1196 | 1196 | if lims: |
|
1197 | 1197 | lims = [] # rebuild lims with ints/floats/strings |
|
1198 | 1198 | for lim in opts.l: |
|
1199 | 1199 | try: |
|
1200 | 1200 | lims.append(int(lim)) |
|
1201 | 1201 | except ValueError: |
|
1202 | 1202 | try: |
|
1203 | 1203 | lims.append(float(lim)) |
|
1204 | 1204 | except ValueError: |
|
1205 | 1205 | lims.append(lim) |
|
1206 | 1206 | |
|
1207 | 1207 | # trap output |
|
1208 | 1208 | sys_stdout = sys.stdout |
|
1209 | 1209 | stdout_trap = StringIO() |
|
1210 | 1210 | try: |
|
1211 | 1211 | sys.stdout = stdout_trap |
|
1212 | 1212 | stats.print_stats(*lims) |
|
1213 | 1213 | finally: |
|
1214 | 1214 | sys.stdout = sys_stdout |
|
1215 | 1215 | output = stdout_trap.getvalue() |
|
1216 | 1216 | output = output.rstrip() |
|
1217 | 1217 | |
|
1218 | 1218 | page(output,screen_lines=self.shell.rc.screen_length) |
|
1219 | 1219 | print sys_exit, |
|
1220 | 1220 | |
|
1221 | 1221 | dump_file = opts.D[0] |
|
1222 | 1222 | text_file = opts.T[0] |
|
1223 | 1223 | if dump_file: |
|
1224 | 1224 | prof.dump_stats(dump_file) |
|
1225 | 1225 | print '\n*** Profile stats marshalled to file',\ |
|
1226 | 1226 | `dump_file`+'.',sys_exit |
|
1227 | 1227 | if text_file: |
|
1228 | 1228 | file(text_file,'w').write(output) |
|
1229 | 1229 | print '\n*** Profile printout saved to text file',\ |
|
1230 | 1230 | `text_file`+'.',sys_exit |
|
1231 | 1231 | |
|
1232 | 1232 | if opts.has_key('r'): |
|
1233 | 1233 | return stats |
|
1234 | 1234 | else: |
|
1235 | 1235 | return None |
|
1236 | 1236 | |
|
1237 | 1237 | def magic_run(self, parameter_s ='',runner=None): |
|
1238 | 1238 | """Run the named file inside IPython as a program. |
|
1239 | 1239 | |
|
1240 | 1240 | Usage:\\ |
|
1241 | 1241 | %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args] |
|
1242 | 1242 | |
|
1243 | 1243 | Parameters after the filename are passed as command-line arguments to |
|
1244 | 1244 | the program (put in sys.argv). Then, control returns to IPython's |
|
1245 | 1245 | prompt. |
|
1246 | 1246 | |
|
1247 | 1247 | This is similar to running at a system prompt:\\ |
|
1248 | 1248 | $ python file args\\ |
|
1249 | 1249 | but with the advantage of giving you IPython's tracebacks, and of |
|
1250 | 1250 | loading all variables into your interactive namespace for further use |
|
1251 | 1251 | (unless -p is used, see below). |
|
1252 | 1252 | |
|
1253 | 1253 | The file is executed in a namespace initially consisting only of |
|
1254 | 1254 | __name__=='__main__' and sys.argv constructed as indicated. It thus |
|
1255 | 1255 | sees its environment as if it were being run as a stand-alone |
|
1256 | 1256 | program. But after execution, the IPython interactive namespace gets |
|
1257 | 1257 | updated with all variables defined in the program (except for __name__ |
|
1258 | 1258 | and sys.argv). This allows for very convenient loading of code for |
|
1259 | 1259 | interactive work, while giving each program a 'clean sheet' to run in. |
|
1260 | 1260 | |
|
1261 | 1261 | Options: |
|
1262 | 1262 | |
|
1263 | 1263 | -n: __name__ is NOT set to '__main__', but to the running file's name |
|
1264 | 1264 | without extension (as python does under import). This allows running |
|
1265 | 1265 | scripts and reloading the definitions in them without calling code |
|
1266 | 1266 | protected by an ' if __name__ == "__main__" ' clause. |
|
1267 | 1267 | |
|
1268 | 1268 | -i: run the file in IPython's namespace instead of an empty one. This |
|
1269 | 1269 | is useful if you are experimenting with code written in a text editor |
|
1270 | 1270 | which depends on variables defined interactively. |
|
1271 | 1271 | |
|
1272 | 1272 | -e: ignore sys.exit() calls or SystemExit exceptions in the script |
|
1273 | 1273 | being run. This is particularly useful if IPython is being used to |
|
1274 | 1274 | run unittests, which always exit with a sys.exit() call. In such |
|
1275 | 1275 | cases you are interested in the output of the test results, not in |
|
1276 | 1276 | seeing a traceback of the unittest module. |
|
1277 | 1277 | |
|
1278 | 1278 | -t: print timing information at the end of the run. IPython will give |
|
1279 | 1279 | you an estimated CPU time consumption for your script, which under |
|
1280 | 1280 | Unix uses the resource module to avoid the wraparound problems of |
|
1281 | 1281 | time.clock(). Under Unix, an estimate of time spent on system tasks |
|
1282 | 1282 | is also given (for Windows platforms this is reported as 0.0). |
|
1283 | 1283 | |
|
1284 | 1284 | If -t is given, an additional -N<N> option can be given, where <N> |
|
1285 | 1285 | must be an integer indicating how many times you want the script to |
|
1286 | 1286 | run. The final timing report will include total and per run results. |
|
1287 | 1287 | |
|
1288 | 1288 | For example (testing the script uniq_stable.py): |
|
1289 | 1289 | |
|
1290 | 1290 | In [1]: run -t uniq_stable |
|
1291 | 1291 | |
|
1292 | 1292 | IPython CPU timings (estimated):\\ |
|
1293 | 1293 | User : 0.19597 s.\\ |
|
1294 | 1294 | System: 0.0 s.\\ |
|
1295 | 1295 | |
|
1296 | 1296 | In [2]: run -t -N5 uniq_stable |
|
1297 | 1297 | |
|
1298 | 1298 | IPython CPU timings (estimated):\\ |
|
1299 | 1299 | Total runs performed: 5\\ |
|
1300 | 1300 | Times : Total Per run\\ |
|
1301 | 1301 | User : 0.910862 s, 0.1821724 s.\\ |
|
1302 | 1302 | System: 0.0 s, 0.0 s. |
|
1303 | 1303 | |
|
1304 | 1304 | -d: run your program under the control of pdb, the Python debugger. |
|
1305 | 1305 | This allows you to execute your program step by step, watch variables, |
|
1306 | 1306 | etc. Internally, what IPython does is similar to calling: |
|
1307 | 1307 | |
|
1308 | 1308 | pdb.run('execfile("YOURFILENAME")') |
|
1309 | 1309 | |
|
1310 | 1310 | with a breakpoint set on line 1 of your file. You can change the line |
|
1311 | 1311 | number for this automatic breakpoint to be <N> by using the -bN option |
|
1312 | 1312 | (where N must be an integer). For example: |
|
1313 | 1313 | |
|
1314 | 1314 | %run -d -b40 myscript |
|
1315 | 1315 | |
|
1316 | 1316 | will set the first breakpoint at line 40 in myscript.py. Note that |
|
1317 | 1317 | the first breakpoint must be set on a line which actually does |
|
1318 | 1318 | something (not a comment or docstring) for it to stop execution. |
|
1319 | 1319 | |
|
1320 | 1320 | When the pdb debugger starts, you will see a (Pdb) prompt. You must |
|
1321 | 1321 | first enter 'c' (without qoutes) to start execution up to the first |
|
1322 | 1322 | breakpoint. |
|
1323 | 1323 | |
|
1324 | 1324 | Entering 'help' gives information about the use of the debugger. You |
|
1325 | 1325 | can easily see pdb's full documentation with "import pdb;pdb.help()" |
|
1326 | 1326 | at a prompt. |
|
1327 | 1327 | |
|
1328 | 1328 | -p: run program under the control of the Python profiler module (which |
|
1329 | 1329 | prints a detailed report of execution times, function calls, etc). |
|
1330 | 1330 | |
|
1331 | 1331 | You can pass other options after -p which affect the behavior of the |
|
1332 | 1332 | profiler itself. See the docs for %prun for details. |
|
1333 | 1333 | |
|
1334 | 1334 | In this mode, the program's variables do NOT propagate back to the |
|
1335 | 1335 | IPython interactive namespace (because they remain in the namespace |
|
1336 | 1336 | where the profiler executes them). |
|
1337 | 1337 | |
|
1338 | 1338 | Internally this triggers a call to %prun, see its documentation for |
|
1339 | 1339 | details on the options available specifically for profiling.""" |
|
1340 | 1340 | |
|
1341 | 1341 | # get arguments and set sys.argv for program to be run. |
|
1342 | 1342 | opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e', |
|
1343 | 1343 | mode='list',list_all=1) |
|
1344 | 1344 | |
|
1345 | 1345 | try: |
|
1346 | 1346 | filename = get_py_filename(arg_lst[0]) |
|
1347 | 1347 | except IndexError: |
|
1348 | 1348 | warn('you must provide at least a filename.') |
|
1349 | 1349 | print '\n%run:\n',OInspect.getdoc(self.magic_run) |
|
1350 | 1350 | return |
|
1351 | 1351 | except IOError,msg: |
|
1352 | 1352 | error(msg) |
|
1353 | 1353 | return |
|
1354 | 1354 | |
|
1355 | 1355 | # Control the response to exit() calls made by the script being run |
|
1356 | 1356 | exit_ignore = opts.has_key('e') |
|
1357 | 1357 | |
|
1358 | 1358 | # Make sure that the running script gets a proper sys.argv as if it |
|
1359 | 1359 | # were run from a system shell. |
|
1360 | 1360 | save_argv = sys.argv # save it for later restoring |
|
1361 | 1361 | sys.argv = [filename]+ arg_lst[1:] # put in the proper filename |
|
1362 | 1362 | |
|
1363 | 1363 | if opts.has_key('i'): |
|
1364 | 1364 | prog_ns = self.shell.user_ns |
|
1365 | 1365 | __name__save = self.shell.user_ns['__name__'] |
|
1366 | 1366 | prog_ns['__name__'] = '__main__' |
|
1367 | 1367 | else: |
|
1368 | 1368 | if opts.has_key('n'): |
|
1369 | 1369 | name = os.path.splitext(os.path.basename(filename))[0] |
|
1370 | 1370 | else: |
|
1371 | 1371 | name = '__main__' |
|
1372 | 1372 | prog_ns = {'__name__':name} |
|
1373 | 1373 | |
|
1374 | 1374 | # pickle fix. See iplib for an explanation |
|
1375 | 1375 | sys.modules[prog_ns['__name__']] = FakeModule(prog_ns) |
|
1376 | 1376 | |
|
1377 | 1377 | stats = None |
|
1378 | 1378 | try: |
|
1379 | 1379 | if opts.has_key('p'): |
|
1380 | 1380 | stats = self.magic_prun('',0,opts,arg_lst,prog_ns) |
|
1381 | 1381 | else: |
|
1382 | 1382 | if opts.has_key('d'): |
|
1383 | 1383 | deb = Debugger.Pdb(self.shell.rc.colors) |
|
1384 | 1384 | # reset Breakpoint state, which is moronically kept |
|
1385 | 1385 | # in a class |
|
1386 | 1386 | bdb.Breakpoint.next = 1 |
|
1387 | 1387 | bdb.Breakpoint.bplist = {} |
|
1388 | 1388 | bdb.Breakpoint.bpbynumber = [None] |
|
1389 | 1389 | # Set an initial breakpoint to stop execution |
|
1390 | 1390 | maxtries = 10 |
|
1391 | 1391 | bp = int(opts.get('b',[1])[0]) |
|
1392 | 1392 | checkline = deb.checkline(filename,bp) |
|
1393 | 1393 | if not checkline: |
|
1394 | 1394 | for bp in range(bp+1,bp+maxtries+1): |
|
1395 | 1395 | if deb.checkline(filename,bp): |
|
1396 | 1396 | break |
|
1397 | 1397 | else: |
|
1398 | 1398 | msg = ("\nI failed to find a valid line to set " |
|
1399 | 1399 | "a breakpoint\n" |
|
1400 | 1400 | "after trying up to line: %s.\n" |
|
1401 | 1401 | "Please set a valid breakpoint manually " |
|
1402 | 1402 | "with the -b option." % bp) |
|
1403 | 1403 | error(msg) |
|
1404 | 1404 | return |
|
1405 | 1405 | # if we find a good linenumber, set the breakpoint |
|
1406 | 1406 | deb.do_break('%s:%s' % (filename,bp)) |
|
1407 | 1407 | # Start file run |
|
1408 | 1408 | print "NOTE: Enter 'c' at the", |
|
1409 | 1409 | print "ipdb> prompt to start your script." |
|
1410 | 1410 | try: |
|
1411 | 1411 | deb.run('execfile("%s")' % filename,prog_ns) |
|
1412 | 1412 | except: |
|
1413 | 1413 | etype, value, tb = sys.exc_info() |
|
1414 | 1414 | # Skip three frames in the traceback: the %run one, |
|
1415 | 1415 | # one inside bdb.py, and the command-line typed by the |
|
1416 | 1416 | # user (run by exec in pdb itself). |
|
1417 | 1417 | self.shell.InteractiveTB(etype,value,tb,tb_offset=3) |
|
1418 | 1418 | else: |
|
1419 | 1419 | if runner is None: |
|
1420 | 1420 | runner = self.shell.safe_execfile |
|
1421 | 1421 | if opts.has_key('t'): |
|
1422 | 1422 | try: |
|
1423 | 1423 | nruns = int(opts['N'][0]) |
|
1424 | 1424 | if nruns < 1: |
|
1425 | 1425 | error('Number of runs must be >=1') |
|
1426 | 1426 | return |
|
1427 | 1427 | except (KeyError): |
|
1428 | 1428 | nruns = 1 |
|
1429 | 1429 | if nruns == 1: |
|
1430 | 1430 | t0 = clock2() |
|
1431 | 1431 | runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore) |
|
1432 | 1432 | t1 = clock2() |
|
1433 | 1433 | t_usr = t1[0]-t0[0] |
|
1434 | 1434 | t_sys = t1[1]-t1[1] |
|
1435 | 1435 | print "\nIPython CPU timings (estimated):" |
|
1436 | 1436 | print " User : %10s s." % t_usr |
|
1437 | 1437 | print " System: %10s s." % t_sys |
|
1438 | 1438 | else: |
|
1439 | 1439 | runs = range(nruns) |
|
1440 | 1440 | t0 = clock2() |
|
1441 | 1441 | for nr in runs: |
|
1442 | 1442 | runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore) |
|
1443 | 1443 | t1 = clock2() |
|
1444 | 1444 | t_usr = t1[0]-t0[0] |
|
1445 | 1445 | t_sys = t1[1]-t1[1] |
|
1446 | 1446 | print "\nIPython CPU timings (estimated):" |
|
1447 | 1447 | print "Total runs performed:",nruns |
|
1448 | 1448 | print " Times : %10s %10s" % ('Total','Per run') |
|
1449 | 1449 | print " User : %10s s, %10s s." % (t_usr,t_usr/nruns) |
|
1450 | 1450 | print " System: %10s s, %10s s." % (t_sys,t_sys/nruns) |
|
1451 | 1451 | |
|
1452 | 1452 | else: |
|
1453 | 1453 | runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore) |
|
1454 | 1454 | if opts.has_key('i'): |
|
1455 | 1455 | self.shell.user_ns['__name__'] = __name__save |
|
1456 | 1456 | else: |
|
1457 | 1457 | # update IPython interactive namespace |
|
1458 | 1458 | del prog_ns['__name__'] |
|
1459 | 1459 | self.shell.user_ns.update(prog_ns) |
|
1460 | 1460 | finally: |
|
1461 | 1461 | sys.argv = save_argv |
|
1462 | 1462 | return stats |
|
1463 | 1463 | |
|
1464 | 1464 | def magic_runlog(self, parameter_s =''): |
|
1465 | 1465 | """Run files as logs. |
|
1466 | 1466 | |
|
1467 | 1467 | Usage:\\ |
|
1468 | 1468 | %runlog file1 file2 ... |
|
1469 | 1469 | |
|
1470 | 1470 | Run the named files (treating them as log files) in sequence inside |
|
1471 | 1471 | the interpreter, and return to the prompt. This is much slower than |
|
1472 | 1472 | %run because each line is executed in a try/except block, but it |
|
1473 | 1473 | allows running files with syntax errors in them. |
|
1474 | 1474 | |
|
1475 | 1475 | Normally IPython will guess when a file is one of its own logfiles, so |
|
1476 | 1476 | you can typically use %run even for logs. This shorthand allows you to |
|
1477 | 1477 | force any file to be treated as a log file.""" |
|
1478 | 1478 | |
|
1479 | 1479 | for f in parameter_s.split(): |
|
1480 | 1480 | self.shell.safe_execfile(f,self.shell.user_ns, |
|
1481 | 1481 | self.shell.user_ns,islog=1) |
|
1482 | 1482 | |
|
1483 | 1483 | def magic_time(self,parameter_s = ''): |
|
1484 | 1484 | """Time execution of a Python statement or expression. |
|
1485 | 1485 | |
|
1486 | 1486 | The CPU and wall clock times are printed, and the value of the |
|
1487 | 1487 | expression (if any) is returned. Note that under Win32, system time |
|
1488 | 1488 | is always reported as 0, since it can not be measured. |
|
1489 | 1489 | |
|
1490 | 1490 | This function provides very basic timing functionality. In Python |
|
1491 | 1491 | 2.3, the timeit module offers more control and sophistication, but for |
|
1492 | 1492 | now IPython supports Python 2.2, so we can not rely on timeit being |
|
1493 | 1493 | present. |
|
1494 | 1494 | |
|
1495 | 1495 | Some examples: |
|
1496 | 1496 | |
|
1497 | 1497 | In [1]: time 2**128 |
|
1498 | 1498 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1499 | 1499 | Wall time: 0.00 |
|
1500 | 1500 | Out[1]: 340282366920938463463374607431768211456L |
|
1501 | 1501 | |
|
1502 | 1502 | In [2]: n = 1000000 |
|
1503 | 1503 | |
|
1504 | 1504 | In [3]: time sum(range(n)) |
|
1505 | 1505 | CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s |
|
1506 | 1506 | Wall time: 1.37 |
|
1507 | 1507 | Out[3]: 499999500000L |
|
1508 | 1508 | |
|
1509 | 1509 | In [4]: time print 'hello world' |
|
1510 | 1510 | hello world |
|
1511 | 1511 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1512 | 1512 | Wall time: 0.00 |
|
1513 | 1513 | """ |
|
1514 | 1514 | |
|
1515 | 1515 | # fail immediately if the given expression can't be compiled |
|
1516 | 1516 | try: |
|
1517 | 1517 | mode = 'eval' |
|
1518 | 1518 | code = compile(parameter_s,'<timed eval>',mode) |
|
1519 | 1519 | except SyntaxError: |
|
1520 | 1520 | mode = 'exec' |
|
1521 | 1521 | code = compile(parameter_s,'<timed exec>',mode) |
|
1522 | 1522 | # skew measurement as little as possible |
|
1523 | 1523 | glob = self.shell.user_ns |
|
1524 | 1524 | clk = clock2 |
|
1525 | 1525 | wtime = time.time |
|
1526 | 1526 | # time execution |
|
1527 | 1527 | wall_st = wtime() |
|
1528 | 1528 | if mode=='eval': |
|
1529 | 1529 | st = clk() |
|
1530 | 1530 | out = eval(code,glob) |
|
1531 | 1531 | end = clk() |
|
1532 | 1532 | else: |
|
1533 | 1533 | st = clk() |
|
1534 | 1534 | exec code in glob |
|
1535 | 1535 | end = clk() |
|
1536 | 1536 | out = None |
|
1537 | 1537 | wall_end = wtime() |
|
1538 | 1538 | # Compute actual times and report |
|
1539 | 1539 | wall_time = wall_end-wall_st |
|
1540 | 1540 | cpu_user = end[0]-st[0] |
|
1541 | 1541 | cpu_sys = end[1]-st[1] |
|
1542 | 1542 | cpu_tot = cpu_user+cpu_sys |
|
1543 | 1543 | print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \ |
|
1544 | 1544 | (cpu_user,cpu_sys,cpu_tot) |
|
1545 | 1545 | print "Wall time: %.2f" % wall_time |
|
1546 | 1546 | return out |
|
1547 | 1547 | |
|
1548 | 1548 | def magic_macro(self,parameter_s = ''): |
|
1549 | 1549 | """Define a set of input lines as a macro for future re-execution. |
|
1550 | 1550 | |
|
1551 | 1551 | Usage:\\ |
|
1552 | 1552 | %macro name n1:n2 n3:n4 ... n5 .. n6 ... |
|
1553 | 1553 | |
|
1554 | 1554 | This will define a global variable called `name` which is a string |
|
1555 | 1555 | made of joining the slices and lines you specify (n1,n2,... numbers |
|
1556 | 1556 | above) from your input history into a single string. This variable |
|
1557 | 1557 | acts like an automatic function which re-executes those lines as if |
|
1558 | 1558 | you had typed them. You just type 'name' at the prompt and the code |
|
1559 | 1559 | executes. |
|
1560 | 1560 | |
|
1561 | 1561 | Note that the slices use the standard Python slicing notation (5:8 |
|
1562 | 1562 | means include lines numbered 5,6,7). |
|
1563 | 1563 | |
|
1564 | 1564 | For example, if your history contains (%hist prints it): |
|
1565 | 1565 | |
|
1566 | 1566 | 44: x=1\\ |
|
1567 | 1567 | 45: y=3\\ |
|
1568 | 1568 | 46: z=x+y\\ |
|
1569 | 1569 | 47: print x\\ |
|
1570 | 1570 | 48: a=5\\ |
|
1571 | 1571 | 49: print 'x',x,'y',y\\ |
|
1572 | 1572 | |
|
1573 | 1573 | you can create a macro with lines 44 through 47 (included) and line 49 |
|
1574 | 1574 | called my_macro with: |
|
1575 | 1575 | |
|
1576 | 1576 | In [51]: %macro my_macro 44:48 49 |
|
1577 | 1577 | |
|
1578 | 1578 | Now, typing `my_macro` (without quotes) will re-execute all this code |
|
1579 | 1579 | in one pass. |
|
1580 | 1580 | |
|
1581 | 1581 | You don't need to give the line-numbers in order, and any given line |
|
1582 | 1582 | number can appear multiple times. You can assemble macros with any |
|
1583 | 1583 | lines from your input history in any order. |
|
1584 | 1584 | |
|
1585 | 1585 | The macro is a simple object which holds its value in an attribute, |
|
1586 | 1586 | but IPython's display system checks for macros and executes them as |
|
1587 | 1587 | code instead of printing them when you type their name. |
|
1588 | 1588 | |
|
1589 | 1589 | You can view a macro's contents by explicitly printing it with: |
|
1590 | 1590 | |
|
1591 | 1591 | 'print macro_name'. |
|
1592 | 1592 | |
|
1593 | 1593 | For one-off cases which DON'T contain magic function calls in them you |
|
1594 | 1594 | can obtain similar results by explicitly executing slices from your |
|
1595 | 1595 | input history with: |
|
1596 | 1596 | |
|
1597 | 1597 | In [60]: exec In[44:48]+In[49]""" |
|
1598 | 1598 | |
|
1599 | 1599 | args = parameter_s.split() |
|
1600 | 1600 | name,ranges = args[0], args[1:] |
|
1601 | 1601 | #print 'rng',ranges # dbg |
|
1602 | 1602 | cmds = self.extract_input_slices(ranges) |
|
1603 | 1603 | macro = Macro(cmds) |
|
1604 | 1604 | self.shell.user_ns.update({name:macro}) |
|
1605 | 1605 | print 'Macro `%s` created. To execute, type its name (without quotes).' % name |
|
1606 | 1606 | print 'Macro contents:' |
|
1607 | 1607 | print str(macro).rstrip(), |
|
1608 | 1608 | |
|
1609 | 1609 | def magic_save(self,parameter_s = ''): |
|
1610 | 1610 | """Save a set of lines to a given filename. |
|
1611 | 1611 | |
|
1612 | 1612 | Usage:\\ |
|
1613 | 1613 | %save filename n1:n2 n3:n4 ... n5 .. n6 ... |
|
1614 | 1614 | |
|
1615 | 1615 | This function uses the same syntax as %macro for line extraction, but |
|
1616 | 1616 | instead of creating a macro it saves the resulting string to the |
|
1617 | 1617 | filename you specify. |
|
1618 | 1618 | |
|
1619 | 1619 | It adds a '.py' extension to the file if you don't do so yourself, and |
|
1620 | 1620 | it asks for confirmation before overwriting existing files.""" |
|
1621 | 1621 | |
|
1622 | 1622 | args = parameter_s.split() |
|
1623 | 1623 | fname,ranges = args[0], args[1:] |
|
1624 | 1624 | if not fname.endswith('.py'): |
|
1625 | 1625 | fname += '.py' |
|
1626 | 1626 | if os.path.isfile(fname): |
|
1627 | 1627 | ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname) |
|
1628 | 1628 | if ans.lower() not in ['y','yes']: |
|
1629 | 1629 | print 'Operation cancelled.' |
|
1630 | 1630 | return |
|
1631 | 1631 | cmds = ''.join(self.extract_input_slices(ranges)) |
|
1632 | 1632 | f = file(fname,'w') |
|
1633 | 1633 | f.write(cmds) |
|
1634 | 1634 | f.close() |
|
1635 | 1635 | print 'The following commands were written to file `%s`:' % fname |
|
1636 | 1636 | print cmds |
|
1637 | 1637 | |
|
1638 | 1638 | def magic_ed(self,parameter_s = ''): |
|
1639 | 1639 | """Alias to %edit.""" |
|
1640 | 1640 | return self.magic_edit(parameter_s) |
|
1641 | 1641 | |
|
1642 | 1642 | def magic_edit(self,parameter_s = '',last_call=['','']): |
|
1643 | 1643 | """Bring up an editor and execute the resulting code. |
|
1644 | 1644 | |
|
1645 | 1645 | Usage: |
|
1646 | 1646 | %edit [options] [args] |
|
1647 | 1647 | |
|
1648 | 1648 | %edit runs IPython's editor hook. The default version of this hook is |
|
1649 | 1649 | set to call the __IPYTHON__.rc.editor command. This is read from your |
|
1650 | 1650 | environment variable $EDITOR. If this isn't found, it will default to |
|
1651 | 1651 | vi under Linux/Unix and to notepad under Windows. See the end of this |
|
1652 | 1652 | docstring for how to change the editor hook. |
|
1653 | 1653 | |
|
1654 | 1654 | You can also set the value of this editor via the command line option |
|
1655 | 1655 | '-editor' or in your ipythonrc file. This is useful if you wish to use |
|
1656 | 1656 | specifically for IPython an editor different from your typical default |
|
1657 | 1657 | (and for Windows users who typically don't set environment variables). |
|
1658 | 1658 | |
|
1659 | 1659 | This command allows you to conveniently edit multi-line code right in |
|
1660 | 1660 | your IPython session. |
|
1661 | 1661 | |
|
1662 | 1662 | If called without arguments, %edit opens up an empty editor with a |
|
1663 | 1663 | temporary file and will execute the contents of this file when you |
|
1664 | 1664 | close it (don't forget to save it!). |
|
1665 | 1665 | |
|
1666 | 1666 | Options: |
|
1667 | 1667 | |
|
1668 | 1668 | -p: this will call the editor with the same data as the previous time |
|
1669 | 1669 | it was used, regardless of how long ago (in your current session) it |
|
1670 | 1670 | was. |
|
1671 | 1671 | |
|
1672 | 1672 | -x: do not execute the edited code immediately upon exit. This is |
|
1673 | 1673 | mainly useful if you are editing programs which need to be called with |
|
1674 | 1674 | command line arguments, which you can then do using %run. |
|
1675 | 1675 | |
|
1676 | 1676 | Arguments: |
|
1677 | 1677 | |
|
1678 | 1678 | If arguments are given, the following possibilites exist: |
|
1679 | 1679 | |
|
1680 | 1680 | - The arguments are numbers or pairs of colon-separated numbers (like |
|
1681 | 1681 | 1 4:8 9). These are interpreted as lines of previous input to be |
|
1682 | 1682 | loaded into the editor. The syntax is the same of the %macro command. |
|
1683 | 1683 | |
|
1684 | 1684 | - If the argument doesn't start with a number, it is evaluated as a |
|
1685 | 1685 | variable and its contents loaded into the editor. You can thus edit |
|
1686 | 1686 | any string which contains python code (including the result of |
|
1687 | 1687 | previous edits). |
|
1688 | 1688 | |
|
1689 | 1689 | - If the argument is the name of an object (other than a string), |
|
1690 | 1690 | IPython will try to locate the file where it was defined and open the |
|
1691 | 1691 | editor at the point where it is defined. You can use `%edit function` |
|
1692 | 1692 | to load an editor exactly at the point where 'function' is defined, |
|
1693 | 1693 | edit it and have the file be executed automatically. |
|
1694 | 1694 | |
|
1695 | 1695 | Note: opening at an exact line is only supported under Unix, and some |
|
1696 | 1696 | editors (like kedit and gedit up to Gnome 2.8) do not understand the |
|
1697 | 1697 | '+NUMBER' parameter necessary for this feature. Good editors like |
|
1698 | 1698 | (X)Emacs, vi, jed, pico and joe all do. |
|
1699 | 1699 | |
|
1700 | 1700 | - If the argument is not found as a variable, IPython will look for a |
|
1701 | 1701 | file with that name (adding .py if necessary) and load it into the |
|
1702 | 1702 | editor. It will execute its contents with execfile() when you exit, |
|
1703 | 1703 | loading any code in the file into your interactive namespace. |
|
1704 | 1704 | |
|
1705 | 1705 | After executing your code, %edit will return as output the code you |
|
1706 | 1706 | typed in the editor (except when it was an existing file). This way |
|
1707 | 1707 | you can reload the code in further invocations of %edit as a variable, |
|
1708 | 1708 | via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of |
|
1709 | 1709 | the output. |
|
1710 | 1710 | |
|
1711 | 1711 | Note that %edit is also available through the alias %ed. |
|
1712 | 1712 | |
|
1713 | 1713 | This is an example of creating a simple function inside the editor and |
|
1714 | 1714 | then modifying it. First, start up the editor: |
|
1715 | 1715 | |
|
1716 | 1716 | In [1]: ed\\ |
|
1717 | 1717 | Editing... done. Executing edited code...\\ |
|
1718 | 1718 | Out[1]: 'def foo():\\n print "foo() was defined in an editing session"\\n' |
|
1719 | 1719 | |
|
1720 | 1720 | We can then call the function foo(): |
|
1721 | 1721 | |
|
1722 | 1722 | In [2]: foo()\\ |
|
1723 | 1723 | foo() was defined in an editing session |
|
1724 | 1724 | |
|
1725 | 1725 | Now we edit foo. IPython automatically loads the editor with the |
|
1726 | 1726 | (temporary) file where foo() was previously defined: |
|
1727 | 1727 | |
|
1728 | 1728 | In [3]: ed foo\\ |
|
1729 | 1729 | Editing... done. Executing edited code... |
|
1730 | 1730 | |
|
1731 | 1731 | And if we call foo() again we get the modified version: |
|
1732 | 1732 | |
|
1733 | 1733 | In [4]: foo()\\ |
|
1734 | 1734 | foo() has now been changed! |
|
1735 | 1735 | |
|
1736 | 1736 | Here is an example of how to edit a code snippet successive |
|
1737 | 1737 | times. First we call the editor: |
|
1738 | 1738 | |
|
1739 | 1739 | In [8]: ed\\ |
|
1740 | 1740 | Editing... done. Executing edited code...\\ |
|
1741 | 1741 | hello\\ |
|
1742 | 1742 | Out[8]: "print 'hello'\\n" |
|
1743 | 1743 | |
|
1744 | 1744 | Now we call it again with the previous output (stored in _): |
|
1745 | 1745 | |
|
1746 | 1746 | In [9]: ed _\\ |
|
1747 | 1747 | Editing... done. Executing edited code...\\ |
|
1748 | 1748 | hello world\\ |
|
1749 | 1749 | Out[9]: "print 'hello world'\\n" |
|
1750 | 1750 | |
|
1751 | 1751 | Now we call it with the output #8 (stored in _8, also as Out[8]): |
|
1752 | 1752 | |
|
1753 | 1753 | In [10]: ed _8\\ |
|
1754 | 1754 | Editing... done. Executing edited code...\\ |
|
1755 | 1755 | hello again\\ |
|
1756 | 1756 | Out[10]: "print 'hello again'\\n" |
|
1757 | 1757 | |
|
1758 | 1758 | |
|
1759 | 1759 | Changing the default editor hook: |
|
1760 | 1760 | |
|
1761 | 1761 | If you wish to write your own editor hook, you can put it in a |
|
1762 | 1762 | configuration file which you load at startup time. The default hook |
|
1763 | 1763 | is defined in the IPython.hooks module, and you can use that as a |
|
1764 | 1764 | starting example for further modifications. That file also has |
|
1765 | 1765 | general instructions on how to set a new hook for use once you've |
|
1766 | 1766 | defined it.""" |
|
1767 | 1767 | |
|
1768 | 1768 | # FIXME: This function has become a convoluted mess. It needs a |
|
1769 | 1769 | # ground-up rewrite with clean, simple logic. |
|
1770 | 1770 | |
|
1771 | 1771 | def make_filename(arg): |
|
1772 | 1772 | "Make a filename from the given args" |
|
1773 | 1773 | try: |
|
1774 | 1774 | filename = get_py_filename(arg) |
|
1775 | 1775 | except IOError: |
|
1776 | 1776 | if args.endswith('.py'): |
|
1777 | 1777 | filename = arg |
|
1778 | 1778 | else: |
|
1779 | 1779 | filename = None |
|
1780 | 1780 | return filename |
|
1781 | 1781 | |
|
1782 | 1782 | # custom exceptions |
|
1783 | 1783 | class DataIsObject(Exception): pass |
|
1784 | 1784 | |
|
1785 | 1785 | opts,args = self.parse_options(parameter_s,'px') |
|
1786 | 1786 | |
|
1787 | 1787 | # Default line number value |
|
1788 | 1788 | lineno = None |
|
1789 | 1789 | if opts.has_key('p'): |
|
1790 | 1790 | args = '_%s' % last_call[0] |
|
1791 | 1791 | if not self.shell.user_ns.has_key(args): |
|
1792 | 1792 | args = last_call[1] |
|
1793 | 1793 | |
|
1794 | 1794 | # use last_call to remember the state of the previous call, but don't |
|
1795 | 1795 | # let it be clobbered by successive '-p' calls. |
|
1796 | 1796 | try: |
|
1797 | 1797 | last_call[0] = self.shell.outputcache.prompt_count |
|
1798 | 1798 | if not opts.has_key('p'): |
|
1799 | 1799 | last_call[1] = parameter_s |
|
1800 | 1800 | except: |
|
1801 | 1801 | pass |
|
1802 | 1802 | |
|
1803 | 1803 | # by default this is done with temp files, except when the given |
|
1804 | 1804 | # arg is a filename |
|
1805 | 1805 | use_temp = 1 |
|
1806 | 1806 | |
|
1807 | 1807 | if re.match(r'\d',args): |
|
1808 | 1808 | # Mode where user specifies ranges of lines, like in %macro. |
|
1809 | 1809 | # This means that you can't edit files whose names begin with |
|
1810 | 1810 | # numbers this way. Tough. |
|
1811 | 1811 | ranges = args.split() |
|
1812 | 1812 | data = ''.join(self.extract_input_slices(ranges)) |
|
1813 | 1813 | elif args.endswith('.py'): |
|
1814 | 1814 | filename = make_filename(args) |
|
1815 | 1815 | data = '' |
|
1816 | 1816 | use_temp = 0 |
|
1817 | 1817 | elif args: |
|
1818 | 1818 | try: |
|
1819 | 1819 | # Load the parameter given as a variable. If not a string, |
|
1820 | 1820 | # process it as an object instead (below) |
|
1821 | 1821 | |
|
1822 | 1822 | #print '*** args',args,'type',type(args) # dbg |
|
1823 | 1823 | data = eval(args,self.shell.user_ns) |
|
1824 | 1824 | if not type(data) in StringTypes: |
|
1825 | 1825 | raise DataIsObject |
|
1826 | 1826 | except (NameError,SyntaxError): |
|
1827 | 1827 | # given argument is not a variable, try as a filename |
|
1828 | 1828 | filename = make_filename(args) |
|
1829 | 1829 | if filename is None: |
|
1830 | 1830 | warn("Argument given (%s) can't be found as a variable " |
|
1831 | 1831 | "or as a filename." % args) |
|
1832 | 1832 | return |
|
1833 | 1833 | data = '' |
|
1834 | 1834 | use_temp = 0 |
|
1835 | 1835 | except DataIsObject: |
|
1836 | 1836 | # For objects, try to edit the file where they are defined |
|
1837 | 1837 | try: |
|
1838 | 1838 | filename = inspect.getabsfile(data) |
|
1839 | 1839 | datafile = 1 |
|
1840 | 1840 | except TypeError: |
|
1841 | 1841 | filename = make_filename(args) |
|
1842 | 1842 | datafile = 1 |
|
1843 | 1843 | warn('Could not find file where `%s` is defined.\n' |
|
1844 | 1844 | 'Opening a file named `%s`' % (args,filename)) |
|
1845 | 1845 | # Now, make sure we can actually read the source (if it was in |
|
1846 | 1846 | # a temp file it's gone by now). |
|
1847 | 1847 | if datafile: |
|
1848 | 1848 | try: |
|
1849 | 1849 | lineno = inspect.getsourcelines(data)[1] |
|
1850 | 1850 | except IOError: |
|
1851 | 1851 | filename = make_filename(args) |
|
1852 | 1852 | if filename is None: |
|
1853 | 1853 | warn('The file `%s` where `%s` was defined cannot ' |
|
1854 | 1854 | 'be read.' % (filename,data)) |
|
1855 | 1855 | return |
|
1856 | 1856 | use_temp = 0 |
|
1857 | 1857 | else: |
|
1858 | 1858 | data = '' |
|
1859 | 1859 | |
|
1860 | 1860 | if use_temp: |
|
1861 | 1861 | filename = tempfile.mktemp('.py') |
|
1862 | 1862 | self.shell.tempfiles.append(filename) |
|
1863 | 1863 | |
|
1864 | 1864 | if data and use_temp: |
|
1865 | 1865 | tmp_file = open(filename,'w') |
|
1866 | 1866 | tmp_file.write(data) |
|
1867 | 1867 | tmp_file.close() |
|
1868 | 1868 | |
|
1869 | 1869 | # do actual editing here |
|
1870 | 1870 | print 'Editing...', |
|
1871 | 1871 | sys.stdout.flush() |
|
1872 | 1872 | self.shell.hooks.editor(filename,lineno) |
|
1873 | 1873 | if opts.has_key('x'): # -x prevents actual execution |
|
1874 | 1874 | |
|
1875 | 1875 | else: |
|
1876 | 1876 | print 'done. Executing edited code...' |
|
1877 | 1877 | try: |
|
1878 | 1878 | self.shell.safe_execfile(filename,self.shell.user_ns) |
|
1879 | 1879 | except IOError,msg: |
|
1880 | 1880 | if msg.filename == filename: |
|
1881 | 1881 | warn('File not found. Did you forget to save?') |
|
1882 | 1882 | return |
|
1883 | 1883 | else: |
|
1884 | 1884 | self.shell.showtraceback() |
|
1885 | 1885 | except: |
|
1886 | 1886 | self.shell.showtraceback() |
|
1887 | 1887 | if use_temp: |
|
1888 | 1888 | contents = open(filename).read() |
|
1889 | 1889 | return contents |
|
1890 | 1890 | |
|
1891 | 1891 | def magic_xmode(self,parameter_s = ''): |
|
1892 | 1892 | """Switch modes for the exception handlers. |
|
1893 | 1893 | |
|
1894 | 1894 | Valid modes: Plain, Context and Verbose. |
|
1895 | 1895 | |
|
1896 | 1896 | If called without arguments, acts as a toggle.""" |
|
1897 | 1897 | |
|
1898 | 1898 | new_mode = parameter_s.strip().capitalize() |
|
1899 | 1899 | try: |
|
1900 | 1900 | self.InteractiveTB.set_mode(mode = new_mode) |
|
1901 | 1901 | print 'Exception reporting mode:',self.InteractiveTB.mode |
|
1902 | 1902 | except: |
|
1903 | 1903 | warn('Error changing exception modes.\n' + str(sys.exc_info()[1])) |
|
1904 | 1904 | |
|
1905 | 1905 | def magic_colors(self,parameter_s = ''): |
|
1906 | 1906 | """Switch color scheme for prompts, info system and exception handlers. |
|
1907 | 1907 | |
|
1908 | 1908 | Currently implemented schemes: NoColor, Linux, LightBG. |
|
1909 | 1909 | |
|
1910 | 1910 | Color scheme names are not case-sensitive.""" |
|
1911 | 1911 | |
|
1912 | 1912 | new_scheme = parameter_s.strip() |
|
1913 | 1913 | if not new_scheme: |
|
1914 | 1914 | print 'You must specify a color scheme.' |
|
1915 | 1915 | return |
|
1916 | 1916 | # Under Windows, check for Gary Bishop's readline, which is necessary |
|
1917 | 1917 | # for ANSI coloring |
|
1918 | 1918 | if os.name in ['nt','dos']: |
|
1919 | 1919 | try: |
|
1920 | 1920 | import readline |
|
1921 | 1921 | except ImportError: |
|
1922 | 1922 | has_readline = 0 |
|
1923 | 1923 | else: |
|
1924 | 1924 | try: |
|
1925 | 1925 | readline.GetOutputFile() |
|
1926 | 1926 | except AttributeError: |
|
1927 | 1927 | has_readline = 0 |
|
1928 | 1928 | else: |
|
1929 | 1929 | has_readline = 1 |
|
1930 | 1930 | if not has_readline: |
|
1931 | 1931 | msg = """\ |
|
1932 | 1932 | Proper color support under MS Windows requires Gary Bishop's readline library. |
|
1933 | 1933 | You can find it at: |
|
1934 | 1934 | http://sourceforge.net/projects/uncpythontools |
|
1935 | 1935 | Gary's readline needs the ctypes module, from: |
|
1936 | 1936 | http://starship.python.net/crew/theller/ctypes |
|
1937 | 1937 | |
|
1938 | 1938 | Defaulting color scheme to 'NoColor'""" |
|
1939 | 1939 | new_scheme = 'NoColor' |
|
1940 | 1940 | warn(msg) |
|
1941 | 1941 | |
|
1942 | 1942 | # Set prompt colors |
|
1943 | 1943 | try: |
|
1944 | 1944 | self.shell.outputcache.set_colors(new_scheme) |
|
1945 | 1945 | except: |
|
1946 | 1946 | warn('Error changing prompt color schemes.\n' |
|
1947 | 1947 | + str(sys.exc_info()[1])) |
|
1948 | 1948 | else: |
|
1949 | 1949 | self.shell.rc.colors = \ |
|
1950 | 1950 | self.shell.outputcache.color_table.active_scheme_name |
|
1951 | 1951 | # Set exception colors |
|
1952 | 1952 | try: |
|
1953 | 1953 | self.shell.InteractiveTB.set_colors(scheme = new_scheme) |
|
1954 | 1954 | self.shell.SyntaxTB.set_colors(scheme = new_scheme) |
|
1955 | 1955 | except: |
|
1956 | 1956 | warn('Error changing exception color schemes.\n' |
|
1957 | 1957 | + str(sys.exc_info()[1])) |
|
1958 | 1958 | # Set info (for 'object?') colors |
|
1959 | 1959 | if self.shell.rc.color_info: |
|
1960 | 1960 | try: |
|
1961 | 1961 | self.shell.inspector.set_active_scheme(new_scheme) |
|
1962 | 1962 | except: |
|
1963 | 1963 | warn('Error changing object inspector color schemes.\n' |
|
1964 | 1964 | + str(sys.exc_info()[1])) |
|
1965 | 1965 | else: |
|
1966 | 1966 | self.shell.inspector.set_active_scheme('NoColor') |
|
1967 | 1967 | |
|
1968 | 1968 | def magic_color_info(self,parameter_s = ''): |
|
1969 | 1969 | """Toggle color_info. |
|
1970 | 1970 | |
|
1971 | 1971 | The color_info configuration parameter controls whether colors are |
|
1972 | 1972 | used for displaying object details (by things like %psource, %pfile or |
|
1973 | 1973 | the '?' system). This function toggles this value with each call. |
|
1974 | 1974 | |
|
1975 | 1975 | Note that unless you have a fairly recent pager (less works better |
|
1976 | 1976 | than more) in your system, using colored object information displays |
|
1977 | 1977 | will not work properly. Test it and see.""" |
|
1978 | 1978 | |
|
1979 | 1979 | self.shell.rc.color_info = 1 - self.shell.rc.color_info |
|
1980 | 1980 | self.magic_colors(self.shell.rc.colors) |
|
1981 | 1981 | print 'Object introspection functions have now coloring:', |
|
1982 | 1982 | print ['OFF','ON'][self.shell.rc.color_info] |
|
1983 | 1983 | |
|
1984 | 1984 | def magic_Pprint(self, parameter_s=''): |
|
1985 | 1985 | """Toggle pretty printing on/off.""" |
|
1986 | 1986 | |
|
1987 | 1987 | self.shell.outputcache.Pprint = 1 - self.shell.outputcache.Pprint |
|
1988 | 1988 | print 'Pretty printing has been turned', \ |
|
1989 | 1989 | ['OFF','ON'][self.shell.outputcache.Pprint] |
|
1990 | 1990 | |
|
1991 | def magic_exit(self, parameter_s=''): | |
|
1992 | """Exit IPython, confirming if configured to do so. | |
|
1993 | ||
|
1994 | You can configure whether IPython asks for confirmation upon exit by | |
|
1995 | setting the confirm_exit flag in the ipythonrc file.""" | |
|
1996 | ||
|
1997 | self.shell.exit() | |
|
1998 | ||
|
1999 | def magic_quit(self, parameter_s=''): | |
|
2000 | """Exit IPython, confirming if configured to do so (like %exit)""" | |
|
2001 | ||
|
2002 | self.shell.exit() | |
|
2003 | ||
|
1991 | 2004 | def magic_Exit(self, parameter_s=''): |
|
1992 | 2005 | """Exit IPython without confirmation.""" |
|
1993 | 2006 | |
|
1994 | 2007 | self.shell.exit_now = True |
|
1995 | 2008 | |
|
1996 | 2009 | def magic_Quit(self, parameter_s=''): |
|
1997 | 2010 | """Exit IPython without confirmation (like %Exit).""" |
|
1998 | 2011 | |
|
1999 | 2012 | self.shell.exit_now = True |
|
2000 | 2013 | |
|
2001 | 2014 | #...................................................................... |
|
2002 | 2015 | # Functions to implement unix shell-type things |
|
2003 | 2016 | |
|
2004 | 2017 | def magic_alias(self, parameter_s = ''): |
|
2005 | 2018 | """Define an alias for a system command. |
|
2006 | 2019 | |
|
2007 | 2020 | '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd' |
|
2008 | 2021 | |
|
2009 | 2022 | Then, typing 'alias_name params' will execute the system command 'cmd |
|
2010 | 2023 | params' (from your underlying operating system). |
|
2011 | 2024 | |
|
2012 | 2025 | Aliases have lower precedence than magic functions and Python normal |
|
2013 | 2026 | variables, so if 'foo' is both a Python variable and an alias, the |
|
2014 | 2027 | alias can not be executed until 'del foo' removes the Python variable. |
|
2015 | 2028 | |
|
2016 | 2029 | You can use the %l specifier in an alias definition to represent the |
|
2017 | 2030 | whole line when the alias is called. For example: |
|
2018 | 2031 | |
|
2019 | 2032 | In [2]: alias all echo "Input in brackets: <%l>"\\ |
|
2020 | 2033 | In [3]: all hello world\\ |
|
2021 | 2034 | Input in brackets: <hello world> |
|
2022 | 2035 | |
|
2023 | 2036 | You can also define aliases with parameters using %s specifiers (one |
|
2024 | 2037 | per parameter): |
|
2025 | 2038 | |
|
2026 | 2039 | In [1]: alias parts echo first %s second %s\\ |
|
2027 | 2040 | In [2]: %parts A B\\ |
|
2028 | 2041 | first A second B\\ |
|
2029 | 2042 | In [3]: %parts A\\ |
|
2030 | 2043 | Incorrect number of arguments: 2 expected.\\ |
|
2031 | 2044 | parts is an alias to: 'echo first %s second %s' |
|
2032 | 2045 | |
|
2033 | 2046 | Note that %l and %s are mutually exclusive. You can only use one or |
|
2034 | 2047 | the other in your aliases. |
|
2035 | 2048 | |
|
2036 | 2049 | Aliases expand Python variables just like system calls using ! or !! |
|
2037 | 2050 | do: all expressions prefixed with '$' get expanded. For details of |
|
2038 | 2051 | the semantic rules, see PEP-215: |
|
2039 | 2052 | http://www.python.org/peps/pep-0215.html. This is the library used by |
|
2040 | 2053 | IPython for variable expansion. If you want to access a true shell |
|
2041 | 2054 | variable, an extra $ is necessary to prevent its expansion by IPython: |
|
2042 | 2055 | |
|
2043 | 2056 | In [6]: alias show echo\\ |
|
2044 | 2057 | In [7]: PATH='A Python string'\\ |
|
2045 | 2058 | In [8]: show $PATH\\ |
|
2046 | 2059 | A Python string\\ |
|
2047 | 2060 | In [9]: show $$PATH\\ |
|
2048 | 2061 | /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:... |
|
2049 | 2062 | |
|
2050 | 2063 | You can use the alias facility to acess all of $PATH. See the %rehash |
|
2051 | 2064 | and %rehashx functions, which automatically create aliases for the |
|
2052 | 2065 | contents of your $PATH. |
|
2053 | 2066 | |
|
2054 | 2067 | If called with no parameters, %alias prints the current alias table.""" |
|
2055 | 2068 | |
|
2056 | 2069 | par = parameter_s.strip() |
|
2057 | 2070 | if not par: |
|
2058 | 2071 | if self.shell.rc.automagic: |
|
2059 | 2072 | prechar = '' |
|
2060 | 2073 | else: |
|
2061 | 2074 | prechar = self.shell.ESC_MAGIC |
|
2062 | 2075 | print 'Alias\t\tSystem Command\n'+'-'*30 |
|
2063 | 2076 | atab = self.shell.alias_table |
|
2064 | 2077 | aliases = atab.keys() |
|
2065 | 2078 | aliases.sort() |
|
2066 | 2079 | for alias in aliases: |
|
2067 | 2080 | print prechar+alias+'\t\t'+atab[alias][1] |
|
2068 | 2081 | print '-'*30+'\nTotal number of aliases:',len(aliases) |
|
2069 | 2082 | return |
|
2070 | 2083 | try: |
|
2071 | 2084 | alias,cmd = par.split(None,1) |
|
2072 | 2085 | except: |
|
2073 | 2086 | print OInspect.getdoc(self.magic_alias) |
|
2074 | 2087 | else: |
|
2075 | 2088 | nargs = cmd.count('%s') |
|
2076 | 2089 | if nargs>0 and cmd.find('%l')>=0: |
|
2077 | 2090 | error('The %s and %l specifiers are mutually exclusive ' |
|
2078 | 2091 | 'in alias definitions.') |
|
2079 | 2092 | else: # all looks OK |
|
2080 | 2093 | self.shell.alias_table[alias] = (nargs,cmd) |
|
2081 | 2094 | self.shell.alias_table_validate(verbose=1) |
|
2082 | 2095 | # end magic_alias |
|
2083 | 2096 | |
|
2084 | 2097 | def magic_unalias(self, parameter_s = ''): |
|
2085 | 2098 | """Remove an alias""" |
|
2086 | 2099 | |
|
2087 | 2100 | aname = parameter_s.strip() |
|
2088 | 2101 | if aname in self.shell.alias_table: |
|
2089 | 2102 | del self.shell.alias_table[aname] |
|
2090 | 2103 | |
|
2091 | 2104 | def magic_rehash(self, parameter_s = ''): |
|
2092 | 2105 | """Update the alias table with all entries in $PATH. |
|
2093 | 2106 | |
|
2094 | 2107 | This version does no checks on execute permissions or whether the |
|
2095 | 2108 | contents of $PATH are truly files (instead of directories or something |
|
2096 | 2109 | else). For such a safer (but slower) version, use %rehashx.""" |
|
2097 | 2110 | |
|
2098 | 2111 | # This function (and rehashx) manipulate the alias_table directly |
|
2099 | 2112 | # rather than calling magic_alias, for speed reasons. A rehash on a |
|
2100 | 2113 | # typical Linux box involves several thousand entries, so efficiency |
|
2101 | 2114 | # here is a top concern. |
|
2102 | 2115 | |
|
2103 | 2116 | path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep)) |
|
2104 | 2117 | alias_table = self.shell.alias_table |
|
2105 | 2118 | for pdir in path: |
|
2106 | 2119 | for ff in os.listdir(pdir): |
|
2107 | 2120 | # each entry in the alias table must be (N,name), where |
|
2108 | 2121 | # N is the number of positional arguments of the alias. |
|
2109 | 2122 | alias_table[ff] = (0,ff) |
|
2110 | 2123 | # Make sure the alias table doesn't contain keywords or builtins |
|
2111 | 2124 | self.shell.alias_table_validate() |
|
2112 | 2125 | # Call again init_auto_alias() so we get 'rm -i' and other modified |
|
2113 | 2126 | # aliases since %rehash will probably clobber them |
|
2114 | 2127 | self.shell.init_auto_alias() |
|
2115 | 2128 | |
|
2116 | 2129 | def magic_rehashx(self, parameter_s = ''): |
|
2117 | 2130 | """Update the alias table with all executable files in $PATH. |
|
2118 | 2131 | |
|
2119 | 2132 | This version explicitly checks that every entry in $PATH is a file |
|
2120 | 2133 | with execute access (os.X_OK), so it is much slower than %rehash. |
|
2121 | 2134 | |
|
2122 | 2135 | Under Windows, it checks executability as a match agains a |
|
2123 | 2136 | '|'-separated string of extensions, stored in the IPython config |
|
2124 | 2137 | variable win_exec_ext. This defaults to 'exe|com|bat'. """ |
|
2125 | 2138 | |
|
2126 | 2139 | path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep)) |
|
2127 | 2140 | alias_table = self.shell.alias_table |
|
2128 | 2141 | |
|
2129 | 2142 | if os.name == 'posix': |
|
2130 | 2143 | isexec = lambda fname:os.path.isfile(fname) and \ |
|
2131 | 2144 | os.access(fname,os.X_OK) |
|
2132 | 2145 | else: |
|
2133 | 2146 | |
|
2134 | 2147 | try: |
|
2135 | 2148 | winext = os.environ['pathext'].replace(';','|').replace('.','') |
|
2136 | 2149 | except KeyError: |
|
2137 | 2150 | winext = 'exe|com|bat' |
|
2138 | 2151 | |
|
2139 | 2152 | execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE) |
|
2140 | 2153 | isexec = lambda fname:os.path.isfile(fname) and execre.match(fname) |
|
2141 | 2154 | savedir = os.getcwd() |
|
2142 | 2155 | try: |
|
2143 | 2156 | # write the whole loop for posix/Windows so we don't have an if in |
|
2144 | 2157 | # the innermost part |
|
2145 | 2158 | if os.name == 'posix': |
|
2146 | 2159 | for pdir in path: |
|
2147 | 2160 | os.chdir(pdir) |
|
2148 | 2161 | for ff in os.listdir(pdir): |
|
2149 | 2162 | if isexec(ff): |
|
2150 | 2163 | # each entry in the alias table must be (N,name), |
|
2151 | 2164 | # where N is the number of positional arguments of the |
|
2152 | 2165 | # alias. |
|
2153 | 2166 | alias_table[ff] = (0,ff) |
|
2154 | 2167 | else: |
|
2155 | 2168 | for pdir in path: |
|
2156 | 2169 | os.chdir(pdir) |
|
2157 | 2170 | for ff in os.listdir(pdir): |
|
2158 | 2171 | if isexec(ff): |
|
2159 | 2172 | alias_table[execre.sub(r'\1',ff)] = (0,ff) |
|
2160 | 2173 | # Make sure the alias table doesn't contain keywords or builtins |
|
2161 | 2174 | self.shell.alias_table_validate() |
|
2162 | 2175 | # Call again init_auto_alias() so we get 'rm -i' and other |
|
2163 | 2176 | # modified aliases since %rehashx will probably clobber them |
|
2164 | 2177 | self.shell.init_auto_alias() |
|
2165 | 2178 | finally: |
|
2166 | 2179 | os.chdir(savedir) |
|
2167 | 2180 | |
|
2168 | 2181 | def magic_pwd(self, parameter_s = ''): |
|
2169 | 2182 | """Return the current working directory path.""" |
|
2170 | 2183 | return os.getcwd() |
|
2171 | 2184 | |
|
2172 | 2185 | def magic_cd(self, parameter_s=''): |
|
2173 | 2186 | """Change the current working directory. |
|
2174 | 2187 | |
|
2175 | 2188 | This command automatically maintains an internal list of directories |
|
2176 | 2189 | you visit during your IPython session, in the variable _dh. The |
|
2177 | 2190 | command %dhist shows this history nicely formatted. |
|
2178 | 2191 | |
|
2179 | 2192 | Usage: |
|
2180 | 2193 | |
|
2181 | 2194 | cd 'dir': changes to directory 'dir'. |
|
2182 | 2195 | |
|
2183 | 2196 | cd -: changes to the last visited directory. |
|
2184 | 2197 | |
|
2185 | 2198 | cd -<n>: changes to the n-th directory in the directory history. |
|
2186 | 2199 | |
|
2187 | 2200 | cd -b <bookmark_name>: jump to a bookmark set by %bookmark |
|
2188 | 2201 | (note: cd <bookmark_name> is enough if there is no |
|
2189 | 2202 | directory <bookmark_name>, but a bookmark with the name exists.) |
|
2190 | 2203 | |
|
2191 | 2204 | Options: |
|
2192 | 2205 | |
|
2193 | 2206 | -q: quiet. Do not print the working directory after the cd command is |
|
2194 | 2207 | executed. By default IPython's cd command does print this directory, |
|
2195 | 2208 | since the default prompts do not display path information. |
|
2196 | 2209 | |
|
2197 | 2210 | Note that !cd doesn't work for this purpose because the shell where |
|
2198 | 2211 | !command runs is immediately discarded after executing 'command'.""" |
|
2199 | 2212 | |
|
2200 | 2213 | parameter_s = parameter_s.strip() |
|
2201 | 2214 | bkms = self.shell.persist.get("bookmarks",{}) |
|
2202 | 2215 | |
|
2203 | 2216 | numcd = re.match(r'(-)(\d+)$',parameter_s) |
|
2204 | 2217 | # jump in directory history by number |
|
2205 | 2218 | if numcd: |
|
2206 | 2219 | nn = int(numcd.group(2)) |
|
2207 | 2220 | try: |
|
2208 | 2221 | ps = self.shell.user_ns['_dh'][nn] |
|
2209 | 2222 | except IndexError: |
|
2210 | 2223 | print 'The requested directory does not exist in history.' |
|
2211 | 2224 | return |
|
2212 | 2225 | else: |
|
2213 | 2226 | opts = {} |
|
2214 | 2227 | else: |
|
2215 | 2228 | opts,ps = self.parse_options(parameter_s,'qb',mode='string') |
|
2216 | 2229 | # jump to previous |
|
2217 | 2230 | if ps == '-': |
|
2218 | 2231 | try: |
|
2219 | 2232 | ps = self.shell.user_ns['_dh'][-2] |
|
2220 | 2233 | except IndexError: |
|
2221 | 2234 | print 'No previous directory to change to.' |
|
2222 | 2235 | return |
|
2223 | 2236 | # jump to bookmark |
|
2224 | 2237 | elif opts.has_key('b') or (bkms.has_key(ps) and not os.path.isdir(ps)): |
|
2225 | 2238 | if bkms.has_key(ps): |
|
2226 | 2239 | target = bkms[ps] |
|
2227 | 2240 | print '(bookmark:%s) -> %s' % (ps,target) |
|
2228 | 2241 | ps = target |
|
2229 | 2242 | else: |
|
2230 | 2243 | if bkms: |
|
2231 | 2244 | error("Bookmark '%s' not found. " |
|
2232 | 2245 | "Use '%bookmark -l' to see your bookmarks." % ps) |
|
2233 | 2246 | else: |
|
2234 | 2247 | print "Bookmarks not set - use %bookmark <bookmarkname>" |
|
2235 | 2248 | return |
|
2236 | 2249 | |
|
2237 | 2250 | # at this point ps should point to the target dir |
|
2238 | 2251 | if ps: |
|
2239 | 2252 | try: |
|
2240 | 2253 | os.chdir(os.path.expanduser(ps)) |
|
2241 | 2254 | except OSError: |
|
2242 | 2255 | print sys.exc_info()[1] |
|
2243 | 2256 | else: |
|
2244 | 2257 | self.shell.user_ns['_dh'].append(os.getcwd()) |
|
2245 | 2258 | else: |
|
2246 | 2259 | os.chdir(self.home_dir) |
|
2247 | 2260 | self.shell.user_ns['_dh'].append(os.getcwd()) |
|
2248 | 2261 | if not 'q' in opts: |
|
2249 | 2262 | print self.shell.user_ns['_dh'][-1] |
|
2250 | 2263 | |
|
2251 | 2264 | def magic_dhist(self, parameter_s=''): |
|
2252 | 2265 | """Print your history of visited directories. |
|
2253 | 2266 | |
|
2254 | 2267 | %dhist -> print full history\\ |
|
2255 | 2268 | %dhist n -> print last n entries only\\ |
|
2256 | 2269 | %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\ |
|
2257 | 2270 | |
|
2258 | 2271 | This history is automatically maintained by the %cd command, and |
|
2259 | 2272 | always available as the global list variable _dh. You can use %cd -<n> |
|
2260 | 2273 | to go to directory number <n>.""" |
|
2261 | 2274 | |
|
2262 | 2275 | dh = self.shell.user_ns['_dh'] |
|
2263 | 2276 | if parameter_s: |
|
2264 | 2277 | try: |
|
2265 | 2278 | args = map(int,parameter_s.split()) |
|
2266 | 2279 | except: |
|
2267 | 2280 | self.arg_err(Magic.magic_dhist) |
|
2268 | 2281 | return |
|
2269 | 2282 | if len(args) == 1: |
|
2270 | 2283 | ini,fin = max(len(dh)-(args[0]),0),len(dh) |
|
2271 | 2284 | elif len(args) == 2: |
|
2272 | 2285 | ini,fin = args |
|
2273 | 2286 | else: |
|
2274 | 2287 | self.arg_err(Magic.magic_dhist) |
|
2275 | 2288 | return |
|
2276 | 2289 | else: |
|
2277 | 2290 | ini,fin = 0,len(dh) |
|
2278 | 2291 | nlprint(dh, |
|
2279 | 2292 | header = 'Directory history (kept in _dh)', |
|
2280 | 2293 | start=ini,stop=fin) |
|
2281 | 2294 | |
|
2282 | 2295 | def magic_env(self, parameter_s=''): |
|
2283 | 2296 | """List environment variables.""" |
|
2284 | 2297 | |
|
2285 | 2298 | # environ is an instance of UserDict |
|
2286 | 2299 | return os.environ.data |
|
2287 | 2300 | |
|
2288 | 2301 | def magic_pushd(self, parameter_s=''): |
|
2289 | 2302 | """Place the current dir on stack and change directory. |
|
2290 | 2303 | |
|
2291 | 2304 | Usage:\\ |
|
2292 | 2305 | %pushd ['dirname'] |
|
2293 | 2306 | |
|
2294 | 2307 | %pushd with no arguments does a %pushd to your home directory. |
|
2295 | 2308 | """ |
|
2296 | 2309 | if parameter_s == '': parameter_s = '~' |
|
2297 | 2310 | if len(self.dir_stack)>0 and os.path.expanduser(parameter_s) != \ |
|
2298 | 2311 | os.path.expanduser(self.dir_stack[0]): |
|
2299 | 2312 | try: |
|
2300 | 2313 | self.magic_cd(parameter_s) |
|
2301 | 2314 | self.dir_stack.insert(0,os.getcwd().replace(self.home_dir,'~')) |
|
2302 | 2315 | self.magic_dirs() |
|
2303 | 2316 | except: |
|
2304 | 2317 | print 'Invalid directory' |
|
2305 | 2318 | else: |
|
2306 | 2319 | print 'You are already there!' |
|
2307 | 2320 | |
|
2308 | 2321 | def magic_popd(self, parameter_s=''): |
|
2309 | 2322 | """Change to directory popped off the top of the stack. |
|
2310 | 2323 | """ |
|
2311 | 2324 | if len (self.dir_stack) > 1: |
|
2312 | 2325 | self.dir_stack.pop(0) |
|
2313 | 2326 | self.magic_cd(self.dir_stack[0]) |
|
2314 | 2327 | print self.dir_stack[0] |
|
2315 | 2328 | else: |
|
2316 | 2329 | print "You can't remove the starting directory from the stack:",\ |
|
2317 | 2330 | self.dir_stack |
|
2318 | 2331 | |
|
2319 | 2332 | def magic_dirs(self, parameter_s=''): |
|
2320 | 2333 | """Return the current directory stack.""" |
|
2321 | 2334 | |
|
2322 | 2335 | return self.dir_stack[:] |
|
2323 | 2336 | |
|
2324 | 2337 | def magic_sc(self, parameter_s=''): |
|
2325 | 2338 | """Shell capture - execute a shell command and capture its output. |
|
2326 | 2339 | |
|
2327 | 2340 | %sc [options] varname=command |
|
2328 | 2341 | |
|
2329 | 2342 | IPython will run the given command using commands.getoutput(), and |
|
2330 | 2343 | will then update the user's interactive namespace with a variable |
|
2331 | 2344 | called varname, containing the value of the call. Your command can |
|
2332 | 2345 | contain shell wildcards, pipes, etc. |
|
2333 | 2346 | |
|
2334 | 2347 | The '=' sign in the syntax is mandatory, and the variable name you |
|
2335 | 2348 | supply must follow Python's standard conventions for valid names. |
|
2336 | 2349 | |
|
2337 | 2350 | Options: |
|
2338 | 2351 | |
|
2339 | 2352 | -l: list output. Split the output on newlines into a list before |
|
2340 | 2353 | assigning it to the given variable. By default the output is stored |
|
2341 | 2354 | as a single string. |
|
2342 | 2355 | |
|
2343 | 2356 | -v: verbose. Print the contents of the variable. |
|
2344 | 2357 | |
|
2345 | 2358 | In most cases you should not need to split as a list, because the |
|
2346 | 2359 | returned value is a special type of string which can automatically |
|
2347 | 2360 | provide its contents either as a list (split on newlines) or as a |
|
2348 | 2361 | space-separated string. These are convenient, respectively, either |
|
2349 | 2362 | for sequential processing or to be passed to a shell command. |
|
2350 | 2363 | |
|
2351 | 2364 | For example: |
|
2352 | 2365 | |
|
2353 | 2366 | # Capture into variable a |
|
2354 | 2367 | In [9]: sc a=ls *py |
|
2355 | 2368 | |
|
2356 | 2369 | # a is a string with embedded newlines |
|
2357 | 2370 | In [10]: a |
|
2358 | 2371 | Out[10]: 'setup.py\nwin32_manual_post_install.py' |
|
2359 | 2372 | |
|
2360 | 2373 | # which can be seen as a list: |
|
2361 | 2374 | In [11]: a.l |
|
2362 | 2375 | Out[11]: ['setup.py', 'win32_manual_post_install.py'] |
|
2363 | 2376 | |
|
2364 | 2377 | # or as a whitespace-separated string: |
|
2365 | 2378 | In [12]: a.s |
|
2366 | 2379 | Out[12]: 'setup.py win32_manual_post_install.py' |
|
2367 | 2380 | |
|
2368 | 2381 | # a.s is useful to pass as a single command line: |
|
2369 | 2382 | In [13]: !wc -l $a.s |
|
2370 | 2383 | 146 setup.py |
|
2371 | 2384 | 130 win32_manual_post_install.py |
|
2372 | 2385 | 276 total |
|
2373 | 2386 | |
|
2374 | 2387 | # while the list form is useful to loop over: |
|
2375 | 2388 | In [14]: for f in a.l: |
|
2376 | 2389 | ....: !wc -l $f |
|
2377 | 2390 | ....: |
|
2378 | 2391 | 146 setup.py |
|
2379 | 2392 | 130 win32_manual_post_install.py |
|
2380 | 2393 | |
|
2381 | 2394 | Similiarly, the lists returned by the -l option are also special, in |
|
2382 | 2395 | the sense that you can equally invoke the .s attribute on them to |
|
2383 | 2396 | automatically get a whitespace-separated string from their contents: |
|
2384 | 2397 | |
|
2385 | 2398 | In [1]: sc -l b=ls *py |
|
2386 | 2399 | |
|
2387 | 2400 | In [2]: b |
|
2388 | 2401 | Out[2]: ['setup.py', 'win32_manual_post_install.py'] |
|
2389 | 2402 | |
|
2390 | 2403 | In [3]: b.s |
|
2391 | 2404 | Out[3]: 'setup.py win32_manual_post_install.py' |
|
2392 | 2405 | |
|
2393 | 2406 | In summary, both the lists and strings used for ouptut capture have |
|
2394 | 2407 | the following special attributes: |
|
2395 | 2408 | |
|
2396 | 2409 | .l (or .list) : value as list. |
|
2397 | 2410 | .n (or .nlstr): value as newline-separated string. |
|
2398 | 2411 | .s (or .spstr): value as space-separated string. |
|
2399 | 2412 | """ |
|
2400 | 2413 | |
|
2401 | 2414 | opts,args = self.parse_options(parameter_s,'lv') |
|
2402 | 2415 | # Try to get a variable name and command to run |
|
2403 | 2416 | try: |
|
2404 | 2417 | # the variable name must be obtained from the parse_options |
|
2405 | 2418 | # output, which uses shlex.split to strip options out. |
|
2406 | 2419 | var,_ = args.split('=',1) |
|
2407 | 2420 | var = var.strip() |
|
2408 | 2421 | # But the the command has to be extracted from the original input |
|
2409 | 2422 | # parameter_s, not on what parse_options returns, to avoid the |
|
2410 | 2423 | # quote stripping which shlex.split performs on it. |
|
2411 | 2424 | _,cmd = parameter_s.split('=',1) |
|
2412 | 2425 | except ValueError: |
|
2413 | 2426 | var,cmd = '','' |
|
2414 | 2427 | if not var: |
|
2415 | 2428 | error('you must specify a variable to assign the command to.') |
|
2416 | 2429 | return |
|
2417 | 2430 | # If all looks ok, proceed |
|
2418 | 2431 | out,err = self.shell.getoutputerror(cmd) |
|
2419 | 2432 | if err: |
|
2420 | 2433 | print >> Term.cerr,err |
|
2421 | 2434 | if opts.has_key('l'): |
|
2422 | 2435 | out = SList(out.split('\n')) |
|
2423 | 2436 | else: |
|
2424 | 2437 | out = LSString(out) |
|
2425 | 2438 | if opts.has_key('v'): |
|
2426 | 2439 | print '%s ==\n%s' % (var,pformat(out)) |
|
2427 | 2440 | self.shell.user_ns.update({var:out}) |
|
2428 | 2441 | |
|
2429 | 2442 | def magic_sx(self, parameter_s=''): |
|
2430 | 2443 | """Shell execute - run a shell command and capture its output. |
|
2431 | 2444 | |
|
2432 | 2445 | %sx command |
|
2433 | 2446 | |
|
2434 | 2447 | IPython will run the given command using commands.getoutput(), and |
|
2435 | 2448 | return the result formatted as a list (split on '\\n'). Since the |
|
2436 | 2449 | output is _returned_, it will be stored in ipython's regular output |
|
2437 | 2450 | cache Out[N] and in the '_N' automatic variables. |
|
2438 | 2451 | |
|
2439 | 2452 | Notes: |
|
2440 | 2453 | |
|
2441 | 2454 | 1) If an input line begins with '!!', then %sx is automatically |
|
2442 | 2455 | invoked. That is, while: |
|
2443 | 2456 | !ls |
|
2444 | 2457 | causes ipython to simply issue system('ls'), typing |
|
2445 | 2458 | !!ls |
|
2446 | 2459 | is a shorthand equivalent to: |
|
2447 | 2460 | %sx ls |
|
2448 | 2461 | |
|
2449 | 2462 | 2) %sx differs from %sc in that %sx automatically splits into a list, |
|
2450 | 2463 | like '%sc -l'. The reason for this is to make it as easy as possible |
|
2451 | 2464 | to process line-oriented shell output via further python commands. |
|
2452 | 2465 | %sc is meant to provide much finer control, but requires more |
|
2453 | 2466 | typing. |
|
2454 | 2467 | |
|
2455 | 2468 | 3) Just like %sc -l, this is a list with special attributes: |
|
2456 | 2469 | |
|
2457 | 2470 | .l (or .list) : value as list. |
|
2458 | 2471 | .n (or .nlstr): value as newline-separated string. |
|
2459 | 2472 | .s (or .spstr): value as whitespace-separated string. |
|
2460 | 2473 | |
|
2461 | 2474 | This is very useful when trying to use such lists as arguments to |
|
2462 | 2475 | system commands.""" |
|
2463 | 2476 | |
|
2464 | 2477 | if parameter_s: |
|
2465 | 2478 | out,err = self.shell.getoutputerror(parameter_s) |
|
2466 | 2479 | if err: |
|
2467 | 2480 | print >> Term.cerr,err |
|
2468 | 2481 | return SList(out.split('\n')) |
|
2469 | 2482 | |
|
2470 | 2483 | def magic_bg(self, parameter_s=''): |
|
2471 | 2484 | """Run a job in the background, in a separate thread. |
|
2472 | 2485 | |
|
2473 | 2486 | For example, |
|
2474 | 2487 | |
|
2475 | 2488 | %bg myfunc(x,y,z=1) |
|
2476 | 2489 | |
|
2477 | 2490 | will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the |
|
2478 | 2491 | execution starts, a message will be printed indicating the job |
|
2479 | 2492 | number. If your job number is 5, you can use |
|
2480 | 2493 | |
|
2481 | 2494 | myvar = jobs.result(5) or myvar = jobs[5].result |
|
2482 | 2495 | |
|
2483 | 2496 | to assign this result to variable 'myvar'. |
|
2484 | 2497 | |
|
2485 | 2498 | IPython has a job manager, accessible via the 'jobs' object. You can |
|
2486 | 2499 | type jobs? to get more information about it, and use jobs.<TAB> to see |
|
2487 | 2500 | its attributes. All attributes not starting with an underscore are |
|
2488 | 2501 | meant for public use. |
|
2489 | 2502 | |
|
2490 | 2503 | In particular, look at the jobs.new() method, which is used to create |
|
2491 | 2504 | new jobs. This magic %bg function is just a convenience wrapper |
|
2492 | 2505 | around jobs.new(), for expression-based jobs. If you want to create a |
|
2493 | 2506 | new job with an explicit function object and arguments, you must call |
|
2494 | 2507 | jobs.new() directly. |
|
2495 | 2508 | |
|
2496 | 2509 | The jobs.new docstring also describes in detail several important |
|
2497 | 2510 | caveats associated with a thread-based model for background job |
|
2498 | 2511 | execution. Type jobs.new? for details. |
|
2499 | 2512 | |
|
2500 | 2513 | You can check the status of all jobs with jobs.status(). |
|
2501 | 2514 | |
|
2502 | 2515 | The jobs variable is set by IPython into the Python builtin namespace. |
|
2503 | 2516 | If you ever declare a variable named 'jobs', you will shadow this |
|
2504 | 2517 | name. You can either delete your global jobs variable to regain |
|
2505 | 2518 | access to the job manager, or make a new name and assign it manually |
|
2506 | 2519 | to the manager (stored in IPython's namespace). For example, to |
|
2507 | 2520 | assign the job manager to the Jobs name, use: |
|
2508 | 2521 | |
|
2509 | 2522 | Jobs = __builtins__.jobs""" |
|
2510 | 2523 | |
|
2511 | 2524 | self.shell.jobs.new(parameter_s,self.shell.user_ns) |
|
2512 | 2525 | |
|
2513 | 2526 | def magic_bookmark(self, parameter_s=''): |
|
2514 | 2527 | """Manage IPython's bookmark system. |
|
2515 | 2528 | |
|
2516 | 2529 | %bookmark <name> - set bookmark to current dir |
|
2517 | 2530 | %bookmark <name> <dir> - set bookmark to <dir> |
|
2518 | 2531 | %bookmark -l - list all bookmarks |
|
2519 | 2532 | %bookmark -d <name> - remove bookmark |
|
2520 | 2533 | %bookmark -r - remove all bookmarks |
|
2521 | 2534 | |
|
2522 | 2535 | You can later on access a bookmarked folder with: |
|
2523 | 2536 | %cd -b <name> |
|
2524 | 2537 | or simply '%cd <name>' if there is no directory called <name> AND |
|
2525 | 2538 | there is such a bookmark defined. |
|
2526 | 2539 | |
|
2527 | 2540 | Your bookmarks persist through IPython sessions, but they are |
|
2528 | 2541 | associated with each profile.""" |
|
2529 | 2542 | |
|
2530 | 2543 | opts,args = self.parse_options(parameter_s,'drl',mode='list') |
|
2531 | 2544 | if len(args) > 2: |
|
2532 | 2545 | error('You can only give at most two arguments') |
|
2533 | 2546 | return |
|
2534 | 2547 | |
|
2535 | 2548 | bkms = self.shell.persist.get('bookmarks',{}) |
|
2536 | 2549 | |
|
2537 | 2550 | if opts.has_key('d'): |
|
2538 | 2551 | try: |
|
2539 | 2552 | todel = args[0] |
|
2540 | 2553 | except IndexError: |
|
2541 | 2554 | error('You must provide a bookmark to delete') |
|
2542 | 2555 | else: |
|
2543 | 2556 | try: |
|
2544 | 2557 | del bkms[todel] |
|
2545 | 2558 | except: |
|
2546 | 2559 | error("Can't delete bookmark '%s'" % todel) |
|
2547 | 2560 | elif opts.has_key('r'): |
|
2548 | 2561 | bkms = {} |
|
2549 | 2562 | elif opts.has_key('l'): |
|
2550 | 2563 | bks = bkms.keys() |
|
2551 | 2564 | bks.sort() |
|
2552 | 2565 | if bks: |
|
2553 | 2566 | size = max(map(len,bks)) |
|
2554 | 2567 | else: |
|
2555 | 2568 | size = 0 |
|
2556 | 2569 | fmt = '%-'+str(size)+'s -> %s' |
|
2557 | 2570 | print 'Current bookmarks:' |
|
2558 | 2571 | for bk in bks: |
|
2559 | 2572 | print fmt % (bk,bkms[bk]) |
|
2560 | 2573 | else: |
|
2561 | 2574 | if not args: |
|
2562 | 2575 | error("You must specify the bookmark name") |
|
2563 | 2576 | elif len(args)==1: |
|
2564 | 2577 | bkms[args[0]] = os.getcwd() |
|
2565 | 2578 | elif len(args)==2: |
|
2566 | 2579 | bkms[args[0]] = args[1] |
|
2567 | 2580 | self.persist['bookmarks'] = bkms |
|
2568 | 2581 | |
|
2569 | 2582 | def magic_pycat(self, parameter_s=''): |
|
2570 | 2583 | """Show a syntax-highlighted file through a pager. |
|
2571 | 2584 | |
|
2572 | 2585 | This magic is similar to the cat utility, but it will assume the file |
|
2573 | 2586 | to be Python source and will show it with syntax highlighting. """ |
|
2574 | 2587 | |
|
2575 | 2588 | filename = get_py_filename(parameter_s) |
|
2576 | 2589 | page(self.shell.colorize(file_read(filename)), |
|
2577 | 2590 | screen_lines=self.shell.rc.screen_length) |
|
2578 | 2591 | |
|
2579 | 2592 | # end Magic |
@@ -1,1964 +1,1958 b'' | |||
|
1 | 1 | # -*- coding: utf-8 -*- |
|
2 | 2 | """ |
|
3 | 3 | IPython -- An enhanced Interactive Python |
|
4 | 4 | |
|
5 | 5 | Requires Python 2.1 or newer. |
|
6 | 6 | |
|
7 | 7 | This file contains all the classes and helper functions specific to IPython. |
|
8 | 8 | |
|
9 |
$Id: iplib.py 96 |
|
|
9 | $Id: iplib.py 962 2005-12-28 18:04:59Z fperez $ | |
|
10 | 10 | """ |
|
11 | 11 | |
|
12 | 12 | #***************************************************************************** |
|
13 | 13 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and |
|
14 | 14 | # Copyright (C) 2001-2005 Fernando Perez. <fperez@colorado.edu> |
|
15 | 15 | # |
|
16 | 16 | # Distributed under the terms of the BSD License. The full license is in |
|
17 | 17 | # the file COPYING, distributed as part of this software. |
|
18 | 18 | # |
|
19 | 19 | # Note: this code originally subclassed code.InteractiveConsole from the |
|
20 | 20 | # Python standard library. Over time, all of that class has been copied |
|
21 | 21 | # verbatim here for modifications which could not be accomplished by |
|
22 | 22 | # subclassing. At this point, there are no dependencies at all on the code |
|
23 | 23 | # module anymore (it is not even imported). The Python License (sec. 2) |
|
24 | 24 | # allows for this, but it's always nice to acknowledge credit where credit is |
|
25 | 25 | # due. |
|
26 | 26 | #***************************************************************************** |
|
27 | 27 | |
|
28 | 28 | #**************************************************************************** |
|
29 | 29 | # Modules and globals |
|
30 | 30 | |
|
31 | 31 | from __future__ import generators # for 2.2 backwards-compatibility |
|
32 | 32 | |
|
33 | 33 | from IPython import Release |
|
34 | 34 | __author__ = '%s <%s>\n%s <%s>' % \ |
|
35 | 35 | ( Release.authors['Janko'] + Release.authors['Fernando'] ) |
|
36 | 36 | __license__ = Release.license |
|
37 | 37 | __version__ = Release.version |
|
38 | 38 | |
|
39 | 39 | # Python standard modules |
|
40 | 40 | import __main__ |
|
41 | 41 | import __builtin__ |
|
42 | 42 | import StringIO |
|
43 | 43 | import bdb |
|
44 | 44 | import cPickle as pickle |
|
45 | 45 | import codeop |
|
46 | 46 | import exceptions |
|
47 | 47 | import glob |
|
48 | 48 | import inspect |
|
49 | 49 | import keyword |
|
50 | 50 | import new |
|
51 | 51 | import os |
|
52 | 52 | import pdb |
|
53 | 53 | import pydoc |
|
54 | 54 | import re |
|
55 | 55 | import shutil |
|
56 | 56 | import string |
|
57 | 57 | import sys |
|
58 | 58 | import traceback |
|
59 | 59 | import types |
|
60 | 60 | |
|
61 | 61 | from pprint import pprint, pformat |
|
62 | 62 | |
|
63 | 63 | # IPython's own modules |
|
64 | 64 | import IPython |
|
65 | 65 | from IPython import OInspect,PyColorize,ultraTB |
|
66 | 66 | from IPython.ColorANSI import ColorScheme,ColorSchemeTable # too long names |
|
67 | 67 | from IPython.FakeModule import FakeModule |
|
68 | 68 | from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns |
|
69 | 69 | from IPython.Logger import Logger |
|
70 | 70 | from IPython.Magic import Magic,magic2python |
|
71 | 71 | from IPython.Struct import Struct |
|
72 | 72 | from IPython.background_jobs import BackgroundJobManager |
|
73 | 73 | from IPython.usage import cmd_line_usage,interactive_usage |
|
74 | 74 | from IPython.genutils import * |
|
75 | 75 | |
|
76 | 76 | # store the builtin raw_input globally, and use this always, in case user code |
|
77 | 77 | # overwrites it (like wx.py.PyShell does) |
|
78 | 78 | raw_input_original = raw_input |
|
79 | 79 | |
|
80 | 80 | #**************************************************************************** |
|
81 | 81 | # Some utility function definitions |
|
82 | 82 | |
|
83 | 83 | # This can be replaced with an isspace() call once we drop 2.2 compatibility |
|
84 | 84 | _isspace_match = re.compile(r'^\s+$').match |
|
85 | 85 | def isspace(s): |
|
86 | 86 | return bool(_isspace_match(s)) |
|
87 | 87 | |
|
88 | 88 | def esc_quotes(strng): |
|
89 | 89 | """Return the input string with single and double quotes escaped out""" |
|
90 | 90 | |
|
91 | 91 | return strng.replace('"','\\"').replace("'","\\'") |
|
92 | 92 | |
|
93 | 93 | def import_fail_info(mod_name,fns=None): |
|
94 | 94 | """Inform load failure for a module.""" |
|
95 | 95 | |
|
96 | 96 | if fns == None: |
|
97 | 97 | warn("Loading of %s failed.\n" % (mod_name,)) |
|
98 | 98 | else: |
|
99 | 99 | warn("Loading of %s from %s failed.\n" % (fns,mod_name)) |
|
100 | 100 | |
|
101 | 101 | def qw_lol(indata): |
|
102 | 102 | """qw_lol('a b') -> [['a','b']], |
|
103 | 103 | otherwise it's just a call to qw(). |
|
104 | 104 | |
|
105 | 105 | We need this to make sure the modules_some keys *always* end up as a |
|
106 | 106 | list of lists.""" |
|
107 | 107 | |
|
108 | 108 | if type(indata) in StringTypes: |
|
109 | 109 | return [qw(indata)] |
|
110 | 110 | else: |
|
111 | 111 | return qw(indata) |
|
112 | 112 | |
|
113 | 113 | def ipmagic(arg_s): |
|
114 | 114 | """Call a magic function by name. |
|
115 | 115 | |
|
116 | 116 | Input: a string containing the name of the magic function to call and any |
|
117 | 117 | additional arguments to be passed to the magic. |
|
118 | 118 | |
|
119 | 119 | ipmagic('name -opt foo bar') is equivalent to typing at the ipython |
|
120 | 120 | prompt: |
|
121 | 121 | |
|
122 | 122 | In[1]: %name -opt foo bar |
|
123 | 123 | |
|
124 | 124 | To call a magic without arguments, simply use ipmagic('name'). |
|
125 | 125 | |
|
126 | 126 | This provides a proper Python function to call IPython's magics in any |
|
127 | 127 | valid Python code you can type at the interpreter, including loops and |
|
128 | 128 | compound statements. It is added by IPython to the Python builtin |
|
129 | 129 | namespace upon initialization.""" |
|
130 | 130 | |
|
131 | 131 | args = arg_s.split(' ',1) |
|
132 | 132 | magic_name = args[0] |
|
133 | 133 | if magic_name.startswith(__IPYTHON__.ESC_MAGIC): |
|
134 | 134 | magic_name = magic_name[1:] |
|
135 | 135 | try: |
|
136 | 136 | magic_args = args[1] |
|
137 | 137 | except IndexError: |
|
138 | 138 | magic_args = '' |
|
139 | 139 | fn = getattr(__IPYTHON__,'magic_'+magic_name,None) |
|
140 | 140 | if fn is None: |
|
141 | 141 | error("Magic function `%s` not found." % magic_name) |
|
142 | 142 | else: |
|
143 | 143 | magic_args = __IPYTHON__.var_expand(magic_args) |
|
144 | 144 | return fn(magic_args) |
|
145 | 145 | |
|
146 | 146 | def ipalias(arg_s): |
|
147 | 147 | """Call an alias by name. |
|
148 | 148 | |
|
149 | 149 | Input: a string containing the name of the alias to call and any |
|
150 | 150 | additional arguments to be passed to the magic. |
|
151 | 151 | |
|
152 | 152 | ipalias('name -opt foo bar') is equivalent to typing at the ipython |
|
153 | 153 | prompt: |
|
154 | 154 | |
|
155 | 155 | In[1]: name -opt foo bar |
|
156 | 156 | |
|
157 | 157 | To call an alias without arguments, simply use ipalias('name'). |
|
158 | 158 | |
|
159 | 159 | This provides a proper Python function to call IPython's aliases in any |
|
160 | 160 | valid Python code you can type at the interpreter, including loops and |
|
161 | 161 | compound statements. It is added by IPython to the Python builtin |
|
162 | 162 | namespace upon initialization.""" |
|
163 | 163 | |
|
164 | 164 | args = arg_s.split(' ',1) |
|
165 | 165 | alias_name = args[0] |
|
166 | 166 | try: |
|
167 | 167 | alias_args = args[1] |
|
168 | 168 | except IndexError: |
|
169 | 169 | alias_args = '' |
|
170 | 170 | if alias_name in __IPYTHON__.alias_table: |
|
171 | 171 | __IPYTHON__.call_alias(alias_name,alias_args) |
|
172 | 172 | else: |
|
173 | 173 | error("Alias `%s` not found." % alias_name) |
|
174 | 174 | |
|
175 | 175 | def softspace(file, newvalue): |
|
176 | 176 | """Copied from code.py, to remove the dependency""" |
|
177 | 177 | oldvalue = 0 |
|
178 | 178 | try: |
|
179 | 179 | oldvalue = file.softspace |
|
180 | 180 | except AttributeError: |
|
181 | 181 | pass |
|
182 | 182 | try: |
|
183 | 183 | file.softspace = newvalue |
|
184 | 184 | except (AttributeError, TypeError): |
|
185 | 185 | # "attribute-less object" or "read-only attributes" |
|
186 | 186 | pass |
|
187 | 187 | return oldvalue |
|
188 | 188 | |
|
189 | 189 | |
|
190 | 190 | #**************************************************************************** |
|
191 | 191 | # Local use exceptions |
|
192 | 192 | class SpaceInInput(exceptions.Exception): pass |
|
193 | 193 | |
|
194 | class IPythonExit(exceptions.Exception): pass | |
|
195 | ||
|
196 | 194 | #**************************************************************************** |
|
197 | 195 | # Local use classes |
|
198 | 196 | class Bunch: pass |
|
199 | 197 | |
|
200 | 198 | class InputList(list): |
|
201 | 199 | """Class to store user input. |
|
202 | 200 | |
|
203 | 201 | It's basically a list, but slices return a string instead of a list, thus |
|
204 | 202 | allowing things like (assuming 'In' is an instance): |
|
205 | 203 | |
|
206 | 204 | exec In[4:7] |
|
207 | 205 | |
|
208 | 206 | or |
|
209 | 207 | |
|
210 | 208 | exec In[5:9] + In[14] + In[21:25]""" |
|
211 | 209 | |
|
212 | 210 | def __getslice__(self,i,j): |
|
213 | 211 | return ''.join(list.__getslice__(self,i,j)) |
|
214 | 212 | |
|
215 | 213 | class SyntaxTB(ultraTB.ListTB): |
|
216 | 214 | """Extension which holds some state: the last exception value""" |
|
217 | 215 | |
|
218 | 216 | def __init__(self,color_scheme = 'NoColor'): |
|
219 | 217 | ultraTB.ListTB.__init__(self,color_scheme) |
|
220 | 218 | self.last_syntax_error = None |
|
221 | 219 | |
|
222 | 220 | def __call__(self, etype, value, elist): |
|
223 | 221 | self.last_syntax_error = value |
|
224 | 222 | ultraTB.ListTB.__call__(self,etype,value,elist) |
|
225 | 223 | |
|
226 | 224 | def clear_err_state(self): |
|
227 | 225 | """Return the current error state and clear it""" |
|
228 | 226 | e = self.last_syntax_error |
|
229 | 227 | self.last_syntax_error = None |
|
230 | 228 | return e |
|
231 | 229 | |
|
232 | 230 | #**************************************************************************** |
|
233 | 231 | # Main IPython class |
|
234 | 232 | class InteractiveShell(Logger, Magic): |
|
235 | 233 | """An enhanced console for Python.""" |
|
236 | 234 | |
|
237 | 235 | def __init__(self,name,usage=None,rc=Struct(opts=None,args=None), |
|
238 | 236 | user_ns = None,user_global_ns=None,banner2='', |
|
239 | 237 | custom_exceptions=((),None),embedded=False): |
|
240 | 238 | |
|
241 | 239 | # Put a reference to self in builtins so that any form of embedded or |
|
242 | 240 | # imported code can test for being inside IPython. |
|
243 | 241 | __builtin__.__IPYTHON__ = self |
|
244 | 242 | |
|
245 | 243 | # And load into builtins ipmagic/ipalias as well |
|
246 | 244 | __builtin__.ipmagic = ipmagic |
|
247 | 245 | __builtin__.ipalias = ipalias |
|
248 | 246 | |
|
249 | 247 | # Add to __builtin__ other parts of IPython's public API |
|
250 | 248 | __builtin__.ip_set_hook = self.set_hook |
|
251 | 249 | |
|
252 | 250 | # Keep in the builtins a flag for when IPython is active. We set it |
|
253 | 251 | # with setdefault so that multiple nested IPythons don't clobber one |
|
254 | 252 | # another. Each will increase its value by one upon being activated, |
|
255 | 253 | # which also gives us a way to determine the nesting level. |
|
256 | 254 | __builtin__.__dict__.setdefault('__IPYTHON__active',0) |
|
257 | 255 | |
|
258 | 256 | # Do the intuitively correct thing for quit/exit: we remove the |
|
259 | 257 | # builtins if they exist, and our own prefilter routine will handle |
|
260 | 258 | # these special cases |
|
261 | 259 | try: |
|
262 | 260 | del __builtin__.exit, __builtin__.quit |
|
263 | 261 | except AttributeError: |
|
264 | 262 | pass |
|
265 | 263 | |
|
266 | 264 | # We need to know whether the instance is meant for embedding, since |
|
267 | 265 | # global/local namespaces need to be handled differently in that case |
|
268 | 266 | self.embedded = embedded |
|
269 | 267 | |
|
270 | 268 | # command compiler |
|
271 | 269 | self.compile = codeop.CommandCompiler() |
|
272 | 270 | |
|
273 | 271 | # User input buffer |
|
274 | 272 | self.buffer = [] |
|
275 | 273 | |
|
276 | 274 | # Default name given in compilation of code |
|
277 | 275 | self.filename = '<ipython console>' |
|
278 | 276 | |
|
279 | 277 | # Create the namespace where the user will operate. user_ns is |
|
280 | 278 | # normally the only one used, and it is passed to the exec calls as |
|
281 | 279 | # the locals argument. But we do carry a user_global_ns namespace |
|
282 | 280 | # given as the exec 'globals' argument, This is useful in embedding |
|
283 | 281 | # situations where the ipython shell opens in a context where the |
|
284 | 282 | # distinction between locals and globals is meaningful. |
|
285 | 283 | |
|
286 | 284 | # FIXME. For some strange reason, __builtins__ is showing up at user |
|
287 | 285 | # level as a dict instead of a module. This is a manual fix, but I |
|
288 | 286 | # should really track down where the problem is coming from. Alex |
|
289 | 287 | # Schmolck reported this problem first. |
|
290 | 288 | |
|
291 | 289 | # A useful post by Alex Martelli on this topic: |
|
292 | 290 | # Re: inconsistent value from __builtins__ |
|
293 | 291 | # Von: Alex Martelli <aleaxit@yahoo.com> |
|
294 | 292 | # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends |
|
295 | 293 | # Gruppen: comp.lang.python |
|
296 | 294 | # Referenzen: 1 |
|
297 | 295 | |
|
298 | 296 | # Michael Hohn <hohn@hooknose.lbl.gov> wrote: |
|
299 | 297 | # > >>> print type(builtin_check.get_global_binding('__builtins__')) |
|
300 | 298 | # > <type 'dict'> |
|
301 | 299 | # > >>> print type(__builtins__) |
|
302 | 300 | # > <type 'module'> |
|
303 | 301 | # > Is this difference in return value intentional? |
|
304 | 302 | |
|
305 | 303 | # Well, it's documented that '__builtins__' can be either a dictionary |
|
306 | 304 | # or a module, and it's been that way for a long time. Whether it's |
|
307 | 305 | # intentional (or sensible), I don't know. In any case, the idea is |
|
308 | 306 | # that if you need to access the built-in namespace directly, you |
|
309 | 307 | # should start with "import __builtin__" (note, no 's') which will |
|
310 | 308 | # definitely give you a module. Yeah, it's somewhat confusing:-(. |
|
311 | 309 | |
|
312 | 310 | if user_ns is None: |
|
313 | 311 | # Set __name__ to __main__ to better match the behavior of the |
|
314 | 312 | # normal interpreter. |
|
315 | 313 | user_ns = {'__name__' :'__main__', |
|
316 | 314 | '__builtins__' : __builtin__, |
|
317 | 315 | } |
|
318 | 316 | |
|
319 | 317 | if user_global_ns is None: |
|
320 | 318 | user_global_ns = {} |
|
321 | 319 | |
|
322 | 320 | # Assign namespaces |
|
323 | 321 | # This is the namespace where all normal user variables live |
|
324 | 322 | self.user_ns = user_ns |
|
325 | 323 | # Embedded instances require a separate namespace for globals. |
|
326 | 324 | # Normally this one is unused by non-embedded instances. |
|
327 | 325 | self.user_global_ns = user_global_ns |
|
328 | 326 | # A namespace to keep track of internal data structures to prevent |
|
329 | 327 | # them from cluttering user-visible stuff. Will be updated later |
|
330 | 328 | self.internal_ns = {} |
|
331 | 329 | |
|
332 | 330 | # Namespace of system aliases. Each entry in the alias |
|
333 | 331 | # table must be a 2-tuple of the form (N,name), where N is the number |
|
334 | 332 | # of positional arguments of the alias. |
|
335 | 333 | self.alias_table = {} |
|
336 | 334 | |
|
337 | 335 | # A table holding all the namespaces IPython deals with, so that |
|
338 | 336 | # introspection facilities can search easily. |
|
339 | 337 | self.ns_table = {'user':user_ns, |
|
340 | 338 | 'user_global':user_global_ns, |
|
341 | 339 | 'alias':self.alias_table, |
|
342 | 340 | 'internal':self.internal_ns, |
|
343 | 341 | 'builtin':__builtin__.__dict__ |
|
344 | 342 | } |
|
345 | 343 | |
|
346 | 344 | # The user namespace MUST have a pointer to the shell itself. |
|
347 | 345 | self.user_ns[name] = self |
|
348 | 346 | |
|
349 | 347 | # We need to insert into sys.modules something that looks like a |
|
350 | 348 | # module but which accesses the IPython namespace, for shelve and |
|
351 | 349 | # pickle to work interactively. Normally they rely on getting |
|
352 | 350 | # everything out of __main__, but for embedding purposes each IPython |
|
353 | 351 | # instance has its own private namespace, so we can't go shoving |
|
354 | 352 | # everything into __main__. |
|
355 | 353 | |
|
356 | 354 | # note, however, that we should only do this for non-embedded |
|
357 | 355 | # ipythons, which really mimic the __main__.__dict__ with their own |
|
358 | 356 | # namespace. Embedded instances, on the other hand, should not do |
|
359 | 357 | # this because they need to manage the user local/global namespaces |
|
360 | 358 | # only, but they live within a 'normal' __main__ (meaning, they |
|
361 | 359 | # shouldn't overtake the execution environment of the script they're |
|
362 | 360 | # embedded in). |
|
363 | 361 | |
|
364 | 362 | if not embedded: |
|
365 | 363 | try: |
|
366 | 364 | main_name = self.user_ns['__name__'] |
|
367 | 365 | except KeyError: |
|
368 | 366 | raise KeyError,'user_ns dictionary MUST have a "__name__" key' |
|
369 | 367 | else: |
|
370 | 368 | #print "pickle hack in place" # dbg |
|
371 | 369 | sys.modules[main_name] = FakeModule(self.user_ns) |
|
372 | 370 | |
|
373 | 371 | # List of input with multi-line handling. |
|
374 | 372 | # Fill its zero entry, user counter starts at 1 |
|
375 | 373 | self.input_hist = InputList(['\n']) |
|
376 | 374 | |
|
377 | 375 | # list of visited directories |
|
378 | 376 | try: |
|
379 | 377 | self.dir_hist = [os.getcwd()] |
|
380 | 378 | except IOError, e: |
|
381 | 379 | self.dir_hist = [] |
|
382 | 380 | |
|
383 | 381 | # dict of output history |
|
384 | 382 | self.output_hist = {} |
|
385 | 383 | |
|
386 | 384 | # dict of things NOT to alias (keywords, builtins and some magics) |
|
387 | 385 | no_alias = {} |
|
388 | 386 | no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias'] |
|
389 | 387 | for key in keyword.kwlist + no_alias_magics: |
|
390 | 388 | no_alias[key] = 1 |
|
391 | 389 | no_alias.update(__builtin__.__dict__) |
|
392 | 390 | self.no_alias = no_alias |
|
393 | 391 | |
|
394 | 392 | # make global variables for user access to these |
|
395 | 393 | self.user_ns['_ih'] = self.input_hist |
|
396 | 394 | self.user_ns['_oh'] = self.output_hist |
|
397 | 395 | self.user_ns['_dh'] = self.dir_hist |
|
398 | 396 | |
|
399 | 397 | # user aliases to input and output histories |
|
400 | 398 | self.user_ns['In'] = self.input_hist |
|
401 | 399 | self.user_ns['Out'] = self.output_hist |
|
402 | 400 | |
|
403 | 401 | # Store the actual shell's name |
|
404 | 402 | self.name = name |
|
405 | 403 | |
|
406 | 404 | # Object variable to store code object waiting execution. This is |
|
407 | 405 | # used mainly by the multithreaded shells, but it can come in handy in |
|
408 | 406 | # other situations. No need to use a Queue here, since it's a single |
|
409 | 407 | # item which gets cleared once run. |
|
410 | 408 | self.code_to_run = None |
|
411 | 409 | |
|
412 | 410 | # Job manager (for jobs run as background threads) |
|
413 | 411 | self.jobs = BackgroundJobManager() |
|
414 | 412 | # Put the job manager into builtins so it's always there. |
|
415 | 413 | __builtin__.jobs = self.jobs |
|
416 | 414 | |
|
417 | 415 | # escapes for automatic behavior on the command line |
|
418 | 416 | self.ESC_SHELL = '!' |
|
419 | 417 | self.ESC_HELP = '?' |
|
420 | 418 | self.ESC_MAGIC = '%' |
|
421 | 419 | self.ESC_QUOTE = ',' |
|
422 | 420 | self.ESC_QUOTE2 = ';' |
|
423 | 421 | self.ESC_PAREN = '/' |
|
424 | 422 | |
|
425 | 423 | # And their associated handlers |
|
426 | 424 | self.esc_handlers = {self.ESC_PAREN:self.handle_auto, |
|
427 | 425 | self.ESC_QUOTE:self.handle_auto, |
|
428 | 426 | self.ESC_QUOTE2:self.handle_auto, |
|
429 | 427 | self.ESC_MAGIC:self.handle_magic, |
|
430 | 428 | self.ESC_HELP:self.handle_help, |
|
431 | 429 | self.ESC_SHELL:self.handle_shell_escape, |
|
432 | 430 | } |
|
433 | 431 | |
|
434 | 432 | # class initializations |
|
435 | 433 | Logger.__init__(self,log_ns = self.user_ns) |
|
436 | 434 | Magic.__init__(self,self) |
|
437 | 435 | |
|
438 | 436 | # an ugly hack to get a pointer to the shell, so I can start writing |
|
439 | 437 | # magic code via this pointer instead of the current mixin salad. |
|
440 | 438 | Magic.set_shell(self,self) |
|
441 | 439 | |
|
442 | 440 | # Python source parser/formatter for syntax highlighting |
|
443 | 441 | pyformat = PyColorize.Parser().format |
|
444 | 442 | self.pycolorize = lambda src: pyformat(src,'str',self.rc['colors']) |
|
445 | 443 | |
|
446 | 444 | # hooks holds pointers used for user-side customizations |
|
447 | 445 | self.hooks = Struct() |
|
448 | 446 | |
|
449 | 447 | # Set all default hooks, defined in the IPython.hooks module. |
|
450 | 448 | hooks = IPython.hooks |
|
451 | 449 | for hook_name in hooks.__all__: |
|
452 | 450 | self.set_hook(hook_name,getattr(hooks,hook_name)) |
|
453 | 451 | |
|
454 | 452 | # Flag to mark unconditional exit |
|
455 | 453 | self.exit_now = False |
|
456 | 454 | |
|
457 | 455 | self.usage_min = """\ |
|
458 | 456 | An enhanced console for Python. |
|
459 | 457 | Some of its features are: |
|
460 | 458 | - Readline support if the readline library is present. |
|
461 | 459 | - Tab completion in the local namespace. |
|
462 | 460 | - Logging of input, see command-line options. |
|
463 | 461 | - System shell escape via ! , eg !ls. |
|
464 | 462 | - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.) |
|
465 | 463 | - Keeps track of locally defined variables via %who, %whos. |
|
466 | 464 | - Show object information with a ? eg ?x or x? (use ?? for more info). |
|
467 | 465 | """ |
|
468 | 466 | if usage: self.usage = usage |
|
469 | 467 | else: self.usage = self.usage_min |
|
470 | 468 | |
|
471 | 469 | # Storage |
|
472 | 470 | self.rc = rc # This will hold all configuration information |
|
473 | 471 | self.inputcache = [] |
|
474 | 472 | self._boundcache = [] |
|
475 | 473 | self.pager = 'less' |
|
476 | 474 | # temporary files used for various purposes. Deleted at exit. |
|
477 | 475 | self.tempfiles = [] |
|
478 | 476 | |
|
479 | 477 | # Keep track of readline usage (later set by init_readline) |
|
480 | 478 | self.has_readline = False |
|
481 | 479 | |
|
482 | 480 | # for pushd/popd management |
|
483 | 481 | try: |
|
484 | 482 | self.home_dir = get_home_dir() |
|
485 | 483 | except HomeDirError,msg: |
|
486 | 484 | fatal(msg) |
|
487 | 485 | |
|
488 | 486 | self.dir_stack = [os.getcwd().replace(self.home_dir,'~')] |
|
489 | 487 | |
|
490 | 488 | # Functions to call the underlying shell. |
|
491 | 489 | |
|
492 | 490 | # utility to expand user variables via Itpl |
|
493 | 491 | self.var_expand = lambda cmd: str(ItplNS(cmd.replace('#','\#'), |
|
494 | 492 | self.user_ns)) |
|
495 | 493 | # The first is similar to os.system, but it doesn't return a value, |
|
496 | 494 | # and it allows interpolation of variables in the user's namespace. |
|
497 | 495 | self.system = lambda cmd: shell(self.var_expand(cmd), |
|
498 | 496 | header='IPython system call: ', |
|
499 | 497 | verbose=self.rc.system_verbose) |
|
500 | 498 | # These are for getoutput and getoutputerror: |
|
501 | 499 | self.getoutput = lambda cmd: \ |
|
502 | 500 | getoutput(self.var_expand(cmd), |
|
503 | 501 | header='IPython system call: ', |
|
504 | 502 | verbose=self.rc.system_verbose) |
|
505 | 503 | self.getoutputerror = lambda cmd: \ |
|
506 | 504 | getoutputerror(str(ItplNS(cmd.replace('#','\#'), |
|
507 | 505 | self.user_ns)), |
|
508 | 506 | header='IPython system call: ', |
|
509 | 507 | verbose=self.rc.system_verbose) |
|
510 | 508 | |
|
511 | 509 | # RegExp for splitting line contents into pre-char//first |
|
512 | 510 | # word-method//rest. For clarity, each group in on one line. |
|
513 | 511 | |
|
514 | 512 | # WARNING: update the regexp if the above escapes are changed, as they |
|
515 | 513 | # are hardwired in. |
|
516 | 514 | |
|
517 | 515 | # Don't get carried away with trying to make the autocalling catch too |
|
518 | 516 | # much: it's better to be conservative rather than to trigger hidden |
|
519 | 517 | # evals() somewhere and end up causing side effects. |
|
520 | 518 | |
|
521 | 519 | self.line_split = re.compile(r'^([\s*,;/])' |
|
522 | 520 | r'([\?\w\.]+\w*\s*)' |
|
523 | 521 | r'(\(?.*$)') |
|
524 | 522 | |
|
525 | 523 | # Original re, keep around for a while in case changes break something |
|
526 | 524 | #self.line_split = re.compile(r'(^[\s*!\?%,/]?)' |
|
527 | 525 | # r'(\s*[\?\w\.]+\w*\s*)' |
|
528 | 526 | # r'(\(?.*$)') |
|
529 | 527 | |
|
530 | 528 | # RegExp to identify potential function names |
|
531 | 529 | self.re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$') |
|
532 | 530 | # RegExp to exclude strings with this start from autocalling |
|
533 | 531 | self.re_exclude_auto = re.compile('^[!=()<>,\*/\+-]|^is ') |
|
534 | 532 | |
|
535 | 533 | # try to catch also methods for stuff in lists/tuples/dicts: off |
|
536 | 534 | # (experimental). For this to work, the line_split regexp would need |
|
537 | 535 | # to be modified so it wouldn't break things at '['. That line is |
|
538 | 536 | # nasty enough that I shouldn't change it until I can test it _well_. |
|
539 | 537 | #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$') |
|
540 | 538 | |
|
541 | 539 | # keep track of where we started running (mainly for crash post-mortem) |
|
542 | 540 | self.starting_dir = os.getcwd() |
|
543 | 541 | |
|
544 | 542 | # Attributes for Logger mixin class, make defaults here |
|
545 | 543 | self._dolog = False |
|
546 | 544 | self.LOG = '' |
|
547 | 545 | self.LOGDEF = '.InteractiveShell.log' |
|
548 | 546 | self.LOGMODE = 'over' |
|
549 | 547 | self.LOGHEAD = Itpl( |
|
550 | 548 | """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE *** |
|
551 | 549 | #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW |
|
552 | 550 | #log# opts = $self.rc.opts |
|
553 | 551 | #log# args = $self.rc.args |
|
554 | 552 | #log# It is safe to make manual edits below here. |
|
555 | 553 | #log#----------------------------------------------------------------------- |
|
556 | 554 | """) |
|
557 | 555 | # Various switches which can be set |
|
558 | 556 | self.CACHELENGTH = 5000 # this is cheap, it's just text |
|
559 | 557 | self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__ |
|
560 | 558 | self.banner2 = banner2 |
|
561 | 559 | |
|
562 | 560 | # TraceBack handlers: |
|
563 | 561 | # Need two, one for syntax errors and one for other exceptions. |
|
564 | 562 | self.SyntaxTB = SyntaxTB(color_scheme='NoColor') |
|
565 | 563 | # The interactive one is initialized with an offset, meaning we always |
|
566 | 564 | # want to remove the topmost item in the traceback, which is our own |
|
567 | 565 | # internal code. Valid modes: ['Plain','Context','Verbose'] |
|
568 | 566 | self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain', |
|
569 | 567 | color_scheme='NoColor', |
|
570 | 568 | tb_offset = 1) |
|
571 | 569 | # and add any custom exception handlers the user may have specified |
|
572 | 570 | self.set_custom_exc(*custom_exceptions) |
|
573 | 571 | |
|
574 | 572 | # Object inspector |
|
575 | 573 | self.inspector = OInspect.Inspector(OInspect.InspectColors, |
|
576 | 574 | PyColorize.ANSICodeColors, |
|
577 | 575 | 'NoColor') |
|
578 | 576 | # indentation management |
|
579 | 577 | self.autoindent = False |
|
580 | 578 | self.indent_current_nsp = 0 |
|
581 | 579 | self.indent_current = '' # actual indent string |
|
582 | 580 | |
|
583 | 581 | # Make some aliases automatically |
|
584 | 582 | # Prepare list of shell aliases to auto-define |
|
585 | 583 | if os.name == 'posix': |
|
586 | 584 | auto_alias = ('mkdir mkdir', 'rmdir rmdir', |
|
587 | 585 | 'mv mv -i','rm rm -i','cp cp -i', |
|
588 | 586 | 'cat cat','less less','clear clear', |
|
589 | 587 | # a better ls |
|
590 | 588 | 'ls ls -F', |
|
591 | 589 | # long ls |
|
592 | 590 | 'll ls -lF', |
|
593 | 591 | # color ls |
|
594 | 592 | 'lc ls -F -o --color', |
|
595 | 593 | # ls normal files only |
|
596 | 594 | 'lf ls -F -o --color %l | grep ^-', |
|
597 | 595 | # ls symbolic links |
|
598 | 596 | 'lk ls -F -o --color %l | grep ^l', |
|
599 | 597 | # directories or links to directories, |
|
600 | 598 | 'ldir ls -F -o --color %l | grep /$', |
|
601 | 599 | # things which are executable |
|
602 | 600 | 'lx ls -F -o --color %l | grep ^-..x', |
|
603 | 601 | ) |
|
604 | 602 | elif os.name in ['nt','dos']: |
|
605 | 603 | auto_alias = ('dir dir /on', 'ls dir /on', |
|
606 | 604 | 'ddir dir /ad /on', 'ldir dir /ad /on', |
|
607 | 605 | 'mkdir mkdir','rmdir rmdir','echo echo', |
|
608 | 606 | 'ren ren','cls cls','copy copy') |
|
609 | 607 | else: |
|
610 | 608 | auto_alias = () |
|
611 | 609 | self.auto_alias = map(lambda s:s.split(None,1),auto_alias) |
|
612 | 610 | # Call the actual (public) initializer |
|
613 | 611 | self.init_auto_alias() |
|
614 | 612 | # end __init__ |
|
615 | 613 | |
|
616 | 614 | def set_hook(self,name,hook): |
|
617 | 615 | """set_hook(name,hook) -> sets an internal IPython hook. |
|
618 | 616 | |
|
619 | 617 | IPython exposes some of its internal API as user-modifiable hooks. By |
|
620 | 618 | resetting one of these hooks, you can modify IPython's behavior to |
|
621 | 619 | call at runtime your own routines.""" |
|
622 | 620 | |
|
623 | 621 | # At some point in the future, this should validate the hook before it |
|
624 | 622 | # accepts it. Probably at least check that the hook takes the number |
|
625 | 623 | # of args it's supposed to. |
|
626 | 624 | setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__)) |
|
627 | 625 | |
|
628 | 626 | def set_custom_exc(self,exc_tuple,handler): |
|
629 | 627 | """set_custom_exc(exc_tuple,handler) |
|
630 | 628 | |
|
631 | 629 | Set a custom exception handler, which will be called if any of the |
|
632 | 630 | exceptions in exc_tuple occur in the mainloop (specifically, in the |
|
633 | 631 | runcode() method. |
|
634 | 632 | |
|
635 | 633 | Inputs: |
|
636 | 634 | |
|
637 | 635 | - exc_tuple: a *tuple* of valid exceptions to call the defined |
|
638 | 636 | handler for. It is very important that you use a tuple, and NOT A |
|
639 | 637 | LIST here, because of the way Python's except statement works. If |
|
640 | 638 | you only want to trap a single exception, use a singleton tuple: |
|
641 | 639 | |
|
642 | 640 | exc_tuple == (MyCustomException,) |
|
643 | 641 | |
|
644 | 642 | - handler: this must be defined as a function with the following |
|
645 | 643 | basic interface: def my_handler(self,etype,value,tb). |
|
646 | 644 | |
|
647 | 645 | This will be made into an instance method (via new.instancemethod) |
|
648 | 646 | of IPython itself, and it will be called if any of the exceptions |
|
649 | 647 | listed in the exc_tuple are caught. If the handler is None, an |
|
650 | 648 | internal basic one is used, which just prints basic info. |
|
651 | 649 | |
|
652 | 650 | WARNING: by putting in your own exception handler into IPython's main |
|
653 | 651 | execution loop, you run a very good chance of nasty crashes. This |
|
654 | 652 | facility should only be used if you really know what you are doing.""" |
|
655 | 653 | |
|
656 | 654 | assert type(exc_tuple)==type(()) , \ |
|
657 | 655 | "The custom exceptions must be given AS A TUPLE." |
|
658 | 656 | |
|
659 | 657 | def dummy_handler(self,etype,value,tb): |
|
660 | 658 | print '*** Simple custom exception handler ***' |
|
661 | 659 | print 'Exception type :',etype |
|
662 | 660 | print 'Exception value:',value |
|
663 | 661 | print 'Traceback :',tb |
|
664 | 662 | print 'Source code :','\n'.join(self.buffer) |
|
665 | 663 | |
|
666 | 664 | if handler is None: handler = dummy_handler |
|
667 | 665 | |
|
668 | 666 | self.CustomTB = new.instancemethod(handler,self,self.__class__) |
|
669 | 667 | self.custom_exceptions = exc_tuple |
|
670 | 668 | |
|
671 | 669 | def set_custom_completer(self,completer,pos=0): |
|
672 | 670 | """set_custom_completer(completer,pos=0) |
|
673 | 671 | |
|
674 | 672 | Adds a new custom completer function. |
|
675 | 673 | |
|
676 | 674 | The position argument (defaults to 0) is the index in the completers |
|
677 | 675 | list where you want the completer to be inserted.""" |
|
678 | 676 | |
|
679 | 677 | newcomp = new.instancemethod(completer,self.Completer, |
|
680 | 678 | self.Completer.__class__) |
|
681 | 679 | self.Completer.matchers.insert(pos,newcomp) |
|
682 | 680 | |
|
683 | 681 | def complete(self,text): |
|
684 | 682 | """Return a sorted list of all possible completions on text. |
|
685 | 683 | |
|
686 | 684 | Inputs: |
|
687 | 685 | |
|
688 | 686 | - text: a string of text to be completed on. |
|
689 | 687 | |
|
690 | 688 | This is a wrapper around the completion mechanism, similar to what |
|
691 | 689 | readline does at the command line when the TAB key is hit. By |
|
692 | 690 | exposing it as a method, it can be used by other non-readline |
|
693 | 691 | environments (such as GUIs) for text completion. |
|
694 | 692 | |
|
695 | 693 | Simple usage example: |
|
696 | 694 | |
|
697 | 695 | In [1]: x = 'hello' |
|
698 | 696 | |
|
699 | 697 | In [2]: __IP.complete('x.l') |
|
700 | 698 | Out[2]: ['x.ljust', 'x.lower', 'x.lstrip']""" |
|
701 | 699 | |
|
702 | 700 | complete = self.Completer.complete |
|
703 | 701 | state = 0 |
|
704 | 702 | # use a dict so we get unique keys, since ipyhton's multiple |
|
705 | 703 | # completers can return duplicates. |
|
706 | 704 | comps = {} |
|
707 | 705 | while True: |
|
708 | 706 | newcomp = complete(text,state) |
|
709 | 707 | if newcomp is None: |
|
710 | 708 | break |
|
711 | 709 | comps[newcomp] = 1 |
|
712 | 710 | state += 1 |
|
713 | 711 | outcomps = comps.keys() |
|
714 | 712 | outcomps.sort() |
|
715 | 713 | return outcomps |
|
716 | 714 | |
|
717 | 715 | def set_completer_frame(self, frame): |
|
718 | 716 | if frame: |
|
719 | 717 | self.Completer.namespace = frame.f_locals |
|
720 | 718 | self.Completer.global_namespace = frame.f_globals |
|
721 | 719 | else: |
|
722 | 720 | self.Completer.namespace = self.user_ns |
|
723 | 721 | self.Completer.global_namespace = self.user_global_ns |
|
724 | 722 | |
|
725 | 723 | def post_config_initialization(self): |
|
726 | 724 | """Post configuration init method |
|
727 | 725 | |
|
728 | 726 | This is called after the configuration files have been processed to |
|
729 | 727 | 'finalize' the initialization.""" |
|
730 | 728 | |
|
731 | 729 | rc = self.rc |
|
732 | 730 | |
|
733 | 731 | # Load readline proper |
|
734 | 732 | if rc.readline: |
|
735 | 733 | self.init_readline() |
|
736 | 734 | |
|
737 | 735 | # Set user colors (don't do it in the constructor above so that it |
|
738 | 736 | # doesn't crash if colors option is invalid) |
|
739 | 737 | self.magic_colors(rc.colors) |
|
740 | 738 | |
|
741 | 739 | # Load user aliases |
|
742 | 740 | for alias in rc.alias: |
|
743 | 741 | self.magic_alias(alias) |
|
744 | 742 | |
|
745 | 743 | # dynamic data that survives through sessions |
|
746 | 744 | # XXX make the filename a config option? |
|
747 | 745 | persist_base = 'persist' |
|
748 | 746 | if rc.profile: |
|
749 | 747 | persist_base += '_%s' % rc.profile |
|
750 | 748 | self.persist_fname = os.path.join(rc.ipythondir,persist_base) |
|
751 | 749 | |
|
752 | 750 | try: |
|
753 | 751 | self.persist = pickle.load(file(self.persist_fname)) |
|
754 | 752 | except: |
|
755 | 753 | self.persist = {} |
|
756 | 754 | |
|
757 | 755 | def init_auto_alias(self): |
|
758 | 756 | """Define some aliases automatically. |
|
759 | 757 | |
|
760 | 758 | These are ALL parameter-less aliases""" |
|
761 | 759 | for alias,cmd in self.auto_alias: |
|
762 | 760 | self.alias_table[alias] = (0,cmd) |
|
763 | 761 | |
|
764 | 762 | def alias_table_validate(self,verbose=0): |
|
765 | 763 | """Update information about the alias table. |
|
766 | 764 | |
|
767 | 765 | In particular, make sure no Python keywords/builtins are in it.""" |
|
768 | 766 | |
|
769 | 767 | no_alias = self.no_alias |
|
770 | 768 | for k in self.alias_table.keys(): |
|
771 | 769 | if k in no_alias: |
|
772 | 770 | del self.alias_table[k] |
|
773 | 771 | if verbose: |
|
774 | 772 | print ("Deleting alias <%s>, it's a Python " |
|
775 | 773 | "keyword or builtin." % k) |
|
776 | 774 | |
|
777 | 775 | def set_autoindent(self,value=None): |
|
778 | 776 | """Set the autoindent flag, checking for readline support. |
|
779 | 777 | |
|
780 | 778 | If called with no arguments, it acts as a toggle.""" |
|
781 | 779 | |
|
782 | 780 | if not self.has_readline: |
|
783 | 781 | if os.name == 'posix': |
|
784 | 782 | warn("The auto-indent feature requires the readline library") |
|
785 | 783 | self.autoindent = 0 |
|
786 | 784 | return |
|
787 | 785 | if value is None: |
|
788 | 786 | self.autoindent = not self.autoindent |
|
789 | 787 | else: |
|
790 | 788 | self.autoindent = value |
|
791 | 789 | |
|
792 | 790 | def rc_set_toggle(self,rc_field,value=None): |
|
793 | 791 | """Set or toggle a field in IPython's rc config. structure. |
|
794 | 792 | |
|
795 | 793 | If called with no arguments, it acts as a toggle. |
|
796 | 794 | |
|
797 | 795 | If called with a non-existent field, the resulting AttributeError |
|
798 | 796 | exception will propagate out.""" |
|
799 | 797 | |
|
800 | 798 | rc_val = getattr(self.rc,rc_field) |
|
801 | 799 | if value is None: |
|
802 | 800 | value = not rc_val |
|
803 | 801 | setattr(self.rc,rc_field,value) |
|
804 | 802 | |
|
805 | 803 | def user_setup(self,ipythondir,rc_suffix,mode='install'): |
|
806 | 804 | """Install the user configuration directory. |
|
807 | 805 | |
|
808 | 806 | Can be called when running for the first time or to upgrade the user's |
|
809 | 807 | .ipython/ directory with the mode parameter. Valid modes are 'install' |
|
810 | 808 | and 'upgrade'.""" |
|
811 | 809 | |
|
812 | 810 | def wait(): |
|
813 | 811 | try: |
|
814 | 812 | raw_input("Please press <RETURN> to start IPython.") |
|
815 | 813 | except EOFError: |
|
816 | 814 | print >> Term.cout |
|
817 | 815 | print '*'*70 |
|
818 | 816 | |
|
819 | 817 | cwd = os.getcwd() # remember where we started |
|
820 | 818 | glb = glob.glob |
|
821 | 819 | print '*'*70 |
|
822 | 820 | if mode == 'install': |
|
823 | 821 | print \ |
|
824 | 822 | """Welcome to IPython. I will try to create a personal configuration directory |
|
825 | 823 | where you can customize many aspects of IPython's functionality in:\n""" |
|
826 | 824 | else: |
|
827 | 825 | print 'I am going to upgrade your configuration in:' |
|
828 | 826 | |
|
829 | 827 | print ipythondir |
|
830 | 828 | |
|
831 | 829 | rcdirend = os.path.join('IPython','UserConfig') |
|
832 | 830 | cfg = lambda d: os.path.join(d,rcdirend) |
|
833 | 831 | try: |
|
834 | 832 | rcdir = filter(os.path.isdir,map(cfg,sys.path))[0] |
|
835 | 833 | except IOError: |
|
836 | 834 | warning = """ |
|
837 | 835 | Installation error. IPython's directory was not found. |
|
838 | 836 | |
|
839 | 837 | Check the following: |
|
840 | 838 | |
|
841 | 839 | The ipython/IPython directory should be in a directory belonging to your |
|
842 | 840 | PYTHONPATH environment variable (that is, it should be in a directory |
|
843 | 841 | belonging to sys.path). You can copy it explicitly there or just link to it. |
|
844 | 842 | |
|
845 | 843 | IPython will proceed with builtin defaults. |
|
846 | 844 | """ |
|
847 | 845 | warn(warning) |
|
848 | 846 | wait() |
|
849 | 847 | return |
|
850 | 848 | |
|
851 | 849 | if mode == 'install': |
|
852 | 850 | try: |
|
853 | 851 | shutil.copytree(rcdir,ipythondir) |
|
854 | 852 | os.chdir(ipythondir) |
|
855 | 853 | rc_files = glb("ipythonrc*") |
|
856 | 854 | for rc_file in rc_files: |
|
857 | 855 | os.rename(rc_file,rc_file+rc_suffix) |
|
858 | 856 | except: |
|
859 | 857 | warning = """ |
|
860 | 858 | |
|
861 | 859 | There was a problem with the installation: |
|
862 | 860 | %s |
|
863 | 861 | Try to correct it or contact the developers if you think it's a bug. |
|
864 | 862 | IPython will proceed with builtin defaults.""" % sys.exc_info()[1] |
|
865 | 863 | warn(warning) |
|
866 | 864 | wait() |
|
867 | 865 | return |
|
868 | 866 | |
|
869 | 867 | elif mode == 'upgrade': |
|
870 | 868 | try: |
|
871 | 869 | os.chdir(ipythondir) |
|
872 | 870 | except: |
|
873 | 871 | print """ |
|
874 | 872 | Can not upgrade: changing to directory %s failed. Details: |
|
875 | 873 | %s |
|
876 | 874 | """ % (ipythondir,sys.exc_info()[1]) |
|
877 | 875 | wait() |
|
878 | 876 | return |
|
879 | 877 | else: |
|
880 | 878 | sources = glb(os.path.join(rcdir,'[A-Za-z]*')) |
|
881 | 879 | for new_full_path in sources: |
|
882 | 880 | new_filename = os.path.basename(new_full_path) |
|
883 | 881 | if new_filename.startswith('ipythonrc'): |
|
884 | 882 | new_filename = new_filename + rc_suffix |
|
885 | 883 | # The config directory should only contain files, skip any |
|
886 | 884 | # directories which may be there (like CVS) |
|
887 | 885 | if os.path.isdir(new_full_path): |
|
888 | 886 | continue |
|
889 | 887 | if os.path.exists(new_filename): |
|
890 | 888 | old_file = new_filename+'.old' |
|
891 | 889 | if os.path.exists(old_file): |
|
892 | 890 | os.remove(old_file) |
|
893 | 891 | os.rename(new_filename,old_file) |
|
894 | 892 | shutil.copy(new_full_path,new_filename) |
|
895 | 893 | else: |
|
896 | 894 | raise ValueError,'unrecognized mode for install:',`mode` |
|
897 | 895 | |
|
898 | 896 | # Fix line-endings to those native to each platform in the config |
|
899 | 897 | # directory. |
|
900 | 898 | try: |
|
901 | 899 | os.chdir(ipythondir) |
|
902 | 900 | except: |
|
903 | 901 | print """ |
|
904 | 902 | Problem: changing to directory %s failed. |
|
905 | 903 | Details: |
|
906 | 904 | %s |
|
907 | 905 | |
|
908 | 906 | Some configuration files may have incorrect line endings. This should not |
|
909 | 907 | cause any problems during execution. """ % (ipythondir,sys.exc_info()[1]) |
|
910 | 908 | wait() |
|
911 | 909 | else: |
|
912 | 910 | for fname in glb('ipythonrc*'): |
|
913 | 911 | try: |
|
914 | 912 | native_line_ends(fname,backup=0) |
|
915 | 913 | except IOError: |
|
916 | 914 | pass |
|
917 | 915 | |
|
918 | 916 | if mode == 'install': |
|
919 | 917 | print """ |
|
920 | 918 | Successful installation! |
|
921 | 919 | |
|
922 | 920 | Please read the sections 'Initial Configuration' and 'Quick Tips' in the |
|
923 | 921 | IPython manual (there are both HTML and PDF versions supplied with the |
|
924 | 922 | distribution) to make sure that your system environment is properly configured |
|
925 | 923 | to take advantage of IPython's features.""" |
|
926 | 924 | else: |
|
927 | 925 | print """ |
|
928 | 926 | Successful upgrade! |
|
929 | 927 | |
|
930 | 928 | All files in your directory: |
|
931 | 929 | %(ipythondir)s |
|
932 | 930 | which would have been overwritten by the upgrade were backed up with a .old |
|
933 | 931 | extension. If you had made particular customizations in those files you may |
|
934 | 932 | want to merge them back into the new files.""" % locals() |
|
935 | 933 | wait() |
|
936 | 934 | os.chdir(cwd) |
|
937 | 935 | # end user_setup() |
|
938 | 936 | |
|
939 | 937 | def atexit_operations(self): |
|
940 | 938 | """This will be executed at the time of exit. |
|
941 | 939 | |
|
942 | 940 | Saving of persistent data should be performed here. """ |
|
943 | 941 | |
|
944 | 942 | # input history |
|
945 | 943 | self.savehist() |
|
946 | 944 | |
|
947 | 945 | # Cleanup all tempfiles left around |
|
948 | 946 | for tfile in self.tempfiles: |
|
949 | 947 | try: |
|
950 | 948 | os.unlink(tfile) |
|
951 | 949 | except OSError: |
|
952 | 950 | pass |
|
953 | 951 | |
|
954 | 952 | # save the "persistent data" catch-all dictionary |
|
955 | 953 | try: |
|
956 | 954 | pickle.dump(self.persist, open(self.persist_fname,"w")) |
|
957 | 955 | except: |
|
958 | 956 | print "*** ERROR *** persistent data saving failed." |
|
959 | 957 | |
|
960 | 958 | def savehist(self): |
|
961 | 959 | """Save input history to a file (via readline library).""" |
|
962 | 960 | try: |
|
963 | 961 | self.readline.write_history_file(self.histfile) |
|
964 | 962 | except: |
|
965 | 963 | print 'Unable to save IPython command history to file: ' + \ |
|
966 | 964 | `self.histfile` |
|
967 | 965 | |
|
968 | 966 | def pre_readline(self): |
|
969 | 967 | """readline hook to be used at the start of each line. |
|
970 | 968 | |
|
971 | 969 | Currently it handles auto-indent only.""" |
|
972 | 970 | |
|
973 | 971 | self.readline.insert_text(self.indent_current) |
|
974 | 972 | |
|
975 | 973 | def init_readline(self): |
|
976 | 974 | """Command history completion/saving/reloading.""" |
|
977 | 975 | try: |
|
978 | 976 | import readline |
|
979 | 977 | except ImportError: |
|
980 | 978 | self.has_readline = 0 |
|
981 | 979 | self.readline = None |
|
982 | 980 | # no point in bugging windows users with this every time: |
|
983 | 981 | if os.name == 'posix': |
|
984 | 982 | warn('Readline services not available on this platform.') |
|
985 | 983 | else: |
|
986 | 984 | import atexit |
|
987 | 985 | from IPython.completer import IPCompleter |
|
988 | 986 | self.Completer = IPCompleter(self, |
|
989 | 987 | self.user_ns, |
|
990 | 988 | self.user_global_ns, |
|
991 | 989 | self.rc.readline_omit__names, |
|
992 | 990 | self.alias_table) |
|
993 | 991 | |
|
994 | 992 | # Platform-specific configuration |
|
995 | 993 | if os.name == 'nt': |
|
996 | 994 | self.readline_startup_hook = readline.set_pre_input_hook |
|
997 | 995 | else: |
|
998 | 996 | self.readline_startup_hook = readline.set_startup_hook |
|
999 | 997 | |
|
1000 | 998 | # Load user's initrc file (readline config) |
|
1001 | 999 | inputrc_name = os.environ.get('INPUTRC') |
|
1002 | 1000 | if inputrc_name is None: |
|
1003 | 1001 | home_dir = get_home_dir() |
|
1004 | 1002 | if home_dir is not None: |
|
1005 | 1003 | inputrc_name = os.path.join(home_dir,'.inputrc') |
|
1006 | 1004 | if os.path.isfile(inputrc_name): |
|
1007 | 1005 | try: |
|
1008 | 1006 | readline.read_init_file(inputrc_name) |
|
1009 | 1007 | except: |
|
1010 | 1008 | warn('Problems reading readline initialization file <%s>' |
|
1011 | 1009 | % inputrc_name) |
|
1012 | 1010 | |
|
1013 | 1011 | self.has_readline = 1 |
|
1014 | 1012 | self.readline = readline |
|
1015 | 1013 | # save this in sys so embedded copies can restore it properly |
|
1016 | 1014 | sys.ipcompleter = self.Completer.complete |
|
1017 | 1015 | readline.set_completer(self.Completer.complete) |
|
1018 | 1016 | |
|
1019 | 1017 | # Configure readline according to user's prefs |
|
1020 | 1018 | for rlcommand in self.rc.readline_parse_and_bind: |
|
1021 | 1019 | readline.parse_and_bind(rlcommand) |
|
1022 | 1020 | |
|
1023 | 1021 | # remove some chars from the delimiters list |
|
1024 | 1022 | delims = readline.get_completer_delims() |
|
1025 | 1023 | delims = delims.translate(string._idmap, |
|
1026 | 1024 | self.rc.readline_remove_delims) |
|
1027 | 1025 | readline.set_completer_delims(delims) |
|
1028 | 1026 | # otherwise we end up with a monster history after a while: |
|
1029 | 1027 | readline.set_history_length(1000) |
|
1030 | 1028 | try: |
|
1031 | 1029 | #print '*** Reading readline history' # dbg |
|
1032 | 1030 | readline.read_history_file(self.histfile) |
|
1033 | 1031 | except IOError: |
|
1034 | 1032 | pass # It doesn't exist yet. |
|
1035 | 1033 | |
|
1036 | 1034 | atexit.register(self.atexit_operations) |
|
1037 | 1035 | del atexit |
|
1038 | 1036 | |
|
1039 | 1037 | # Configure auto-indent for all platforms |
|
1040 | 1038 | self.set_autoindent(self.rc.autoindent) |
|
1041 | 1039 | |
|
1042 | 1040 | def _should_recompile(self,e): |
|
1043 | 1041 | """Utility routine for edit_syntax_error""" |
|
1044 | 1042 | |
|
1045 | 1043 | if e.filename in ('<ipython console>','<input>','<string>', |
|
1046 | 1044 | '<console>'): |
|
1047 | 1045 | return False |
|
1048 | 1046 | try: |
|
1049 | 1047 | if not ask_yes_no('Return to editor to correct syntax error? ' |
|
1050 | 1048 | '[Y/n] ','y'): |
|
1051 | 1049 | return False |
|
1052 | 1050 | except EOFError: |
|
1053 | 1051 | return False |
|
1054 | 1052 | self.hooks.fix_error_editor(e.filename,e.lineno,e.offset,e.msg) |
|
1055 | 1053 | return True |
|
1056 | 1054 | |
|
1057 | 1055 | def edit_syntax_error(self): |
|
1058 | 1056 | """The bottom half of the syntax error handler called in the main loop. |
|
1059 | 1057 | |
|
1060 | 1058 | Loop until syntax error is fixed or user cancels. |
|
1061 | 1059 | """ |
|
1062 | 1060 | |
|
1063 | 1061 | while self.SyntaxTB.last_syntax_error: |
|
1064 | 1062 | # copy and clear last_syntax_error |
|
1065 | 1063 | err = self.SyntaxTB.clear_err_state() |
|
1066 | 1064 | if not self._should_recompile(err): |
|
1067 | 1065 | return |
|
1068 | 1066 | try: |
|
1069 | 1067 | # may set last_syntax_error again if a SyntaxError is raised |
|
1070 | 1068 | self.safe_execfile(err.filename,self.shell.user_ns) |
|
1071 | 1069 | except: |
|
1072 | 1070 | self.showtraceback() |
|
1073 | 1071 | else: |
|
1074 | 1072 | f = file(err.filename) |
|
1075 | 1073 | try: |
|
1076 | 1074 | sys.displayhook(f.read()) |
|
1077 | 1075 | finally: |
|
1078 | 1076 | f.close() |
|
1079 | 1077 | |
|
1080 | 1078 | def showsyntaxerror(self, filename=None): |
|
1081 | 1079 | """Display the syntax error that just occurred. |
|
1082 | 1080 | |
|
1083 | 1081 | This doesn't display a stack trace because there isn't one. |
|
1084 | 1082 | |
|
1085 | 1083 | If a filename is given, it is stuffed in the exception instead |
|
1086 | 1084 | of what was there before (because Python's parser always uses |
|
1087 | 1085 | "<string>" when reading from a string). |
|
1088 | 1086 | """ |
|
1089 | 1087 | type, value, sys.last_traceback = sys.exc_info() |
|
1090 | 1088 | sys.last_type = type |
|
1091 | 1089 | sys.last_value = value |
|
1092 | 1090 | if filename and type is SyntaxError: |
|
1093 | 1091 | # Work hard to stuff the correct filename in the exception |
|
1094 | 1092 | try: |
|
1095 | 1093 | msg, (dummy_filename, lineno, offset, line) = value |
|
1096 | 1094 | except: |
|
1097 | 1095 | # Not the format we expect; leave it alone |
|
1098 | 1096 | pass |
|
1099 | 1097 | else: |
|
1100 | 1098 | # Stuff in the right filename |
|
1101 | 1099 | try: |
|
1102 | 1100 | # Assume SyntaxError is a class exception |
|
1103 | 1101 | value = SyntaxError(msg, (filename, lineno, offset, line)) |
|
1104 | 1102 | except: |
|
1105 | 1103 | # If that failed, assume SyntaxError is a string |
|
1106 | 1104 | value = msg, (filename, lineno, offset, line) |
|
1107 | 1105 | self.SyntaxTB(type,value,[]) |
|
1108 | 1106 | |
|
1109 | 1107 | def debugger(self): |
|
1110 | 1108 | """Call the pdb debugger.""" |
|
1111 | 1109 | |
|
1112 | 1110 | if not self.rc.pdb: |
|
1113 | 1111 | return |
|
1114 | 1112 | pdb.pm() |
|
1115 | 1113 | |
|
1116 | 1114 | def showtraceback(self,exc_tuple = None,filename=None): |
|
1117 | 1115 | """Display the exception that just occurred.""" |
|
1118 | 1116 | |
|
1119 | 1117 | # Though this won't be called by syntax errors in the input line, |
|
1120 | 1118 | # there may be SyntaxError cases whith imported code. |
|
1121 | 1119 | if exc_tuple is None: |
|
1122 | 1120 | type, value, tb = sys.exc_info() |
|
1123 | 1121 | else: |
|
1124 | 1122 | type, value, tb = exc_tuple |
|
1125 | 1123 | if type is SyntaxError: |
|
1126 | 1124 | self.showsyntaxerror(filename) |
|
1127 | 1125 | else: |
|
1128 | 1126 | sys.last_type = type |
|
1129 | 1127 | sys.last_value = value |
|
1130 | 1128 | sys.last_traceback = tb |
|
1131 | 1129 | self.InteractiveTB() |
|
1132 | 1130 | if self.InteractiveTB.call_pdb and self.has_readline: |
|
1133 | 1131 | # pdb mucks up readline, fix it back |
|
1134 | 1132 | self.readline.set_completer(self.Completer.complete) |
|
1135 | 1133 | |
|
1136 | 1134 | def update_cache(self, line): |
|
1137 | 1135 | """puts line into cache""" |
|
1138 | 1136 | self.inputcache.insert(0, line) # This copies the cache every time ... :-( |
|
1139 | 1137 | if len(self.inputcache) >= self.CACHELENGTH: |
|
1140 | 1138 | self.inputcache.pop() # This doesn't :-) |
|
1141 | 1139 | |
|
1142 | 1140 | def mainloop(self,banner=None): |
|
1143 | 1141 | """Creates the local namespace and starts the mainloop. |
|
1144 | 1142 | |
|
1145 | 1143 | If an optional banner argument is given, it will override the |
|
1146 | 1144 | internally created default banner.""" |
|
1147 | 1145 | |
|
1148 | 1146 | if self.rc.c: # Emulate Python's -c option |
|
1149 | 1147 | self.exec_init_cmd() |
|
1150 | 1148 | if banner is None: |
|
1151 | 1149 | if self.rc.banner: |
|
1152 | 1150 | banner = self.BANNER+self.banner2 |
|
1153 | 1151 | else: |
|
1154 | 1152 | banner = '' |
|
1155 | 1153 | self.interact(banner) |
|
1156 | 1154 | |
|
1157 | 1155 | def exec_init_cmd(self): |
|
1158 | 1156 | """Execute a command given at the command line. |
|
1159 | 1157 | |
|
1160 | 1158 | This emulates Python's -c option.""" |
|
1161 | 1159 | |
|
1162 | 1160 | sys.argv = ['-c'] |
|
1163 | 1161 | self.push(self.rc.c) |
|
1164 | 1162 | |
|
1165 | 1163 | def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0): |
|
1166 | 1164 | """Embeds IPython into a running python program. |
|
1167 | 1165 | |
|
1168 | 1166 | Input: |
|
1169 | 1167 | |
|
1170 | 1168 | - header: An optional header message can be specified. |
|
1171 | 1169 | |
|
1172 | 1170 | - local_ns, global_ns: working namespaces. If given as None, the |
|
1173 | 1171 | IPython-initialized one is updated with __main__.__dict__, so that |
|
1174 | 1172 | program variables become visible but user-specific configuration |
|
1175 | 1173 | remains possible. |
|
1176 | 1174 | |
|
1177 | 1175 | - stack_depth: specifies how many levels in the stack to go to |
|
1178 | 1176 | looking for namespaces (when local_ns and global_ns are None). This |
|
1179 | 1177 | allows an intermediate caller to make sure that this function gets |
|
1180 | 1178 | the namespace from the intended level in the stack. By default (0) |
|
1181 | 1179 | it will get its locals and globals from the immediate caller. |
|
1182 | 1180 | |
|
1183 | 1181 | Warning: it's possible to use this in a program which is being run by |
|
1184 | 1182 | IPython itself (via %run), but some funny things will happen (a few |
|
1185 | 1183 | globals get overwritten). In the future this will be cleaned up, as |
|
1186 | 1184 | there is no fundamental reason why it can't work perfectly.""" |
|
1187 | 1185 | |
|
1188 | 1186 | # Get locals and globals from caller |
|
1189 | 1187 | if local_ns is None or global_ns is None: |
|
1190 | 1188 | call_frame = sys._getframe(stack_depth).f_back |
|
1191 | 1189 | |
|
1192 | 1190 | if local_ns is None: |
|
1193 | 1191 | local_ns = call_frame.f_locals |
|
1194 | 1192 | if global_ns is None: |
|
1195 | 1193 | global_ns = call_frame.f_globals |
|
1196 | 1194 | |
|
1197 | 1195 | # Update namespaces and fire up interpreter |
|
1198 | 1196 | self.user_ns = local_ns |
|
1199 | 1197 | self.user_global_ns = global_ns |
|
1200 | 1198 | |
|
1201 | 1199 | # Patch for global embedding to make sure that things don't overwrite |
|
1202 | 1200 | # user globals accidentally. Thanks to Richard <rxe@renre-europe.com> |
|
1203 | 1201 | # FIXME. Test this a bit more carefully (the if.. is new) |
|
1204 | 1202 | if local_ns is None and global_ns is None: |
|
1205 | 1203 | self.user_global_ns.update(__main__.__dict__) |
|
1206 | 1204 | |
|
1207 | 1205 | # make sure the tab-completer has the correct frame information, so it |
|
1208 | 1206 | # actually completes using the frame's locals/globals |
|
1209 | 1207 | self.set_completer_frame(call_frame) |
|
1210 | 1208 | |
|
1211 | 1209 | self.interact(header) |
|
1212 | 1210 | |
|
1213 | 1211 | def interact(self, banner=None): |
|
1214 | 1212 | """Closely emulate the interactive Python console. |
|
1215 | 1213 | |
|
1216 | 1214 | The optional banner argument specify the banner to print |
|
1217 | 1215 | before the first interaction; by default it prints a banner |
|
1218 | 1216 | similar to the one printed by the real Python interpreter, |
|
1219 | 1217 | followed by the current class name in parentheses (so as not |
|
1220 | 1218 | to confuse this with the real interpreter -- since it's so |
|
1221 | 1219 | close!). |
|
1222 | 1220 | |
|
1223 | 1221 | """ |
|
1224 | 1222 | cprt = 'Type "copyright", "credits" or "license" for more information.' |
|
1225 | 1223 | if banner is None: |
|
1226 | 1224 | self.write("Python %s on %s\n%s\n(%s)\n" % |
|
1227 | 1225 | (sys.version, sys.platform, cprt, |
|
1228 | 1226 | self.__class__.__name__)) |
|
1229 | 1227 | else: |
|
1230 | 1228 | self.write(banner) |
|
1231 | 1229 | |
|
1232 | 1230 | more = 0 |
|
1233 | 1231 | |
|
1234 | 1232 | # Mark activity in the builtins |
|
1235 | 1233 | __builtin__.__dict__['__IPYTHON__active'] += 1 |
|
1236 | 1234 | |
|
1237 | 1235 | # compiled regexps for autoindent management |
|
1238 | 1236 | ini_spaces_re = re.compile(r'^(\s+)') |
|
1239 | 1237 | dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass') |
|
1240 | 1238 | |
|
1241 | 1239 | # exit_now is set by a call to %Exit or %Quit |
|
1242 | 1240 | while not self.exit_now: |
|
1243 | 1241 | try: |
|
1244 | 1242 | if more: |
|
1245 | 1243 | prompt = self.outputcache.prompt2 |
|
1246 | 1244 | if self.autoindent: |
|
1247 | 1245 | self.readline_startup_hook(self.pre_readline) |
|
1248 | 1246 | else: |
|
1249 | 1247 | prompt = self.outputcache.prompt1 |
|
1250 | 1248 | try: |
|
1251 | 1249 | line = self.raw_input(prompt,more) |
|
1252 | 1250 | if self.autoindent: |
|
1253 | 1251 | self.readline_startup_hook(None) |
|
1254 | 1252 | except EOFError: |
|
1255 | 1253 | if self.autoindent: |
|
1256 | 1254 | self.readline_startup_hook(None) |
|
1257 | 1255 | self.write("\n") |
|
1258 | 1256 | self.exit() |
|
1259 | except IPythonExit: | |
|
1260 | self.exit() | |
|
1261 | 1257 | else: |
|
1262 | 1258 | more = self.push(line) |
|
1263 | 1259 | # Auto-indent management |
|
1264 | 1260 | if self.autoindent: |
|
1265 | 1261 | if line: |
|
1266 | 1262 | ini_spaces = ini_spaces_re.match(line) |
|
1267 | 1263 | if ini_spaces: |
|
1268 | 1264 | nspaces = ini_spaces.end() |
|
1269 | 1265 | else: |
|
1270 | 1266 | nspaces = 0 |
|
1271 | 1267 | self.indent_current_nsp = nspaces |
|
1272 | 1268 | |
|
1273 | 1269 | if line[-1] == ':': |
|
1274 | 1270 | self.indent_current_nsp += 4 |
|
1275 | 1271 | elif dedent_re.match(line): |
|
1276 | 1272 | self.indent_current_nsp -= 4 |
|
1277 | 1273 | else: |
|
1278 | 1274 | self.indent_current_nsp = 0 |
|
1279 | 1275 | |
|
1280 | 1276 | # indent_current is the actual string to be inserted |
|
1281 | 1277 | # by the readline hooks for indentation |
|
1282 | 1278 | self.indent_current = ' '* self.indent_current_nsp |
|
1283 | 1279 | |
|
1284 | 1280 | if (self.SyntaxTB.last_syntax_error and |
|
1285 | 1281 | self.rc.autoedit_syntax): |
|
1286 | 1282 | self.edit_syntax_error() |
|
1287 | 1283 | |
|
1288 | 1284 | except KeyboardInterrupt: |
|
1289 | 1285 | self.write("\nKeyboardInterrupt\n") |
|
1290 | 1286 | self.resetbuffer() |
|
1291 | 1287 | more = 0 |
|
1292 | 1288 | # keep cache in sync with the prompt counter: |
|
1293 | 1289 | self.outputcache.prompt_count -= 1 |
|
1294 | 1290 | |
|
1295 | 1291 | if self.autoindent: |
|
1296 | 1292 | self.indent_current_nsp = 0 |
|
1297 | 1293 | self.indent_current = ' '* self.indent_current_nsp |
|
1298 | 1294 | |
|
1299 | 1295 | except bdb.BdbQuit: |
|
1300 | 1296 | warn("The Python debugger has exited with a BdbQuit exception.\n" |
|
1301 | 1297 | "Because of how pdb handles the stack, it is impossible\n" |
|
1302 | 1298 | "for IPython to properly format this particular exception.\n" |
|
1303 | 1299 | "IPython will resume normal operation.") |
|
1304 | 1300 | |
|
1305 | 1301 | # We are off again... |
|
1306 | 1302 | __builtin__.__dict__['__IPYTHON__active'] -= 1 |
|
1307 | 1303 | |
|
1308 | 1304 | def excepthook(self, type, value, tb): |
|
1309 | 1305 | """One more defense for GUI apps that call sys.excepthook. |
|
1310 | 1306 | |
|
1311 | 1307 | GUI frameworks like wxPython trap exceptions and call |
|
1312 | 1308 | sys.excepthook themselves. I guess this is a feature that |
|
1313 | 1309 | enables them to keep running after exceptions that would |
|
1314 | 1310 | otherwise kill their mainloop. This is a bother for IPython |
|
1315 | 1311 | which excepts to catch all of the program exceptions with a try: |
|
1316 | 1312 | except: statement. |
|
1317 | 1313 | |
|
1318 | 1314 | Normally, IPython sets sys.excepthook to a CrashHandler instance, so if |
|
1319 | 1315 | any app directly invokes sys.excepthook, it will look to the user like |
|
1320 | 1316 | IPython crashed. In order to work around this, we can disable the |
|
1321 | 1317 | CrashHandler and replace it with this excepthook instead, which prints a |
|
1322 | 1318 | regular traceback using our InteractiveTB. In this fashion, apps which |
|
1323 | 1319 | call sys.excepthook will generate a regular-looking exception from |
|
1324 | 1320 | IPython, and the CrashHandler will only be triggered by real IPython |
|
1325 | 1321 | crashes. |
|
1326 | 1322 | |
|
1327 | 1323 | This hook should be used sparingly, only in places which are not likely |
|
1328 | 1324 | to be true IPython errors. |
|
1329 | 1325 | """ |
|
1330 | 1326 | |
|
1331 | 1327 | self.InteractiveTB(type, value, tb, tb_offset=0) |
|
1332 | 1328 | if self.InteractiveTB.call_pdb and self.has_readline: |
|
1333 | 1329 | self.readline.set_completer(self.Completer.complete) |
|
1334 | 1330 | |
|
1335 | 1331 | def call_alias(self,alias,rest=''): |
|
1336 | 1332 | """Call an alias given its name and the rest of the line. |
|
1337 | 1333 | |
|
1338 | 1334 | This function MUST be given a proper alias, because it doesn't make |
|
1339 | 1335 | any checks when looking up into the alias table. The caller is |
|
1340 | 1336 | responsible for invoking it only with a valid alias.""" |
|
1341 | 1337 | |
|
1342 | 1338 | #print 'ALIAS: <%s>+<%s>' % (alias,rest) # dbg |
|
1343 | 1339 | nargs,cmd = self.alias_table[alias] |
|
1344 | 1340 | # Expand the %l special to be the user's input line |
|
1345 | 1341 | if cmd.find('%l') >= 0: |
|
1346 | 1342 | cmd = cmd.replace('%l',rest) |
|
1347 | 1343 | rest = '' |
|
1348 | 1344 | if nargs==0: |
|
1349 | 1345 | # Simple, argument-less aliases |
|
1350 | 1346 | cmd = '%s %s' % (cmd,rest) |
|
1351 | 1347 | else: |
|
1352 | 1348 | # Handle aliases with positional arguments |
|
1353 | 1349 | args = rest.split(None,nargs) |
|
1354 | 1350 | if len(args)< nargs: |
|
1355 | 1351 | error('Alias <%s> requires %s arguments, %s given.' % |
|
1356 | 1352 | (alias,nargs,len(args))) |
|
1357 | 1353 | return |
|
1358 | 1354 | cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:])) |
|
1359 | 1355 | # Now call the macro, evaluating in the user's namespace |
|
1360 | 1356 | try: |
|
1361 | 1357 | self.system(cmd) |
|
1362 | 1358 | except: |
|
1363 | 1359 | self.showtraceback() |
|
1364 | 1360 | |
|
1365 | 1361 | def runlines(self,lines): |
|
1366 | 1362 | """Run a string of one or more lines of source. |
|
1367 | 1363 | |
|
1368 | 1364 | This method is capable of running a string containing multiple source |
|
1369 | 1365 | lines, as if they had been entered at the IPython prompt. Since it |
|
1370 | 1366 | exposes IPython's processing machinery, the given strings can contain |
|
1371 | 1367 | magic calls (%magic), special shell access (!cmd), etc.""" |
|
1372 | 1368 | |
|
1373 | 1369 | # We must start with a clean buffer, in case this is run from an |
|
1374 | 1370 | # interactive IPython session (via a magic, for example). |
|
1375 | 1371 | self.resetbuffer() |
|
1376 | 1372 | lines = lines.split('\n') |
|
1377 | 1373 | more = 0 |
|
1378 | 1374 | for line in lines: |
|
1379 | 1375 | # skip blank lines so we don't mess up the prompt counter, but do |
|
1380 | 1376 | # NOT skip even a blank line if we are in a code block (more is |
|
1381 | 1377 | # true) |
|
1382 | 1378 | if line or more: |
|
1383 | 1379 | more = self.push((self.prefilter(line,more))) |
|
1384 | 1380 | # IPython's runsource returns None if there was an error |
|
1385 | 1381 | # compiling the code. This allows us to stop processing right |
|
1386 | 1382 | # away, so the user gets the error message at the right place. |
|
1387 | 1383 | if more is None: |
|
1388 | 1384 | break |
|
1389 | 1385 | # final newline in case the input didn't have it, so that the code |
|
1390 | 1386 | # actually does get executed |
|
1391 | 1387 | if more: |
|
1392 | 1388 | self.push('\n') |
|
1393 | 1389 | |
|
1394 | 1390 | def runsource(self, source, filename='<input>', symbol='single'): |
|
1395 | 1391 | """Compile and run some source in the interpreter. |
|
1396 | 1392 | |
|
1397 | 1393 | Arguments are as for compile_command(). |
|
1398 | 1394 | |
|
1399 | 1395 | One several things can happen: |
|
1400 | 1396 | |
|
1401 | 1397 | 1) The input is incorrect; compile_command() raised an |
|
1402 | 1398 | exception (SyntaxError or OverflowError). A syntax traceback |
|
1403 | 1399 | will be printed by calling the showsyntaxerror() method. |
|
1404 | 1400 | |
|
1405 | 1401 | 2) The input is incomplete, and more input is required; |
|
1406 | 1402 | compile_command() returned None. Nothing happens. |
|
1407 | 1403 | |
|
1408 | 1404 | 3) The input is complete; compile_command() returned a code |
|
1409 | 1405 | object. The code is executed by calling self.runcode() (which |
|
1410 | 1406 | also handles run-time exceptions, except for SystemExit). |
|
1411 | 1407 | |
|
1412 | 1408 | The return value is: |
|
1413 | 1409 | |
|
1414 | 1410 | - True in case 2 |
|
1415 | 1411 | |
|
1416 | 1412 | - False in the other cases, unless an exception is raised, where |
|
1417 | 1413 | None is returned instead. This can be used by external callers to |
|
1418 | 1414 | know whether to continue feeding input or not. |
|
1419 | 1415 | |
|
1420 | 1416 | The return value can be used to decide whether to use sys.ps1 or |
|
1421 | 1417 | sys.ps2 to prompt the next line.""" |
|
1422 | 1418 | |
|
1423 | 1419 | try: |
|
1424 | 1420 | code = self.compile(source,filename,symbol) |
|
1425 | 1421 | except (OverflowError, SyntaxError, ValueError): |
|
1426 | 1422 | # Case 1 |
|
1427 | 1423 | self.showsyntaxerror(filename) |
|
1428 | 1424 | return None |
|
1429 | 1425 | |
|
1430 | 1426 | if code is None: |
|
1431 | 1427 | # Case 2 |
|
1432 | 1428 | return True |
|
1433 | 1429 | |
|
1434 | 1430 | # Case 3 |
|
1435 | 1431 | # We store the code object so that threaded shells and |
|
1436 | 1432 | # custom exception handlers can access all this info if needed. |
|
1437 | 1433 | # The source corresponding to this can be obtained from the |
|
1438 | 1434 | # buffer attribute as '\n'.join(self.buffer). |
|
1439 | 1435 | self.code_to_run = code |
|
1440 | 1436 | # now actually execute the code object |
|
1441 | 1437 | if self.runcode(code) == 0: |
|
1442 | 1438 | return False |
|
1443 | 1439 | else: |
|
1444 | 1440 | return None |
|
1445 | 1441 | |
|
1446 | 1442 | def runcode(self,code_obj): |
|
1447 | 1443 | """Execute a code object. |
|
1448 | 1444 | |
|
1449 | 1445 | When an exception occurs, self.showtraceback() is called to display a |
|
1450 | 1446 | traceback. |
|
1451 | 1447 | |
|
1452 | 1448 | Return value: a flag indicating whether the code to be run completed |
|
1453 | 1449 | successfully: |
|
1454 | 1450 | |
|
1455 | 1451 | - 0: successful execution. |
|
1456 | 1452 | - 1: an error occurred. |
|
1457 | 1453 | """ |
|
1458 | 1454 | |
|
1459 | 1455 | # Set our own excepthook in case the user code tries to call it |
|
1460 | 1456 | # directly, so that the IPython crash handler doesn't get triggered |
|
1461 | 1457 | old_excepthook,sys.excepthook = sys.excepthook, self.excepthook |
|
1462 | 1458 | outflag = 1 # happens in more places, so it's easier as default |
|
1463 | 1459 | try: |
|
1464 | 1460 | try: |
|
1465 | 1461 | # Embedded instances require separate global/local namespaces |
|
1466 | 1462 | # so they can see both the surrounding (local) namespace and |
|
1467 | 1463 | # the module-level globals when called inside another function. |
|
1468 | 1464 | if self.embedded: |
|
1469 | 1465 | exec code_obj in self.user_global_ns, self.user_ns |
|
1470 | 1466 | # Normal (non-embedded) instances should only have a single |
|
1471 | 1467 | # namespace for user code execution, otherwise functions won't |
|
1472 | 1468 | # see interactive top-level globals. |
|
1473 | 1469 | else: |
|
1474 | 1470 | exec code_obj in self.user_ns |
|
1475 | 1471 | finally: |
|
1476 | 1472 | # Reset our crash handler in place |
|
1477 | 1473 | sys.excepthook = old_excepthook |
|
1478 | 1474 | except SystemExit: |
|
1479 | 1475 | self.resetbuffer() |
|
1480 | 1476 | self.showtraceback() |
|
1481 | 1477 | warn("Type exit or quit to exit IPython " |
|
1482 | 1478 | "(%Exit or %Quit do so unconditionally).",level=1) |
|
1483 | 1479 | except self.custom_exceptions: |
|
1484 | 1480 | etype,value,tb = sys.exc_info() |
|
1485 | 1481 | self.CustomTB(etype,value,tb) |
|
1486 | 1482 | except: |
|
1487 | 1483 | self.showtraceback() |
|
1488 | 1484 | else: |
|
1489 | 1485 | outflag = 0 |
|
1490 | 1486 | if softspace(sys.stdout, 0): |
|
1491 | 1487 | |
|
1492 | 1488 | # Flush out code object which has been run (and source) |
|
1493 | 1489 | self.code_to_run = None |
|
1494 | 1490 | return outflag |
|
1495 | 1491 | |
|
1496 | 1492 | def push(self, line): |
|
1497 | 1493 | """Push a line to the interpreter. |
|
1498 | 1494 | |
|
1499 | 1495 | The line should not have a trailing newline; it may have |
|
1500 | 1496 | internal newlines. The line is appended to a buffer and the |
|
1501 | 1497 | interpreter's runsource() method is called with the |
|
1502 | 1498 | concatenated contents of the buffer as source. If this |
|
1503 | 1499 | indicates that the command was executed or invalid, the buffer |
|
1504 | 1500 | is reset; otherwise, the command is incomplete, and the buffer |
|
1505 | 1501 | is left as it was after the line was appended. The return |
|
1506 | 1502 | value is 1 if more input is required, 0 if the line was dealt |
|
1507 | 1503 | with in some way (this is the same as runsource()). |
|
1508 | 1504 | |
|
1509 | 1505 | """ |
|
1510 | 1506 | self.buffer.append(line) |
|
1511 | 1507 | more = self.runsource('\n'.join(self.buffer), self.filename) |
|
1512 | 1508 | if not more: |
|
1513 | 1509 | self.resetbuffer() |
|
1514 | 1510 | return more |
|
1515 | 1511 | |
|
1516 | 1512 | def resetbuffer(self): |
|
1517 | 1513 | """Reset the input buffer.""" |
|
1518 | 1514 | self.buffer[:] = [] |
|
1519 | 1515 | |
|
1520 | 1516 | def raw_input(self,prompt='',continue_prompt=False): |
|
1521 | 1517 | """Write a prompt and read a line. |
|
1522 | 1518 | |
|
1523 | 1519 | The returned line does not include the trailing newline. |
|
1524 | 1520 | When the user enters the EOF key sequence, EOFError is raised. |
|
1525 | 1521 | |
|
1526 | 1522 | Optional inputs: |
|
1527 | 1523 | |
|
1528 | 1524 | - prompt(''): a string to be printed to prompt the user. |
|
1529 | 1525 | |
|
1530 | 1526 | - continue_prompt(False): whether this line is the first one or a |
|
1531 | 1527 | continuation in a sequence of inputs. |
|
1532 | 1528 | """ |
|
1533 | 1529 | |
|
1534 | 1530 | line = raw_input_original(prompt) |
|
1535 | 1531 | # Try to be reasonably smart about not re-indenting pasted input more |
|
1536 | 1532 | # than necessary. We do this by trimming out the auto-indent initial |
|
1537 | 1533 | # spaces, if the user's actual input started itself with whitespace. |
|
1538 | 1534 | if self.autoindent: |
|
1539 | 1535 | line2 = line[self.indent_current_nsp:] |
|
1540 | 1536 | if line2[0:1] in (' ','\t'): |
|
1541 | 1537 | line = line2 |
|
1542 | 1538 | return self.prefilter(line,continue_prompt) |
|
1543 | 1539 | |
|
1544 | 1540 | def split_user_input(self,line): |
|
1545 | 1541 | """Split user input into pre-char, function part and rest.""" |
|
1546 | 1542 | |
|
1547 | 1543 | lsplit = self.line_split.match(line) |
|
1548 | 1544 | if lsplit is None: # no regexp match returns None |
|
1549 | 1545 | try: |
|
1550 | 1546 | iFun,theRest = line.split(None,1) |
|
1551 | 1547 | except ValueError: |
|
1552 | 1548 | iFun,theRest = line,'' |
|
1553 | 1549 | pre = re.match('^(\s*)(.*)',line).groups()[0] |
|
1554 | 1550 | else: |
|
1555 | 1551 | pre,iFun,theRest = lsplit.groups() |
|
1556 | 1552 | |
|
1557 | 1553 | #print 'line:<%s>' % line # dbg |
|
1558 | 1554 | #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun.strip(),theRest) # dbg |
|
1559 | 1555 | return pre,iFun.strip(),theRest |
|
1560 | 1556 | |
|
1561 | 1557 | def _prefilter(self, line, continue_prompt): |
|
1562 | 1558 | """Calls different preprocessors, depending on the form of line.""" |
|
1563 | 1559 | |
|
1564 | 1560 | # All handlers *must* return a value, even if it's blank (''). |
|
1565 | 1561 | |
|
1566 | 1562 | # Lines are NOT logged here. Handlers should process the line as |
|
1567 | 1563 | # needed, update the cache AND log it (so that the input cache array |
|
1568 | 1564 | # stays synced). |
|
1569 | 1565 | |
|
1570 | 1566 | # This function is _very_ delicate, and since it's also the one which |
|
1571 | 1567 | # determines IPython's response to user input, it must be as efficient |
|
1572 | 1568 | # as possible. For this reason it has _many_ returns in it, trying |
|
1573 | 1569 | # always to exit as quickly as it can figure out what it needs to do. |
|
1574 | 1570 | |
|
1575 | 1571 | # This function is the main responsible for maintaining IPython's |
|
1576 | 1572 | # behavior respectful of Python's semantics. So be _very_ careful if |
|
1577 | 1573 | # making changes to anything here. |
|
1578 | 1574 | |
|
1579 | 1575 | #..................................................................... |
|
1580 | 1576 | # Code begins |
|
1581 | 1577 | |
|
1582 | 1578 | #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg |
|
1583 | 1579 | |
|
1584 | 1580 | # save the line away in case we crash, so the post-mortem handler can |
|
1585 | 1581 | # record it |
|
1586 | 1582 | self._last_input_line = line |
|
1587 | 1583 | |
|
1588 | 1584 | #print '***line: <%s>' % line # dbg |
|
1589 | 1585 | |
|
1590 | 1586 | # the input history needs to track even empty lines |
|
1591 | 1587 | if not line.strip(): |
|
1592 | 1588 | if not continue_prompt: |
|
1593 | 1589 | self.outputcache.prompt_count -= 1 |
|
1594 | 1590 | return self.handle_normal(line,continue_prompt) |
|
1595 | 1591 | #return self.handle_normal('',continue_prompt) |
|
1596 | 1592 | |
|
1597 | 1593 | # print '***cont',continue_prompt # dbg |
|
1598 | 1594 | # special handlers are only allowed for single line statements |
|
1599 | 1595 | if continue_prompt and not self.rc.multi_line_specials: |
|
1600 | 1596 | return self.handle_normal(line,continue_prompt) |
|
1601 | 1597 | |
|
1602 | 1598 | # For the rest, we need the structure of the input |
|
1603 | 1599 | pre,iFun,theRest = self.split_user_input(line) |
|
1604 | 1600 | #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg |
|
1605 | 1601 | |
|
1606 | 1602 | # First check for explicit escapes in the last/first character |
|
1607 | 1603 | handler = None |
|
1608 | 1604 | if line[-1] == self.ESC_HELP: |
|
1609 | 1605 | handler = self.esc_handlers.get(line[-1]) # the ? can be at the end |
|
1610 | 1606 | if handler is None: |
|
1611 | 1607 | # look at the first character of iFun, NOT of line, so we skip |
|
1612 | 1608 | # leading whitespace in multiline input |
|
1613 | 1609 | handler = self.esc_handlers.get(iFun[0:1]) |
|
1614 | 1610 | if handler is not None: |
|
1615 | 1611 | return handler(line,continue_prompt,pre,iFun,theRest) |
|
1616 | 1612 | # Emacs ipython-mode tags certain input lines |
|
1617 | 1613 | if line.endswith('# PYTHON-MODE'): |
|
1618 | 1614 | return self.handle_emacs(line,continue_prompt) |
|
1619 | 1615 | |
|
1620 | 1616 | # Next, check if we can automatically execute this thing |
|
1621 | 1617 | |
|
1622 | 1618 | # Allow ! in multi-line statements if multi_line_specials is on: |
|
1623 | 1619 | if continue_prompt and self.rc.multi_line_specials and \ |
|
1624 | 1620 | iFun.startswith(self.ESC_SHELL): |
|
1625 | 1621 | return self.handle_shell_escape(line,continue_prompt, |
|
1626 | 1622 | pre=pre,iFun=iFun, |
|
1627 | 1623 | theRest=theRest) |
|
1628 | 1624 | |
|
1629 | 1625 | # Let's try to find if the input line is a magic fn |
|
1630 | 1626 | oinfo = None |
|
1631 | 1627 | if hasattr(self,'magic_'+iFun): |
|
1632 | 1628 | oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic |
|
1633 | 1629 | if oinfo['ismagic']: |
|
1634 | 1630 | # Be careful not to call magics when a variable assignment is |
|
1635 | 1631 | # being made (ls='hi', for example) |
|
1636 | 1632 | if self.rc.automagic and \ |
|
1637 | 1633 | (len(theRest)==0 or theRest[0] not in '!=()<>,') and \ |
|
1638 | 1634 | (self.rc.multi_line_specials or not continue_prompt): |
|
1639 | 1635 | return self.handle_magic(line,continue_prompt, |
|
1640 | 1636 | pre,iFun,theRest) |
|
1641 | 1637 | else: |
|
1642 | 1638 | return self.handle_normal(line,continue_prompt) |
|
1643 | 1639 | |
|
1644 | 1640 | # If the rest of the line begins with an (in)equality, assginment or |
|
1645 | 1641 | # function call, we should not call _ofind but simply execute it. |
|
1646 | 1642 | # This avoids spurious geattr() accesses on objects upon assignment. |
|
1647 | 1643 | # |
|
1648 | 1644 | # It also allows users to assign to either alias or magic names true |
|
1649 | 1645 | # python variables (the magic/alias systems always take second seat to |
|
1650 | 1646 | # true python code). |
|
1651 | 1647 | if theRest and theRest[0] in '!=()': |
|
1652 | 1648 | return self.handle_normal(line,continue_prompt) |
|
1653 | 1649 | |
|
1654 | 1650 | if oinfo is None: |
|
1655 | 1651 | oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic |
|
1656 | 1652 | |
|
1657 | 1653 | if not oinfo['found']: |
|
1658 | if iFun in ('quit','exit'): | |
|
1659 | raise IPythonExit | |
|
1660 | 1654 | return self.handle_normal(line,continue_prompt) |
|
1661 | 1655 | else: |
|
1662 | 1656 | #print 'iFun <%s> rest <%s>' % (iFun,theRest) # dbg |
|
1663 | 1657 | if oinfo['isalias']: |
|
1664 | 1658 | return self.handle_alias(line,continue_prompt, |
|
1665 | 1659 | pre,iFun,theRest) |
|
1666 | 1660 | |
|
1667 | 1661 | if self.rc.autocall and \ |
|
1668 | 1662 | not self.re_exclude_auto.match(theRest) and \ |
|
1669 | 1663 | self.re_fun_name.match(iFun) and \ |
|
1670 | 1664 | callable(oinfo['obj']) : |
|
1671 | 1665 | #print 'going auto' # dbg |
|
1672 | 1666 | return self.handle_auto(line,continue_prompt,pre,iFun,theRest) |
|
1673 | 1667 | else: |
|
1674 | 1668 | #print 'was callable?', callable(oinfo['obj']) # dbg |
|
1675 | 1669 | return self.handle_normal(line,continue_prompt) |
|
1676 | 1670 | |
|
1677 | 1671 | # If we get here, we have a normal Python line. Log and return. |
|
1678 | 1672 | return self.handle_normal(line,continue_prompt) |
|
1679 | 1673 | |
|
1680 | 1674 | def _prefilter_dumb(self, line, continue_prompt): |
|
1681 | 1675 | """simple prefilter function, for debugging""" |
|
1682 | 1676 | return self.handle_normal(line,continue_prompt) |
|
1683 | 1677 | |
|
1684 | 1678 | # Set the default prefilter() function (this can be user-overridden) |
|
1685 | 1679 | prefilter = _prefilter |
|
1686 | 1680 | |
|
1687 | 1681 | def handle_normal(self,line,continue_prompt=None, |
|
1688 | 1682 | pre=None,iFun=None,theRest=None): |
|
1689 | 1683 | """Handle normal input lines. Use as a template for handlers.""" |
|
1690 | 1684 | |
|
1691 | 1685 | # With autoindent on, we need some way to exit the input loop, and I |
|
1692 | 1686 | # don't want to force the user to have to backspace all the way to |
|
1693 | 1687 | # clear the line. The rule will be in this case, that either two |
|
1694 | 1688 | # lines of pure whitespace in a row, or a line of pure whitespace but |
|
1695 | 1689 | # of a size different to the indent level, will exit the input loop. |
|
1696 | 1690 | if (continue_prompt and self.autoindent and isspace(line) and |
|
1697 | 1691 | (line != self.indent_current or isspace(self.buffer[-1]))): |
|
1698 | 1692 | line = '' |
|
1699 | 1693 | |
|
1700 | 1694 | self.log(line,continue_prompt) |
|
1701 | 1695 | self.update_cache(line) |
|
1702 | 1696 | return line |
|
1703 | 1697 | |
|
1704 | 1698 | def handle_alias(self,line,continue_prompt=None, |
|
1705 | 1699 | pre=None,iFun=None,theRest=None): |
|
1706 | 1700 | """Handle alias input lines. """ |
|
1707 | 1701 | |
|
1708 | 1702 | theRest = esc_quotes(theRest) |
|
1709 | 1703 | line_out = "%s%s.call_alias('%s','%s')" % (pre,self.name,iFun,theRest) |
|
1710 | 1704 | self.log(line_out,continue_prompt) |
|
1711 | 1705 | self.update_cache(line_out) |
|
1712 | 1706 | return line_out |
|
1713 | 1707 | |
|
1714 | 1708 | def handle_shell_escape(self, line, continue_prompt=None, |
|
1715 | 1709 | pre=None,iFun=None,theRest=None): |
|
1716 | 1710 | """Execute the line in a shell, empty return value""" |
|
1717 | 1711 | |
|
1718 | 1712 | #print 'line in :', `line` # dbg |
|
1719 | 1713 | # Example of a special handler. Others follow a similar pattern. |
|
1720 | 1714 | if continue_prompt: # multi-line statements |
|
1721 | 1715 | if iFun.startswith('!!'): |
|
1722 | 1716 | print 'SyntaxError: !! is not allowed in multiline statements' |
|
1723 | 1717 | return pre |
|
1724 | 1718 | else: |
|
1725 | 1719 | cmd = ("%s %s" % (iFun[1:],theRest)).replace('"','\\"') |
|
1726 | 1720 | line_out = '%s%s.system("%s")' % (pre,self.name,cmd) |
|
1727 | 1721 | #line_out = ('%s%s.system(' % (pre,self.name)) + repr(cmd) + ')' |
|
1728 | 1722 | else: # single-line input |
|
1729 | 1723 | if line.startswith('!!'): |
|
1730 | 1724 | # rewrite iFun/theRest to properly hold the call to %sx and |
|
1731 | 1725 | # the actual command to be executed, so handle_magic can work |
|
1732 | 1726 | # correctly |
|
1733 | 1727 | theRest = '%s %s' % (iFun[2:],theRest) |
|
1734 | 1728 | iFun = 'sx' |
|
1735 | 1729 | return self.handle_magic('%ssx %s' % (self.ESC_MAGIC,line[2:]), |
|
1736 | 1730 | continue_prompt,pre,iFun,theRest) |
|
1737 | 1731 | else: |
|
1738 | 1732 | cmd = esc_quotes(line[1:]) |
|
1739 | 1733 | line_out = '%s.system("%s")' % (self.name,cmd) |
|
1740 | 1734 | #line_out = ('%s.system(' % self.name) + repr(cmd)+ ')' |
|
1741 | 1735 | # update cache/log and return |
|
1742 | 1736 | self.log(line_out,continue_prompt) |
|
1743 | 1737 | self.update_cache(line_out) # readline cache gets normal line |
|
1744 | 1738 | #print 'line out r:', `line_out` # dbg |
|
1745 | 1739 | #print 'line out s:', line_out # dbg |
|
1746 | 1740 | return line_out |
|
1747 | 1741 | |
|
1748 | 1742 | def handle_magic(self, line, continue_prompt=None, |
|
1749 | 1743 | pre=None,iFun=None,theRest=None): |
|
1750 | 1744 | """Execute magic functions. |
|
1751 | 1745 | |
|
1752 | 1746 | Also log them with a prepended # so the log is clean Python.""" |
|
1753 | 1747 | |
|
1754 | 1748 | cmd = '%sipmagic("%s")' % (pre,esc_quotes('%s %s' % (iFun,theRest))) |
|
1755 | 1749 | self.log(cmd,continue_prompt) |
|
1756 | 1750 | self.update_cache(line) |
|
1757 | 1751 | #print 'in handle_magic, cmd=<%s>' % cmd # dbg |
|
1758 | 1752 | return cmd |
|
1759 | 1753 | |
|
1760 | 1754 | def handle_auto(self, line, continue_prompt=None, |
|
1761 | 1755 | pre=None,iFun=None,theRest=None): |
|
1762 | 1756 | """Hande lines which can be auto-executed, quoting if requested.""" |
|
1763 | 1757 | |
|
1764 | 1758 | #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg |
|
1765 | 1759 | |
|
1766 | 1760 | # This should only be active for single-line input! |
|
1767 | 1761 | if continue_prompt: |
|
1768 | 1762 | return line |
|
1769 | 1763 | |
|
1770 | 1764 | if pre == self.ESC_QUOTE: |
|
1771 | 1765 | # Auto-quote splitting on whitespace |
|
1772 | 1766 | newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) ) |
|
1773 | 1767 | elif pre == self.ESC_QUOTE2: |
|
1774 | 1768 | # Auto-quote whole string |
|
1775 | 1769 | newcmd = '%s("%s")' % (iFun,theRest) |
|
1776 | 1770 | else: |
|
1777 | 1771 | # Auto-paren |
|
1778 | 1772 | if theRest[0:1] in ('=','['): |
|
1779 | 1773 | # Don't autocall in these cases. They can be either |
|
1780 | 1774 | # rebindings of an existing callable's name, or item access |
|
1781 | 1775 | # for an object which is BOTH callable and implements |
|
1782 | 1776 | # __getitem__. |
|
1783 | 1777 | return '%s %s' % (iFun,theRest) |
|
1784 | 1778 | if theRest.endswith(';'): |
|
1785 | 1779 | newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1]) |
|
1786 | 1780 | else: |
|
1787 | 1781 | newcmd = '%s(%s)' % (iFun.rstrip(),theRest) |
|
1788 | 1782 | |
|
1789 | 1783 | print >>Term.cout, self.outputcache.prompt1.auto_rewrite() + newcmd |
|
1790 | 1784 | # log what is now valid Python, not the actual user input (without the |
|
1791 | 1785 | # final newline) |
|
1792 | 1786 | self.log(newcmd,continue_prompt) |
|
1793 | 1787 | return newcmd |
|
1794 | 1788 | |
|
1795 | 1789 | def handle_help(self, line, continue_prompt=None, |
|
1796 | 1790 | pre=None,iFun=None,theRest=None): |
|
1797 | 1791 | """Try to get some help for the object. |
|
1798 | 1792 | |
|
1799 | 1793 | obj? or ?obj -> basic information. |
|
1800 | 1794 | obj?? or ??obj -> more details. |
|
1801 | 1795 | """ |
|
1802 | 1796 | |
|
1803 | 1797 | # We need to make sure that we don't process lines which would be |
|
1804 | 1798 | # otherwise valid python, such as "x=1 # what?" |
|
1805 | 1799 | try: |
|
1806 | 1800 | codeop.compile_command(line) |
|
1807 | 1801 | except SyntaxError: |
|
1808 | 1802 | # We should only handle as help stuff which is NOT valid syntax |
|
1809 | 1803 | if line[0]==self.ESC_HELP: |
|
1810 | 1804 | line = line[1:] |
|
1811 | 1805 | elif line[-1]==self.ESC_HELP: |
|
1812 | 1806 | line = line[:-1] |
|
1813 | 1807 | self.log('#?'+line) |
|
1814 | 1808 | self.update_cache(line) |
|
1815 | 1809 | if line: |
|
1816 | 1810 | self.magic_pinfo(line) |
|
1817 | 1811 | else: |
|
1818 | 1812 | page(self.usage,screen_lines=self.rc.screen_length) |
|
1819 | 1813 | return '' # Empty string is needed here! |
|
1820 | 1814 | except: |
|
1821 | 1815 | # Pass any other exceptions through to the normal handler |
|
1822 | 1816 | return self.handle_normal(line,continue_prompt) |
|
1823 | 1817 | else: |
|
1824 | 1818 | # If the code compiles ok, we should handle it normally |
|
1825 | 1819 | return self.handle_normal(line,continue_prompt) |
|
1826 | 1820 | |
|
1827 | 1821 | def handle_emacs(self,line,continue_prompt=None, |
|
1828 | 1822 | pre=None,iFun=None,theRest=None): |
|
1829 | 1823 | """Handle input lines marked by python-mode.""" |
|
1830 | 1824 | |
|
1831 | 1825 | # Currently, nothing is done. Later more functionality can be added |
|
1832 | 1826 | # here if needed. |
|
1833 | 1827 | |
|
1834 | 1828 | # The input cache shouldn't be updated |
|
1835 | 1829 | |
|
1836 | 1830 | return line |
|
1837 | 1831 | |
|
1838 | 1832 | def write(self,data): |
|
1839 | 1833 | """Write a string to the default output""" |
|
1840 | 1834 | Term.cout.write(data) |
|
1841 | 1835 | |
|
1842 | 1836 | def write_err(self,data): |
|
1843 | 1837 | """Write a string to the default error output""" |
|
1844 | 1838 | Term.cerr.write(data) |
|
1845 | 1839 | |
|
1846 | 1840 | def exit(self): |
|
1847 | 1841 | """Handle interactive exit. |
|
1848 | 1842 | |
|
1849 | 1843 | This method sets the exit_now attribute.""" |
|
1850 | 1844 | |
|
1851 | 1845 | if self.rc.confirm_exit: |
|
1852 | 1846 | if ask_yes_no('Do you really want to exit ([y]/n)?','y'): |
|
1853 | 1847 | self.exit_now = True |
|
1854 | 1848 | else: |
|
1855 | 1849 | self.exit_now = True |
|
1856 | 1850 | return self.exit_now |
|
1857 | 1851 | |
|
1858 | 1852 | def safe_execfile(self,fname,*where,**kw): |
|
1859 | 1853 | fname = os.path.expanduser(fname) |
|
1860 | 1854 | |
|
1861 | 1855 | # find things also in current directory |
|
1862 | 1856 | dname = os.path.dirname(fname) |
|
1863 | 1857 | if not sys.path.count(dname): |
|
1864 | 1858 | sys.path.append(dname) |
|
1865 | 1859 | |
|
1866 | 1860 | try: |
|
1867 | 1861 | xfile = open(fname) |
|
1868 | 1862 | except: |
|
1869 | 1863 | print >> Term.cerr, \ |
|
1870 | 1864 | 'Could not open file <%s> for safe execution.' % fname |
|
1871 | 1865 | return None |
|
1872 | 1866 | |
|
1873 | 1867 | kw.setdefault('islog',0) |
|
1874 | 1868 | kw.setdefault('quiet',1) |
|
1875 | 1869 | kw.setdefault('exit_ignore',0) |
|
1876 | 1870 | first = xfile.readline() |
|
1877 | 1871 | _LOGHEAD = str(self.LOGHEAD).split('\n',1)[0].strip() |
|
1878 | 1872 | xfile.close() |
|
1879 | 1873 | # line by line execution |
|
1880 | 1874 | if first.startswith(_LOGHEAD) or kw['islog']: |
|
1881 | 1875 | print 'Loading log file <%s> one line at a time...' % fname |
|
1882 | 1876 | if kw['quiet']: |
|
1883 | 1877 | stdout_save = sys.stdout |
|
1884 | 1878 | sys.stdout = StringIO.StringIO() |
|
1885 | 1879 | try: |
|
1886 | 1880 | globs,locs = where[0:2] |
|
1887 | 1881 | except: |
|
1888 | 1882 | try: |
|
1889 | 1883 | globs = locs = where[0] |
|
1890 | 1884 | except: |
|
1891 | 1885 | globs = locs = globals() |
|
1892 | 1886 | badblocks = [] |
|
1893 | 1887 | |
|
1894 | 1888 | # we also need to identify indented blocks of code when replaying |
|
1895 | 1889 | # logs and put them together before passing them to an exec |
|
1896 | 1890 | # statement. This takes a bit of regexp and look-ahead work in the |
|
1897 | 1891 | # file. It's easiest if we swallow the whole thing in memory |
|
1898 | 1892 | # first, and manually walk through the lines list moving the |
|
1899 | 1893 | # counter ourselves. |
|
1900 | 1894 | indent_re = re.compile('\s+\S') |
|
1901 | 1895 | xfile = open(fname) |
|
1902 | 1896 | filelines = xfile.readlines() |
|
1903 | 1897 | xfile.close() |
|
1904 | 1898 | nlines = len(filelines) |
|
1905 | 1899 | lnum = 0 |
|
1906 | 1900 | while lnum < nlines: |
|
1907 | 1901 | line = filelines[lnum] |
|
1908 | 1902 | lnum += 1 |
|
1909 | 1903 | # don't re-insert logger status info into cache |
|
1910 | 1904 | if line.startswith('#log#'): |
|
1911 | 1905 | continue |
|
1912 | 1906 | elif line.startswith('#%s'% self.ESC_MAGIC): |
|
1913 | 1907 | self.update_cache(line[1:]) |
|
1914 | 1908 | line = magic2python(line) |
|
1915 | 1909 | elif line.startswith('#!'): |
|
1916 | 1910 | self.update_cache(line[1:]) |
|
1917 | 1911 | else: |
|
1918 | 1912 | # build a block of code (maybe a single line) for execution |
|
1919 | 1913 | block = line |
|
1920 | 1914 | try: |
|
1921 | 1915 | next = filelines[lnum] # lnum has already incremented |
|
1922 | 1916 | except: |
|
1923 | 1917 | next = None |
|
1924 | 1918 | while next and indent_re.match(next): |
|
1925 | 1919 | block += next |
|
1926 | 1920 | lnum += 1 |
|
1927 | 1921 | try: |
|
1928 | 1922 | next = filelines[lnum] |
|
1929 | 1923 | except: |
|
1930 | 1924 | next = None |
|
1931 | 1925 | # now execute the block of one or more lines |
|
1932 | 1926 | try: |
|
1933 | 1927 | exec block in globs,locs |
|
1934 | 1928 | self.update_cache(block.rstrip()) |
|
1935 | 1929 | except SystemExit: |
|
1936 | 1930 | pass |
|
1937 | 1931 | except: |
|
1938 | 1932 | badblocks.append(block.rstrip()) |
|
1939 | 1933 | if kw['quiet']: # restore stdout |
|
1940 | 1934 | sys.stdout.close() |
|
1941 | 1935 | sys.stdout = stdout_save |
|
1942 | 1936 | print 'Finished replaying log file <%s>' % fname |
|
1943 | 1937 | if badblocks: |
|
1944 | 1938 | print >> sys.stderr, ('\nThe following lines/blocks in file ' |
|
1945 | 1939 | '<%s> reported errors:' % fname) |
|
1946 | 1940 | |
|
1947 | 1941 | for badline in badblocks: |
|
1948 | 1942 | print >> sys.stderr, badline |
|
1949 | 1943 | else: # regular file execution |
|
1950 | 1944 | try: |
|
1951 | 1945 | execfile(fname,*where) |
|
1952 | 1946 | except SyntaxError: |
|
1953 | 1947 | etype, evalue = sys.exc_info()[0:2] |
|
1954 | 1948 | self.SyntaxTB(etype,evalue,[]) |
|
1955 | 1949 | warn('Failure executing file: <%s>' % fname) |
|
1956 | 1950 | except SystemExit,status: |
|
1957 | 1951 | if not kw['exit_ignore']: |
|
1958 | 1952 | self.InteractiveTB() |
|
1959 | 1953 | warn('Failure executing file: <%s>' % fname) |
|
1960 | 1954 | except: |
|
1961 | 1955 | self.InteractiveTB() |
|
1962 | 1956 | warn('Failure executing file: <%s>' % fname) |
|
1963 | 1957 | |
|
1964 | 1958 | #************************* end of file <iplib.py> ***************************** |
|
1 | NO CONTENT: modified file | |
The requested commit or file is too big and content was truncated. Show full diff |
|
1 | NO CONTENT: modified file | |
The requested commit or file is too big and content was truncated. Show full diff |
General Comments 0
You need to be logged in to leave comments.
Login now