Show More
The requested changes are too big and content was truncated. Show full diff
@@ -1,2473 +1,2474 b'' | |||
|
1 | 1 | # -*- coding: utf-8 -*- |
|
2 | 2 | """Magic functions for InteractiveShell. |
|
3 | 3 | |
|
4 |
$Id: Magic.py 90 |
|
|
4 | $Id: Magic.py 907 2005-09-24 00:59:56Z 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 os,sys,inspect,pydoc,re,tempfile,pdb,bdb,time |
|
25 | 25 | try: |
|
26 | 26 | import profile,pstats |
|
27 | 27 | except ImportError: |
|
28 | 28 | profile = pstats = None |
|
29 | 29 | from getopt import getopt |
|
30 | 30 | from pprint import pprint, pformat |
|
31 | 31 | from cStringIO import StringIO |
|
32 | 32 | |
|
33 | 33 | # Homebrewed |
|
34 | 34 | from IPython.Struct import Struct |
|
35 | 35 | from IPython.Itpl import Itpl, itpl, printpl,itplns |
|
36 | 36 | from IPython.FakeModule import FakeModule |
|
37 | 37 | from IPython import OInspect |
|
38 | 38 | from IPython.PyColorize import Parser |
|
39 | 39 | from IPython.genutils import * |
|
40 | 40 | |
|
41 | 41 | # Globals to be set later by Magic constructor |
|
42 | 42 | MAGIC_PREFIX = '' |
|
43 | 43 | MAGIC_ESCAPE = '' |
|
44 | 44 | |
|
45 | 45 | #*************************************************************************** |
|
46 | 46 | # Utility functions |
|
47 | 47 | def magic2python(cmd): |
|
48 | 48 | """Convert a command string of magic syntax to valid Python code.""" |
|
49 | 49 | |
|
50 | 50 | if cmd.startswith('#'+MAGIC_ESCAPE) or \ |
|
51 | 51 | cmd.startswith(MAGIC_ESCAPE): |
|
52 | 52 | if cmd[0]=='#': |
|
53 | 53 | cmd = cmd[1:] |
|
54 | 54 | # we need to return the proper line end later |
|
55 | 55 | if cmd[-1] == '\n': |
|
56 | 56 | endl = '\n' |
|
57 | 57 | else: |
|
58 | 58 | endl = '' |
|
59 | 59 | try: |
|
60 | 60 | func,args = cmd[1:].split(' ',1) |
|
61 | 61 | except: |
|
62 | 62 | func,args = cmd[1:].rstrip(),'' |
|
63 | 63 | args = args.replace('"','\\"').replace("'","\\'").rstrip() |
|
64 | 64 | return '%s%s ("%s")%s' % (MAGIC_PREFIX,func,args,endl) |
|
65 | 65 | else: |
|
66 | 66 | return cmd |
|
67 | 67 | |
|
68 | 68 | def on_off(tag): |
|
69 | 69 | """Return an ON/OFF string for a 1/0 input. Simple utility function.""" |
|
70 | 70 | return ['OFF','ON'][tag] |
|
71 | 71 | |
|
72 | 72 | def get_py_filename(name): |
|
73 | 73 | """Return a valid python filename in the current directory. |
|
74 | 74 | |
|
75 | 75 | If the given name is not a file, it adds '.py' and searches again. |
|
76 | 76 | Raises IOError with an informative message if the file isn't found.""" |
|
77 | 77 | |
|
78 | 78 | name = os.path.expanduser(name) |
|
79 | 79 | if not os.path.isfile(name) and not name.endswith('.py'): |
|
80 | 80 | name += '.py' |
|
81 | 81 | if os.path.isfile(name): |
|
82 | 82 | return name |
|
83 | 83 | else: |
|
84 | 84 | raise IOError,'File `%s` not found.' % name |
|
85 | 85 | |
|
86 | 86 | |
|
87 | 87 | #**************************************************************************** |
|
88 | 88 | # Utility classes |
|
89 | 89 | class Macro: |
|
90 | 90 | """Simple class to store the value of macros as strings. |
|
91 | 91 | |
|
92 | 92 | This allows us to later exec them by checking when something is an |
|
93 | 93 | instance of this class.""" |
|
94 | 94 | |
|
95 | 95 | def __init__(self,cmds): |
|
96 | 96 | """Build a macro from a list of commands.""" |
|
97 | 97 | |
|
98 | 98 | # Since the list may include multi-line entries, first make sure that |
|
99 | 99 | # they've been all broken up before passing it to magic2python |
|
100 | 100 | cmdlist = map(magic2python,''.join(cmds).split('\n')) |
|
101 | 101 | self.value = '\n'.join(cmdlist) |
|
102 | 102 | |
|
103 | 103 | def __str__(self): |
|
104 | 104 | return self.value |
|
105 | 105 | |
|
106 | 106 | #*************************************************************************** |
|
107 | 107 | # Main class implementing Magic functionality |
|
108 | 108 | class Magic: |
|
109 | 109 | """Magic functions for InteractiveShell. |
|
110 | 110 | |
|
111 | 111 | Shell functions which can be reached as %function_name. All magic |
|
112 | 112 | functions should accept a string, which they can parse for their own |
|
113 | 113 | needs. This can make some functions easier to type, eg `%cd ../` |
|
114 | 114 | vs. `%cd("../")` |
|
115 | 115 | |
|
116 | 116 | ALL definitions MUST begin with the prefix magic_. The user won't need it |
|
117 | 117 | at the command line, but it is is needed in the definition. """ |
|
118 | 118 | |
|
119 | 119 | # class globals |
|
120 | 120 | auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.', |
|
121 | 121 | 'Automagic is ON, % prefix NOT needed for magic functions.'] |
|
122 | 122 | |
|
123 | 123 | #...................................................................... |
|
124 | 124 | # some utility functions |
|
125 | 125 | |
|
126 | 126 | def __init__(self,shell): |
|
127 | 127 | # XXX This is hackish, clean up later to avoid these messy globals |
|
128 | 128 | global MAGIC_PREFIX, MAGIC_ESCAPE |
|
129 | 129 | |
|
130 | 130 | self.options_table = {} |
|
131 | 131 | MAGIC_PREFIX = shell.name+'.magic_' |
|
132 | 132 | MAGIC_ESCAPE = shell.ESC_MAGIC |
|
133 | 133 | if profile is None: |
|
134 | 134 | self.magic_prun = self.profile_missing_notice |
|
135 | 135 | |
|
136 | 136 | def profile_missing_notice(self, *args, **kwargs): |
|
137 | 137 | error("""\ |
|
138 | 138 | The profile module could not be found. If you are a Debian user, |
|
139 | 139 | it has been removed from the standard Debian package because of its non-free |
|
140 | 140 | license. To use profiling, please install"python2.3-profiler" from non-free.""") |
|
141 | 141 | |
|
142 | 142 | def default_option(self,fn,optstr): |
|
143 | 143 | """Make an entry in the options_table for fn, with value optstr""" |
|
144 | 144 | |
|
145 | 145 | if fn not in self.lsmagic(): |
|
146 | 146 | error("%s is not a magic function" % fn) |
|
147 | 147 | self.options_table[fn] = optstr |
|
148 | 148 | |
|
149 | 149 | def lsmagic(self): |
|
150 | 150 | """Return a list of currently available magic functions. |
|
151 | 151 | |
|
152 | 152 | Gives a list of the bare names after mangling (['ls','cd', ...], not |
|
153 | 153 | ['magic_ls','magic_cd',...]""" |
|
154 | 154 | |
|
155 | 155 | # FIXME. This needs a cleanup, in the way the magics list is built. |
|
156 | 156 | |
|
157 | 157 | # magics in class definition |
|
158 | 158 | class_magic = lambda fn: fn.startswith('magic_') and \ |
|
159 | 159 | callable(Magic.__dict__[fn]) |
|
160 | 160 | # in instance namespace (run-time user additions) |
|
161 | 161 | inst_magic = lambda fn: fn.startswith('magic_') and \ |
|
162 | 162 | callable(self.__dict__[fn]) |
|
163 | 163 | # and bound magics by user (so they can access self): |
|
164 | 164 | inst_bound_magic = lambda fn: fn.startswith('magic_') and \ |
|
165 | 165 | callable(self.__class__.__dict__[fn]) |
|
166 | 166 | magics = filter(class_magic,Magic.__dict__.keys()) + \ |
|
167 | 167 | filter(inst_magic,self.__dict__.keys()) + \ |
|
168 | 168 | filter(inst_bound_magic,self.__class__.__dict__.keys()) |
|
169 | 169 | out = [] |
|
170 | 170 | for fn in magics: |
|
171 | 171 | out.append(fn.replace('magic_','',1)) |
|
172 | 172 | out.sort() |
|
173 | 173 | return out |
|
174 | 174 | |
|
175 | 175 | def set_shell(self,shell): |
|
176 | 176 | self.shell = shell |
|
177 | 177 | self.alias_table = shell.alias_table |
|
178 | 178 | |
|
179 | 179 | def extract_input_slices(self,slices): |
|
180 | 180 | """Return as a string a set of input history slices. |
|
181 | 181 | |
|
182 | 182 | The set of slices is given as a list of strings (like ['1','4:8','9'], |
|
183 | 183 | since this function is for use by magic functions which get their |
|
184 | 184 | arguments as strings.""" |
|
185 | 185 | |
|
186 | 186 | cmds = [] |
|
187 | 187 | for chunk in slices: |
|
188 | 188 | if ':' in chunk: |
|
189 | 189 | ini,fin = map(int,chunk.split(':')) |
|
190 | 190 | else: |
|
191 | 191 | ini = int(chunk) |
|
192 | 192 | fin = ini+1 |
|
193 | 193 | cmds.append(self.shell.input_hist[ini:fin]) |
|
194 | 194 | return cmds |
|
195 | 195 | |
|
196 | 196 | def _ofind(self,oname): |
|
197 | 197 | """Find an object in the available namespaces. |
|
198 | 198 | |
|
199 | 199 | self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic |
|
200 | 200 | |
|
201 | 201 | Has special code to detect magic functions. |
|
202 | 202 | """ |
|
203 | 203 | |
|
204 | 204 | oname = oname.strip() |
|
205 | 205 | |
|
206 | 206 | # Namespaces to search in: |
|
207 | 207 | user_ns = self.shell.user_ns |
|
208 | 208 | internal_ns = self.shell.internal_ns |
|
209 | 209 | builtin_ns = __builtin__.__dict__ |
|
210 | 210 | alias_ns = self.shell.alias_table |
|
211 | 211 | |
|
212 | 212 | # Put them in a list. The order is important so that we find things in |
|
213 | 213 | # the same order that Python finds them. |
|
214 | 214 | namespaces = [ ('Interactive',user_ns), |
|
215 | 215 | ('IPython internal',internal_ns), |
|
216 | 216 | ('Python builtin',builtin_ns), |
|
217 | 217 | ('Alias',alias_ns), |
|
218 | 218 | ] |
|
219 | 219 | |
|
220 | 220 | # initialize results to 'null' |
|
221 | 221 | found = 0; obj = None; ospace = None; ds = None; |
|
222 | 222 | ismagic = 0; isalias = 0 |
|
223 | 223 | |
|
224 | 224 | # Look for the given name by splitting it in parts. If the head is |
|
225 | 225 | # found, then we look for all the remaining parts as members, and only |
|
226 | 226 | # declare success if we can find them all. |
|
227 | 227 | oname_parts = oname.split('.') |
|
228 | 228 | oname_head, oname_rest = oname_parts[0],oname_parts[1:] |
|
229 | 229 | for nsname,ns in namespaces: |
|
230 | 230 | try: |
|
231 | 231 | obj = ns[oname_head] |
|
232 | 232 | except KeyError: |
|
233 | 233 | continue |
|
234 | 234 | else: |
|
235 | 235 | for part in oname_rest: |
|
236 | 236 | try: |
|
237 | 237 | obj = getattr(obj,part) |
|
238 | 238 | except: |
|
239 | 239 | # Blanket except b/c some badly implemented objects |
|
240 | 240 | # allow __getattr__ to raise exceptions other than |
|
241 | 241 | # AttributeError, which then crashes IPython. |
|
242 | 242 | break |
|
243 | 243 | else: |
|
244 | 244 | # If we finish the for loop (no break), we got all members |
|
245 | 245 | found = 1 |
|
246 | 246 | ospace = nsname |
|
247 | 247 | if ns == alias_ns: |
|
248 | 248 | isalias = 1 |
|
249 | 249 | break # namespace loop |
|
250 | 250 | |
|
251 | 251 | # Try to see if it's magic |
|
252 | 252 | if not found: |
|
253 | 253 | if oname.startswith(self.shell.ESC_MAGIC): |
|
254 | 254 | oname = oname[1:] |
|
255 | 255 | obj = getattr(self,'magic_'+oname,None) |
|
256 | 256 | if obj is not None: |
|
257 | 257 | found = 1 |
|
258 | 258 | ospace = 'IPython internal' |
|
259 | 259 | ismagic = 1 |
|
260 | 260 | |
|
261 | 261 | # Last try: special-case some literals like '', [], {}, etc: |
|
262 | 262 | if not found and oname_head in ["''",'""','[]','{}','()']: |
|
263 | 263 | obj = eval(oname_head) |
|
264 | 264 | found = 1 |
|
265 | 265 | ospace = 'Interactive' |
|
266 | 266 | |
|
267 | 267 | return {'found':found, 'obj':obj, 'namespace':ospace, |
|
268 | 268 | 'ismagic':ismagic, 'isalias':isalias} |
|
269 | 269 | |
|
270 | 270 | def arg_err(self,func): |
|
271 | 271 | """Print docstring if incorrect arguments were passed""" |
|
272 | 272 | print 'Error in arguments:' |
|
273 | 273 | print OInspect.getdoc(func) |
|
274 | 274 | |
|
275 | 275 | |
|
276 | 276 | def format_latex(self,str): |
|
277 | 277 | """Format a string for latex inclusion.""" |
|
278 | 278 | |
|
279 | 279 | # Characters that need to be escaped for latex: |
|
280 | 280 | escape_re = re.compile(r'(%|_|\$)',re.MULTILINE) |
|
281 | 281 | # Magic command names as headers: |
|
282 | 282 | cmd_name_re = re.compile(r'^(%s.*?):' % self.shell.ESC_MAGIC, |
|
283 | 283 | re.MULTILINE) |
|
284 | 284 | # Magic commands |
|
285 | 285 | cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % self.shell.ESC_MAGIC, |
|
286 | 286 | re.MULTILINE) |
|
287 | 287 | # Paragraph continue |
|
288 | 288 | par_re = re.compile(r'\\$',re.MULTILINE) |
|
289 | 289 | |
|
290 | 290 | str = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',str) |
|
291 | 291 | str = cmd_re.sub(r'\\texttt{\g<cmd>}',str) |
|
292 | 292 | str = par_re.sub(r'\\\\',str) |
|
293 | 293 | str = escape_re.sub(r'\\\1',str) |
|
294 | 294 | return str |
|
295 | 295 | |
|
296 | 296 | def format_screen(self,str): |
|
297 | 297 | """Format a string for screen printing. |
|
298 | 298 | |
|
299 | 299 | This removes some latex-type format codes.""" |
|
300 | 300 | # Paragraph continue |
|
301 | 301 | par_re = re.compile(r'\\$',re.MULTILINE) |
|
302 | 302 | str = par_re.sub('',str) |
|
303 | 303 | return str |
|
304 | 304 | |
|
305 | 305 | def parse_options(self,arg_str,opt_str,*long_opts,**kw): |
|
306 | 306 | """Parse options passed to an argument string. |
|
307 | 307 | |
|
308 | 308 | The interface is similar to that of getopt(), but it returns back a |
|
309 | 309 | Struct with the options as keys and the stripped argument string still |
|
310 | 310 | as a string. |
|
311 | 311 | |
|
312 | 312 | arg_str is quoted as a true sys.argv vector by calling on the fly a |
|
313 | 313 | python process in a subshell. This allows us to easily expand |
|
314 | 314 | variables, glob files, quote arguments, etc, with all the power and |
|
315 | 315 | correctness of the underlying system shell. |
|
316 | 316 | |
|
317 | 317 | Options: |
|
318 | 318 | -mode: default 'string'. If given as 'list', the argument string is |
|
319 | 319 | returned as a list (split on whitespace) instead of a string. |
|
320 | 320 | |
|
321 | 321 | -list_all: put all option values in lists. Normally only options |
|
322 | 322 | appearing more than once are put in a list.""" |
|
323 | 323 | |
|
324 | 324 | # inject default options at the beginning of the input line |
|
325 | 325 | caller = sys._getframe(1).f_code.co_name.replace('magic_','') |
|
326 | 326 | arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str) |
|
327 | 327 | |
|
328 | 328 | mode = kw.get('mode','string') |
|
329 | 329 | if mode not in ['string','list']: |
|
330 | 330 | raise ValueError,'incorrect mode given: %s' % mode |
|
331 | 331 | # Get options |
|
332 | 332 | list_all = kw.get('list_all',0) |
|
333 | 333 | |
|
334 | 334 | # Check if we have more than one argument to warrant extra processing: |
|
335 | 335 | odict = {} # Dictionary with options |
|
336 | 336 | args = arg_str.split() |
|
337 | 337 | if len(args) >= 1: |
|
338 | 338 | # If the list of inputs only has 0 or 1 thing in it, there's no |
|
339 | 339 | # need to look for options |
|
340 | 340 | argv = shlex_split(arg_str) |
|
341 | 341 | # Do regular option processing |
|
342 | 342 | opts,args = getopt(argv,opt_str,*long_opts) |
|
343 | 343 | for o,a in opts: |
|
344 | 344 | if o.startswith('--'): |
|
345 | 345 | o = o[2:] |
|
346 | 346 | else: |
|
347 | 347 | o = o[1:] |
|
348 | 348 | try: |
|
349 | 349 | odict[o].append(a) |
|
350 | 350 | except AttributeError: |
|
351 | 351 | odict[o] = [odict[o],a] |
|
352 | 352 | except KeyError: |
|
353 | 353 | if list_all: |
|
354 | 354 | odict[o] = [a] |
|
355 | 355 | else: |
|
356 | 356 | odict[o] = a |
|
357 | 357 | |
|
358 | 358 | # Prepare opts,args for return |
|
359 | 359 | opts = Struct(odict) |
|
360 | 360 | if mode == 'string': |
|
361 | 361 | args = ' '.join(args) |
|
362 | 362 | |
|
363 | 363 | return opts,args |
|
364 | 364 | |
|
365 | 365 | #...................................................................... |
|
366 | 366 | # And now the actual magic functions |
|
367 | 367 | |
|
368 | 368 | # Functions for IPython shell work (vars,funcs, config, etc) |
|
369 | 369 | def magic_lsmagic(self, parameter_s = ''): |
|
370 | 370 | """List currently available magic functions.""" |
|
371 | 371 | mesc = self.shell.ESC_MAGIC |
|
372 | 372 | print 'Available magic functions:\n'+mesc+\ |
|
373 | 373 | (' '+mesc).join(self.lsmagic()) |
|
374 | 374 | print '\n' + Magic.auto_status[self.shell.rc.automagic] |
|
375 | 375 | return None |
|
376 | 376 | |
|
377 | 377 | def magic_magic(self, parameter_s = ''): |
|
378 | 378 | """Print information about the magic function system.""" |
|
379 | 379 | |
|
380 | 380 | mode = '' |
|
381 | 381 | try: |
|
382 | 382 | if parameter_s.split()[0] == '-latex': |
|
383 | 383 | mode = 'latex' |
|
384 | 384 | except: |
|
385 | 385 | pass |
|
386 | 386 | |
|
387 | 387 | magic_docs = [] |
|
388 | 388 | for fname in self.lsmagic(): |
|
389 | 389 | mname = 'magic_' + fname |
|
390 | 390 | for space in (Magic,self,self.__class__): |
|
391 | 391 | try: |
|
392 | 392 | fn = space.__dict__[mname] |
|
393 | 393 | except KeyError: |
|
394 | 394 | pass |
|
395 | 395 | else: |
|
396 | 396 | break |
|
397 | 397 | magic_docs.append('%s%s:\n\t%s\n' %(self.shell.ESC_MAGIC, |
|
398 | 398 | fname,fn.__doc__)) |
|
399 | 399 | magic_docs = ''.join(magic_docs) |
|
400 | 400 | |
|
401 | 401 | if mode == 'latex': |
|
402 | 402 | print self.format_latex(magic_docs) |
|
403 | 403 | return |
|
404 | 404 | else: |
|
405 | 405 | magic_docs = self.format_screen(magic_docs) |
|
406 | 406 | |
|
407 | 407 | outmsg = """ |
|
408 | 408 | IPython's 'magic' functions |
|
409 | 409 | =========================== |
|
410 | 410 | |
|
411 | 411 | The magic function system provides a series of functions which allow you to |
|
412 | 412 | control the behavior of IPython itself, plus a lot of system-type |
|
413 | 413 | features. All these functions are prefixed with a % character, but parameters |
|
414 | 414 | are given without parentheses or quotes. |
|
415 | 415 | |
|
416 | 416 | NOTE: If you have 'automagic' enabled (via the command line option or with the |
|
417 | 417 | %automagic function), you don't need to type in the % explicitly. By default, |
|
418 | 418 | IPython ships with automagic on, so you should only rarely need the % escape. |
|
419 | 419 | |
|
420 | 420 | Example: typing '%cd mydir' (without the quotes) changes you working directory |
|
421 | 421 | to 'mydir', if it exists. |
|
422 | 422 | |
|
423 | 423 | You can define your own magic functions to extend the system. See the supplied |
|
424 | 424 | ipythonrc and example-magic.py files for details (in your ipython |
|
425 | 425 | configuration directory, typically $HOME/.ipython/). |
|
426 | 426 | |
|
427 | 427 | You can also define your own aliased names for magic functions. In your |
|
428 | 428 | ipythonrc file, placing a line like: |
|
429 | 429 | |
|
430 | 430 | execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile |
|
431 | 431 | |
|
432 | 432 | will define %pf as a new name for %profile. |
|
433 | 433 | |
|
434 | 434 | You can also call magics in code using the ipmagic() function, which IPython |
|
435 | 435 | automatically adds to the builtin namespace. Type 'ipmagic?' for details. |
|
436 | 436 | |
|
437 | 437 | For a list of the available magic functions, use %lsmagic. For a description |
|
438 | 438 | of any of them, type %magic_name?, e.g. '%cd?'. |
|
439 | 439 | |
|
440 | 440 | Currently the magic system has the following functions:\n""" |
|
441 | 441 | |
|
442 | 442 | mesc = self.shell.ESC_MAGIC |
|
443 | 443 | outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):" |
|
444 | 444 | "\n\n%s%s\n\n%s" % (outmsg, |
|
445 | 445 | magic_docs,mesc,mesc, |
|
446 | 446 | (' '+mesc).join(self.lsmagic()), |
|
447 | 447 | Magic.auto_status[self.shell.rc.automagic] ) ) |
|
448 | 448 | |
|
449 | 449 | page(outmsg,screen_lines=self.shell.rc.screen_length) |
|
450 | 450 | |
|
451 | 451 | def magic_automagic(self, parameter_s = ''): |
|
452 | 452 | """Make magic functions callable without having to type the initial %. |
|
453 | 453 | |
|
454 | 454 | Toggles on/off (when off, you must call it as %automagic, of |
|
455 | 455 | course). Note that magic functions have lowest priority, so if there's |
|
456 | 456 | a variable whose name collides with that of a magic fn, automagic |
|
457 | 457 | won't work for that function (you get the variable instead). However, |
|
458 | 458 | if you delete the variable (del var), the previously shadowed magic |
|
459 | 459 | function becomes visible to automagic again.""" |
|
460 | 460 | |
|
461 | 461 | rc = self.shell.rc |
|
462 | 462 | rc.automagic = not rc.automagic |
|
463 | 463 | print '\n' + Magic.auto_status[rc.automagic] |
|
464 | 464 | |
|
465 | 465 | def magic_autocall(self, parameter_s = ''): |
|
466 | 466 | """Make functions callable without having to type parentheses. |
|
467 | 467 | |
|
468 | 468 | This toggles the autocall command line option on and off.""" |
|
469 | 469 | |
|
470 | 470 | rc = self.shell.rc |
|
471 | 471 | rc.autocall = not rc.autocall |
|
472 | 472 | print "Automatic calling is:",['OFF','ON'][rc.autocall] |
|
473 | 473 | |
|
474 | 474 | def magic_autoindent(self, parameter_s = ''): |
|
475 | 475 | """Toggle autoindent on/off (if available).""" |
|
476 | 476 | |
|
477 | 477 | self.shell.set_autoindent() |
|
478 | 478 | print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent] |
|
479 | 479 | |
|
480 | 480 | def magic_system_verbose(self, parameter_s = ''): |
|
481 | 481 | """Toggle verbose printing of system calls on/off.""" |
|
482 | 482 | |
|
483 | 483 | self.shell.rc_set_toggle('system_verbose') |
|
484 | 484 | print "System verbose printing is:",\ |
|
485 | 485 | ['OFF','ON'][self.shell.rc.system_verbose] |
|
486 | 486 | |
|
487 | 487 | def magic_history(self, parameter_s = ''): |
|
488 | 488 | """Print input history (_i<n> variables), with most recent last. |
|
489 | 489 | |
|
490 | 490 | %history [-n] -> print at most 40 inputs (some may be multi-line)\\ |
|
491 | 491 | %history [-n] n -> print at most n inputs\\ |
|
492 | 492 | %history [-n] n1 n2 -> print inputs between n1 and n2 (n2 not included)\\ |
|
493 | 493 | |
|
494 | 494 | Each input's number <n> is shown, and is accessible as the |
|
495 | 495 | automatically generated variable _i<n>. Multi-line statements are |
|
496 | 496 | printed starting at a new line for easy copy/paste. |
|
497 | 497 | |
|
498 | 498 | If option -n is used, input numbers are not printed. This is useful if |
|
499 | 499 | you want to get a printout of many lines which can be directly pasted |
|
500 | 500 | into a text editor. |
|
501 | 501 | |
|
502 | 502 | This feature is only available if numbered prompts are in use.""" |
|
503 | 503 | |
|
504 | 504 | if not self.do_full_cache: |
|
505 | 505 | print 'This feature is only available if numbered prompts are in use.' |
|
506 | 506 | return |
|
507 | 507 | opts,args = self.parse_options(parameter_s,'n',mode='list') |
|
508 | 508 | |
|
509 | 509 | default_length = 40 |
|
510 | 510 | if len(args) == 0: |
|
511 | 511 | final = self.outputcache.prompt_count |
|
512 | 512 | init = max(1,final-default_length) |
|
513 | 513 | elif len(args) == 1: |
|
514 | 514 | final = self.outputcache.prompt_count |
|
515 | 515 | init = max(1,final-int(args[0])) |
|
516 | 516 | elif len(args) == 2: |
|
517 | 517 | init,final = map(int,args) |
|
518 | 518 | else: |
|
519 | 519 | warn('%hist takes 0, 1 or 2 arguments separated by spaces.') |
|
520 | 520 | print self.magic_hist.__doc__ |
|
521 | 521 | return |
|
522 | 522 | width = len(str(final)) |
|
523 | 523 | line_sep = ['','\n'] |
|
524 | 524 | input_hist = self.shell.input_hist |
|
525 | 525 | print_nums = not opts.has_key('n') |
|
526 | 526 | for in_num in range(init,final): |
|
527 | 527 | inline = input_hist[in_num] |
|
528 | 528 | multiline = inline.count('\n') > 1 |
|
529 | 529 | if print_nums: |
|
530 | 530 | print str(in_num).ljust(width)+':'+ line_sep[multiline], |
|
531 | 531 | if inline.startswith('#'+self.shell.ESC_MAGIC) or \ |
|
532 | 532 | inline.startswith('#!'): |
|
533 | 533 | print inline[1:], |
|
534 | 534 | else: |
|
535 | 535 | print inline, |
|
536 | 536 | |
|
537 | 537 | def magic_hist(self, parameter_s=''): |
|
538 | 538 | """Alternate name for %history.""" |
|
539 | 539 | return self.magic_history(parameter_s) |
|
540 | 540 | |
|
541 | 541 | def magic_p(self, parameter_s=''): |
|
542 | 542 | """Just a short alias for Python's 'print'.""" |
|
543 | 543 | exec 'print ' + parameter_s in self.shell.user_ns |
|
544 | 544 | |
|
545 | 545 | def magic_r(self, parameter_s=''): |
|
546 | 546 | """Repeat previous input. |
|
547 | 547 | |
|
548 | 548 | If given an argument, repeats the previous command which starts with |
|
549 | 549 | the same string, otherwise it just repeats the previous input. |
|
550 | 550 | |
|
551 | 551 | Shell escaped commands (with ! as first character) are not recognized |
|
552 | 552 | by this system, only pure python code and magic commands. |
|
553 | 553 | """ |
|
554 | 554 | |
|
555 | 555 | start = parameter_s.strip() |
|
556 | 556 | esc_magic = self.shell.ESC_MAGIC |
|
557 | 557 | # Identify magic commands even if automagic is on (which means |
|
558 | 558 | # the in-memory version is different from that typed by the user). |
|
559 | 559 | if self.shell.rc.automagic: |
|
560 | 560 | start_magic = esc_magic+start |
|
561 | 561 | else: |
|
562 | 562 | start_magic = start |
|
563 | 563 | # Look through the input history in reverse |
|
564 | 564 | for n in range(len(self.shell.input_hist)-2,0,-1): |
|
565 | 565 | input = self.shell.input_hist[n] |
|
566 | 566 | # skip plain 'r' lines so we don't recurse to infinity |
|
567 | 567 | if input != 'ipmagic("r")\n' and \ |
|
568 | 568 | (input.startswith(start) or input.startswith(start_magic)): |
|
569 | 569 | #print 'match',`input` # dbg |
|
570 | 570 | if input.startswith(esc_magic): |
|
571 | 571 | input = magic2python(input) |
|
572 | 572 | #print 'modified',`input` # dbg |
|
573 | 573 | print 'Executing:',input, |
|
574 | 574 | exec input in self.shell.user_ns |
|
575 | 575 | return |
|
576 | 576 | print 'No previous input matching `%s` found.' % start |
|
577 | 577 | |
|
578 | 578 | def magic_page(self, parameter_s=''): |
|
579 | 579 | """Pretty print the object and display it through a pager. |
|
580 | 580 | |
|
581 | 581 | If no parameter is given, use _ (last output).""" |
|
582 | 582 | # After a function contributed by Olivier Aubert, slightly modified. |
|
583 | 583 | |
|
584 | 584 | oname = parameter_s and parameter_s or '_' |
|
585 | 585 | info = self._ofind(oname) |
|
586 | 586 | if info['found']: |
|
587 | 587 | page(pformat(info['obj'])) |
|
588 | 588 | else: |
|
589 | 589 | print 'Object `%s` not found' % oname |
|
590 | 590 | |
|
591 | 591 | def magic_profile(self, parameter_s=''): |
|
592 | 592 | """Print your currently active IPyhton profile.""" |
|
593 | 593 | if self.shell.rc.profile: |
|
594 | 594 | printpl('Current IPython profile: $self.shell.rc.profile.') |
|
595 | 595 | else: |
|
596 | 596 | print 'No profile active.' |
|
597 | 597 | |
|
598 | 598 | def _inspect(self,meth,oname,**kw): |
|
599 | 599 | """Generic interface to the inspector system. |
|
600 | 600 | |
|
601 | 601 | This function is meant to be called by pdef, pdoc & friends.""" |
|
602 | 602 | |
|
603 | 603 | oname = oname.strip() |
|
604 | 604 | info = Struct(self._ofind(oname)) |
|
605 | 605 | if info.found: |
|
606 | 606 | pmethod = getattr(self.shell.inspector,meth) |
|
607 | 607 | formatter = info.ismagic and self.format_screen or None |
|
608 | 608 | if meth == 'pdoc': |
|
609 | 609 | pmethod(info.obj,oname,formatter) |
|
610 | 610 | elif meth == 'pinfo': |
|
611 | 611 | pmethod(info.obj,oname,formatter,info,**kw) |
|
612 | 612 | else: |
|
613 | 613 | pmethod(info.obj,oname) |
|
614 | 614 | else: |
|
615 | 615 | print 'Object `%s` not found.' % oname |
|
616 | 616 | return 'not found' # so callers can take other action |
|
617 | 617 | |
|
618 | 618 | def magic_pdef(self, parameter_s=''): |
|
619 | 619 | """Print the definition header for any callable object. |
|
620 | 620 | |
|
621 | 621 | If the object is a class, print the constructor information.""" |
|
622 | 622 | self._inspect('pdef',parameter_s) |
|
623 | 623 | |
|
624 | 624 | def magic_pdoc(self, parameter_s=''): |
|
625 | 625 | """Print the docstring for an object. |
|
626 | 626 | |
|
627 | 627 | If the given object is a class, it will print both the class and the |
|
628 | 628 | constructor docstrings.""" |
|
629 | 629 | self._inspect('pdoc',parameter_s) |
|
630 | 630 | |
|
631 | 631 | def magic_psource(self, parameter_s=''): |
|
632 | 632 | """Print (or run through pager) the source code for an object.""" |
|
633 | 633 | self._inspect('psource',parameter_s) |
|
634 | 634 | |
|
635 | 635 | def magic_pfile(self, parameter_s=''): |
|
636 | 636 | """Print (or run through pager) the file where an object is defined. |
|
637 | 637 | |
|
638 | 638 | The file opens at the line where the object definition begins. IPython |
|
639 | 639 | will honor the environment variable PAGER if set, and otherwise will |
|
640 | 640 | do its best to print the file in a convenient form. |
|
641 | 641 | |
|
642 | 642 | If the given argument is not an object currently defined, IPython will |
|
643 | 643 | try to interpret it as a filename (automatically adding a .py extension |
|
644 | 644 | if needed). You can thus use %pfile as a syntax highlighting code |
|
645 | 645 | viewer.""" |
|
646 | 646 | |
|
647 | 647 | # first interpret argument as an object name |
|
648 | 648 | out = self._inspect('pfile',parameter_s) |
|
649 | 649 | # if not, try the input as a filename |
|
650 | 650 | if out == 'not found': |
|
651 | 651 | try: |
|
652 | 652 | filename = get_py_filename(parameter_s) |
|
653 | 653 | except IOError,msg: |
|
654 | 654 | print msg |
|
655 | 655 | return |
|
656 | 656 | page(self.shell.inspector.format(file(filename).read())) |
|
657 | 657 | |
|
658 | 658 | def magic_pinfo(self, parameter_s=''): |
|
659 | 659 | """Provide detailed information about an object. |
|
660 | 660 | |
|
661 | 661 | '%pinfo object' is just a synonym for object? or ?object.""" |
|
662 | 662 | |
|
663 | 663 | #print 'pinfo par: <%s>' % parameter_s # dbg |
|
664 | 664 | |
|
665 | 665 | # detail_level: 0 -> obj? , 1 -> obj?? |
|
666 | 666 | detail_level = 0 |
|
667 | 667 | # We need to detect if we got called as 'pinfo pinfo foo', which can |
|
668 | 668 | # happen if the user types 'pinfo foo?' at the cmd line. |
|
669 | 669 | pinfo,qmark1,oname,qmark2 = \ |
|
670 | 670 | re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups() |
|
671 | 671 | if pinfo or qmark1 or qmark2: |
|
672 | 672 | detail_level = 1 |
|
673 | 673 | self._inspect('pinfo',oname,detail_level=detail_level) |
|
674 | 674 | |
|
675 | 675 | def magic_who_ls(self, parameter_s=''): |
|
676 | 676 | """Return a sorted list of all interactive variables. |
|
677 | 677 | |
|
678 | 678 | If arguments are given, only variables of types matching these |
|
679 | 679 | arguments are returned.""" |
|
680 | 680 | |
|
681 | 681 | user_ns = self.shell.user_ns |
|
682 | 682 | out = [] |
|
683 | 683 | typelist = parameter_s.split() |
|
684 | 684 | for i in self.shell.user_ns.keys(): |
|
685 | 685 | if not (i.startswith('_') or i.startswith('_i')) \ |
|
686 | 686 | and not (self.internal_ns.has_key(i) or |
|
687 | 687 | self.user_config_ns.has_key(i)): |
|
688 | 688 | if typelist: |
|
689 | 689 | if type(user_ns[i]).__name__ in typelist: |
|
690 | 690 | out.append(i) |
|
691 | 691 | else: |
|
692 | 692 | out.append(i) |
|
693 | 693 | out.sort() |
|
694 | 694 | return out |
|
695 | 695 | |
|
696 | 696 | def magic_who(self, parameter_s=''): |
|
697 | 697 | """Print all interactive variables, with some minimal formatting. |
|
698 | 698 | |
|
699 | 699 | If any arguments are given, only variables whose type matches one of |
|
700 | 700 | these are printed. For example: |
|
701 | 701 | |
|
702 | 702 | %who function str |
|
703 | 703 | |
|
704 | 704 | will only list functions and strings, excluding all other types of |
|
705 | 705 | variables. To find the proper type names, simply use type(var) at a |
|
706 | 706 | command line to see how python prints type names. For example: |
|
707 | 707 | |
|
708 | 708 | In [1]: type('hello')\\ |
|
709 | 709 | Out[1]: <type 'str'> |
|
710 | 710 | |
|
711 | 711 | indicates that the type name for strings is 'str'. |
|
712 | 712 | |
|
713 | 713 | %who always excludes executed names loaded through your configuration |
|
714 | 714 | file and things which are internal to IPython. |
|
715 | 715 | |
|
716 | 716 | This is deliberate, as typically you may load many modules and the |
|
717 | 717 | purpose of %who is to show you only what you've manually defined.""" |
|
718 | 718 | |
|
719 | 719 | varlist = self.magic_who_ls(parameter_s) |
|
720 | 720 | if not varlist: |
|
721 | 721 | print 'Interactive namespace is empty.' |
|
722 | 722 | return |
|
723 | 723 | |
|
724 | 724 | # if we have variables, move on... |
|
725 | 725 | |
|
726 | 726 | # stupid flushing problem: when prompts have no separators, stdout is |
|
727 | 727 | # getting lost. I'm starting to think this is a python bug. I'm having |
|
728 | 728 | # to force a flush with a print because even a sys.stdout.flush |
|
729 | 729 | # doesn't seem to do anything! |
|
730 | 730 | |
|
731 | 731 | count = 0 |
|
732 | 732 | for i in varlist: |
|
733 | 733 | print i+'\t', |
|
734 | 734 | count += 1 |
|
735 | 735 | if count > 8: |
|
736 | 736 | count = 0 |
|
737 | 737 | |
|
738 | 738 | sys.stdout.flush() # FIXME. Why the hell isn't this flushing??? |
|
739 | 739 | |
|
740 | 740 | print # well, this does force a flush at the expense of an extra \n |
|
741 | 741 | |
|
742 | 742 | def magic_whos(self, parameter_s=''): |
|
743 | 743 | """Like %who, but gives some extra information about each variable. |
|
744 | 744 | |
|
745 | 745 | The same type filtering of %who can be applied here. |
|
746 | 746 | |
|
747 | 747 | For all variables, the type is printed. Additionally it prints: |
|
748 | 748 | |
|
749 | 749 | - For {},[],(): their length. |
|
750 | 750 | |
|
751 | 751 | - For Numeric arrays, a summary with shape, number of elements, |
|
752 | 752 | typecode and size in memory. |
|
753 | 753 | |
|
754 | 754 | - Everything else: a string representation, snipping their middle if |
|
755 | 755 | too long.""" |
|
756 | 756 | |
|
757 | 757 | varnames = self.magic_who_ls(parameter_s) |
|
758 | 758 | if not varnames: |
|
759 | 759 | print 'Interactive namespace is empty.' |
|
760 | 760 | return |
|
761 | 761 | |
|
762 | 762 | # if we have variables, move on... |
|
763 | 763 | |
|
764 | 764 | # for these types, show len() instead of data: |
|
765 | 765 | seq_types = [types.DictType,types.ListType,types.TupleType] |
|
766 | 766 | |
|
767 | 767 | # for Numeric arrays, display summary info |
|
768 | 768 | try: |
|
769 | 769 | import Numeric |
|
770 | 770 | except ImportError: |
|
771 | 771 | array_type = None |
|
772 | 772 | else: |
|
773 | 773 | array_type = Numeric.ArrayType.__name__ |
|
774 | 774 | |
|
775 | 775 | # Find all variable names and types so we can figure out column sizes |
|
776 | 776 | get_vars = lambda i: self.locals[i] |
|
777 | 777 | type_name = lambda v: type(v).__name__ |
|
778 | 778 | varlist = map(get_vars,varnames) |
|
779 | 779 | typelist = map(type_name,varlist) |
|
780 | 780 | # column labels and # of spaces as separator |
|
781 | 781 | varlabel = 'Variable' |
|
782 | 782 | typelabel = 'Type' |
|
783 | 783 | datalabel = 'Data/Info' |
|
784 | 784 | colsep = 3 |
|
785 | 785 | # variable format strings |
|
786 | 786 | vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)" |
|
787 | 787 | vfmt_short = '$vstr[:25]<...>$vstr[-25:]' |
|
788 | 788 | aformat = "%s: %s elems, type `%s`, %s bytes" |
|
789 | 789 | # find the size of the columns to format the output nicely |
|
790 | 790 | varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep |
|
791 | 791 | typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep |
|
792 | 792 | # table header |
|
793 | 793 | print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \ |
|
794 | 794 | ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1) |
|
795 | 795 | # and the table itself |
|
796 | 796 | kb = 1024 |
|
797 | 797 | Mb = 1048576 # kb**2 |
|
798 | 798 | for vname,var,vtype in zip(varnames,varlist,typelist): |
|
799 | 799 | print itpl(vformat), |
|
800 | 800 | if vtype in seq_types: |
|
801 | 801 | print len(var) |
|
802 | 802 | elif vtype==array_type: |
|
803 | 803 | vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1] |
|
804 | 804 | vsize = Numeric.size(var) |
|
805 | 805 | vbytes = vsize*var.itemsize() |
|
806 | 806 | if vbytes < 100000: |
|
807 | 807 | print aformat % (vshape,vsize,var.typecode(),vbytes) |
|
808 | 808 | else: |
|
809 | 809 | print aformat % (vshape,vsize,var.typecode(),vbytes), |
|
810 | 810 | if vbytes < Mb: |
|
811 | 811 | print '(%s kb)' % (vbytes/kb,) |
|
812 | 812 | else: |
|
813 | 813 | print '(%s Mb)' % (vbytes/Mb,) |
|
814 | 814 | else: |
|
815 | 815 | vstr = str(var) |
|
816 | 816 | if len(vstr) < 50: |
|
817 | 817 | print vstr |
|
818 | 818 | else: |
|
819 | 819 | printpl(vfmt_short) |
|
820 | 820 | |
|
821 | 821 | def magic_reset(self, parameter_s=''): |
|
822 | 822 | """Resets the namespace by removing all names defined by the user. |
|
823 | 823 | |
|
824 | 824 | Input/Output history are left around in case you need them.""" |
|
825 | 825 | |
|
826 | 826 | ans = raw_input( |
|
827 | 827 | "Once deleted, variables cannot be recovered. Proceed (y/n)? ") |
|
828 | 828 | if not ans.lower() == 'y': |
|
829 | 829 | print 'Nothing done.' |
|
830 | 830 | return |
|
831 | 831 | for i in self.magic_who_ls(): |
|
832 | 832 | del(self.locals[i]) |
|
833 | 833 | |
|
834 | 834 | def magic_config(self,parameter_s=''): |
|
835 | 835 | """Show IPython's internal configuration.""" |
|
836 | 836 | |
|
837 | 837 | page('Current configuration structure:\n'+ |
|
838 | 838 | pformat(self.shell.rc.dict())) |
|
839 | 839 | |
|
840 | 840 | def magic_logstart(self,parameter_s=''): |
|
841 | 841 | """Start logging anywhere in a session. |
|
842 | 842 | |
|
843 | 843 | %logstart [log_name [log_mode]] |
|
844 | 844 | |
|
845 | 845 | If no name is given, it defaults to a file named 'ipython.log' in your |
|
846 | 846 | current directory, in 'rotate' mode (see below). |
|
847 | 847 | |
|
848 | 848 | '%logstart name' saves to file 'name' in 'backup' mode. It saves your |
|
849 | 849 | history up to that point and then continues logging. |
|
850 | 850 | |
|
851 | 851 | %logstart takes a second optional parameter: logging mode. This can be one |
|
852 | 852 | of (note that the modes are given unquoted):\\ |
|
853 | 853 | over: overwrite existing log.\\ |
|
854 | 854 | backup: rename (if exists) to name~ and start name.\\ |
|
855 | 855 | append: well, that says it.\\ |
|
856 | 856 | rotate: create rotating logs name.1~, name.2~, etc. |
|
857 | 857 | """ |
|
858 | 858 | |
|
859 | 859 | #FIXME. This function should all be moved to the Logger class. |
|
860 | 860 | |
|
861 | 861 | valid_modes = qw('over backup append rotate') |
|
862 | 862 | if self.LOG: |
|
863 | 863 | print 'Logging is already in place. Logfile:',self.LOG |
|
864 | 864 | return |
|
865 | 865 | |
|
866 | 866 | par = parameter_s.strip() |
|
867 | 867 | if not par: |
|
868 | 868 | logname = self.LOGDEF |
|
869 | 869 | logmode = 'rotate' # use rotate for the auto-generated logs |
|
870 | 870 | else: |
|
871 | 871 | try: |
|
872 | 872 | logname,logmode = par.split() |
|
873 | 873 | except: |
|
874 | 874 | try: |
|
875 | 875 | logname = par |
|
876 | 876 | logmode = 'backup' |
|
877 | 877 | except: |
|
878 | 878 | warn('Usage: %log [log_name [log_mode]]') |
|
879 | 879 | return |
|
880 | 880 | if not logmode in valid_modes: |
|
881 | 881 | warn('Logging NOT activated.\n' |
|
882 | 882 | 'Usage: %log [log_name [log_mode]]\n' |
|
883 | 883 | 'Valid modes: '+str(valid_modes)) |
|
884 | 884 | return |
|
885 | 885 | |
|
886 | 886 | # If we made it this far, I think we're ok: |
|
887 | 887 | print 'Activating auto-logging.' |
|
888 | 888 | print 'Current session state plus future input saved to:',logname |
|
889 | 889 | print 'Logging mode: ',logmode |
|
890 | 890 | # put logname into rc struct as if it had been called on the command line, |
|
891 | 891 | # so it ends up saved in the log header |
|
892 | 892 | # Save it in case we need to restore it... |
|
893 | 893 | old_logfile = self.shell.rc.opts.get('logfile','') |
|
894 | 894 | logname = os.path.expanduser(logname) |
|
895 | 895 | self.shell.rc.opts.logfile = logname |
|
896 | 896 | self.LOGMODE = logmode # FIXME: this should be set through a function. |
|
897 | 897 | try: |
|
898 | 898 | header = str(self.LOGHEAD) |
|
899 | 899 | self.create_log(header,logname) |
|
900 | 900 | self.logstart(header,logname) |
|
901 | 901 | except: |
|
902 | 902 | self.LOG = '' # we are NOT logging, something went wrong |
|
903 | 903 | self.shell.rc.opts.logfile = old_logfile |
|
904 | 904 | warn("Couldn't start log: "+str(sys.exc_info()[1])) |
|
905 | 905 | else: # log input history up to this point |
|
906 | 906 | self.logfile.write(self.shell.user_ns['_ih'][1:]) |
|
907 | 907 | self.logfile.flush() |
|
908 | 908 | |
|
909 | 909 | def magic_logoff(self,parameter_s=''): |
|
910 | 910 | """Temporarily stop logging. |
|
911 | 911 | |
|
912 | 912 | You must have previously started logging.""" |
|
913 | 913 | self.switch_log(0) |
|
914 | 914 | |
|
915 | 915 | def magic_logon(self,parameter_s=''): |
|
916 | 916 | """Restart logging. |
|
917 | 917 | |
|
918 | 918 | This function is for restarting logging which you've temporarily |
|
919 | 919 | stopped with %logoff. For starting logging for the first time, you |
|
920 | 920 | must use the %logstart function, which allows you to specify an |
|
921 | 921 | optional log filename.""" |
|
922 | 922 | |
|
923 | 923 | self.switch_log(1) |
|
924 | 924 | |
|
925 | 925 | def magic_logstate(self,parameter_s=''): |
|
926 | 926 | """Print the status of the logging system.""" |
|
927 | 927 | |
|
928 | 928 | self.logstate() |
|
929 | 929 | |
|
930 | 930 | def magic_pdb(self, parameter_s=''): |
|
931 | 931 | """Control the calling of the pdb interactive debugger. |
|
932 | 932 | |
|
933 | 933 | Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without |
|
934 | 934 | argument it works as a toggle. |
|
935 | 935 | |
|
936 | 936 | When an exception is triggered, IPython can optionally call the |
|
937 | 937 | interactive pdb debugger after the traceback printout. %pdb toggles |
|
938 | 938 | this feature on and off.""" |
|
939 | 939 | |
|
940 | 940 | par = parameter_s.strip().lower() |
|
941 | 941 | |
|
942 | 942 | if par: |
|
943 | 943 | try: |
|
944 | 944 | pdb = {'off':0,'0':0,'on':1,'1':1}[par] |
|
945 | 945 | except KeyError: |
|
946 | 946 | print 'Incorrect argument. Use on/1, off/0 or nothing for a toggle.' |
|
947 | 947 | return |
|
948 | 948 | else: |
|
949 | 949 | self.shell.InteractiveTB.call_pdb = pdb |
|
950 | 950 | else: |
|
951 | 951 | self.shell.InteractiveTB.call_pdb = 1 - self.shell.InteractiveTB.call_pdb |
|
952 | 952 | print 'Automatic pdb calling has been turned',\ |
|
953 | 953 | on_off(self.shell.InteractiveTB.call_pdb) |
|
954 | 954 | |
|
955 | 955 | |
|
956 | 956 | def magic_prun(self, parameter_s ='',user_mode=1, |
|
957 | 957 | opts=None,arg_lst=None,prog_ns=None): |
|
958 | 958 | |
|
959 | 959 | """Run a statement through the python code profiler. |
|
960 | 960 | |
|
961 | 961 | Usage:\\ |
|
962 | 962 | %prun [options] statement |
|
963 | 963 | |
|
964 | 964 | The given statement (which doesn't require quote marks) is run via the |
|
965 | 965 | python profiler in a manner similar to the profile.run() function. |
|
966 | 966 | Namespaces are internally managed to work correctly; profile.run |
|
967 | 967 | cannot be used in IPython because it makes certain assumptions about |
|
968 | 968 | namespaces which do not hold under IPython. |
|
969 | 969 | |
|
970 | 970 | Options: |
|
971 | 971 | |
|
972 | 972 | -l <limit>: you can place restrictions on what or how much of the |
|
973 | 973 | profile gets printed. The limit value can be: |
|
974 | 974 | |
|
975 | 975 | * A string: only information for function names containing this string |
|
976 | 976 | is printed. |
|
977 | 977 | |
|
978 | 978 | * An integer: only these many lines are printed. |
|
979 | 979 | |
|
980 | 980 | * A float (between 0 and 1): this fraction of the report is printed |
|
981 | 981 | (for example, use a limit of 0.4 to see the topmost 40% only). |
|
982 | 982 | |
|
983 | 983 | You can combine several limits with repeated use of the option. For |
|
984 | 984 | example, '-l __init__ -l 5' will print only the topmost 5 lines of |
|
985 | 985 | information about class constructors. |
|
986 | 986 | |
|
987 | 987 | -r: return the pstats.Stats object generated by the profiling. This |
|
988 | 988 | object has all the information about the profile in it, and you can |
|
989 | 989 | later use it for further analysis or in other functions. |
|
990 | 990 | |
|
991 | 991 | Since magic functions have a particular form of calling which prevents |
|
992 | 992 | you from writing something like:\\ |
|
993 | 993 | In [1]: p = %prun -r print 4 # invalid!\\ |
|
994 | 994 | you must instead use IPython's automatic variables to assign this:\\ |
|
995 | 995 | In [1]: %prun -r print 4 \\ |
|
996 | 996 | Out[1]: <pstats.Stats instance at 0x8222cec>\\ |
|
997 | 997 | In [2]: stats = _ |
|
998 | 998 | |
|
999 | 999 | If you really need to assign this value via an explicit function call, |
|
1000 | 1000 | you can always tap directly into the true name of the magic function |
|
1001 | 1001 | by using the ipmagic function (which IPython automatically adds to the |
|
1002 | 1002 | builtins):\\ |
|
1003 | 1003 | In [3]: stats = ipmagic('prun','-r print 4') |
|
1004 | 1004 | |
|
1005 | 1005 | You can type ipmagic? for more details on ipmagic. |
|
1006 | 1006 | |
|
1007 | 1007 | -s <key>: sort profile by given key. You can provide more than one key |
|
1008 | 1008 | by using the option several times: '-s key1 -s key2 -s key3...'. The |
|
1009 | 1009 | default sorting key is 'time'. |
|
1010 | 1010 | |
|
1011 | 1011 | The following is copied verbatim from the profile documentation |
|
1012 | 1012 | referenced below: |
|
1013 | 1013 | |
|
1014 | 1014 | When more than one key is provided, additional keys are used as |
|
1015 | 1015 | secondary criteria when the there is equality in all keys selected |
|
1016 | 1016 | before them. |
|
1017 | 1017 | |
|
1018 | 1018 | Abbreviations can be used for any key names, as long as the |
|
1019 | 1019 | abbreviation is unambiguous. The following are the keys currently |
|
1020 | 1020 | defined: |
|
1021 | 1021 | |
|
1022 | 1022 | Valid Arg Meaning\\ |
|
1023 | 1023 | "calls" call count\\ |
|
1024 | 1024 | "cumulative" cumulative time\\ |
|
1025 | 1025 | "file" file name\\ |
|
1026 | 1026 | "module" file name\\ |
|
1027 | 1027 | "pcalls" primitive call count\\ |
|
1028 | 1028 | "line" line number\\ |
|
1029 | 1029 | "name" function name\\ |
|
1030 | 1030 | "nfl" name/file/line\\ |
|
1031 | 1031 | "stdname" standard name\\ |
|
1032 | 1032 | "time" internal time |
|
1033 | 1033 | |
|
1034 | 1034 | Note that all sorts on statistics are in descending order (placing |
|
1035 | 1035 | most time consuming items first), where as name, file, and line number |
|
1036 | 1036 | searches are in ascending order (i.e., alphabetical). The subtle |
|
1037 | 1037 | distinction between "nfl" and "stdname" is that the standard name is a |
|
1038 | 1038 | sort of the name as printed, which means that the embedded line |
|
1039 | 1039 | numbers get compared in an odd way. For example, lines 3, 20, and 40 |
|
1040 | 1040 | would (if the file names were the same) appear in the string order |
|
1041 | 1041 | "20" "3" and "40". In contrast, "nfl" does a numeric compare of the |
|
1042 | 1042 | line numbers. In fact, sort_stats("nfl") is the same as |
|
1043 | 1043 | sort_stats("name", "file", "line"). |
|
1044 | 1044 | |
|
1045 | 1045 | -T <filename>: save profile results as shown on screen to a text |
|
1046 | 1046 | file. The profile is still shown on screen. |
|
1047 | 1047 | |
|
1048 | 1048 | -D <filename>: save (via dump_stats) profile statistics to given |
|
1049 | 1049 | filename. This data is in a format understod by the pstats module, and |
|
1050 | 1050 | is generated by a call to the dump_stats() method of profile |
|
1051 | 1051 | objects. The profile is still shown on screen. |
|
1052 | 1052 | |
|
1053 | 1053 | If you want to run complete programs under the profiler's control, use |
|
1054 | 1054 | '%run -p [prof_opts] filename.py [args to program]' where prof_opts |
|
1055 | 1055 | contains profiler specific options as described here. |
|
1056 | 1056 | |
|
1057 | 1057 | You can read the complete documentation for the profile module with:\\ |
|
1058 | 1058 | In [1]: import profile; profile.help() """ |
|
1059 | 1059 | |
|
1060 | 1060 | opts_def = Struct(D=[''],l=[],s=['time'],T=['']) |
|
1061 | 1061 | # protect user quote marks |
|
1062 | 1062 | parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'") |
|
1063 | 1063 | |
|
1064 | 1064 | if user_mode: # regular user call |
|
1065 | 1065 | opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:', |
|
1066 | 1066 | list_all=1) |
|
1067 | 1067 | namespace = self.shell.user_ns |
|
1068 | 1068 | else: # called to run a program by %run -p |
|
1069 | 1069 | try: |
|
1070 | 1070 | filename = get_py_filename(arg_lst[0]) |
|
1071 | 1071 | except IOError,msg: |
|
1072 | 1072 | error(msg) |
|
1073 | 1073 | return |
|
1074 | 1074 | |
|
1075 | 1075 | arg_str = 'execfile(filename,prog_ns)' |
|
1076 | 1076 | namespace = locals() |
|
1077 | 1077 | |
|
1078 | 1078 | opts.merge(opts_def) |
|
1079 | 1079 | |
|
1080 | 1080 | prof = profile.Profile() |
|
1081 | 1081 | try: |
|
1082 | 1082 | prof = prof.runctx(arg_str,namespace,namespace) |
|
1083 | 1083 | sys_exit = '' |
|
1084 | 1084 | except SystemExit: |
|
1085 | 1085 | sys_exit = """*** SystemExit exception caught in code being profiled.""" |
|
1086 | 1086 | |
|
1087 | 1087 | stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s) |
|
1088 | 1088 | |
|
1089 | 1089 | lims = opts.l |
|
1090 | 1090 | if lims: |
|
1091 | 1091 | lims = [] # rebuild lims with ints/floats/strings |
|
1092 | 1092 | for lim in opts.l: |
|
1093 | 1093 | try: |
|
1094 | 1094 | lims.append(int(lim)) |
|
1095 | 1095 | except ValueError: |
|
1096 | 1096 | try: |
|
1097 | 1097 | lims.append(float(lim)) |
|
1098 | 1098 | except ValueError: |
|
1099 | 1099 | lims.append(lim) |
|
1100 | 1100 | |
|
1101 | 1101 | # trap output |
|
1102 | 1102 | sys_stdout = sys.stdout |
|
1103 | 1103 | stdout_trap = StringIO() |
|
1104 | 1104 | try: |
|
1105 | 1105 | sys.stdout = stdout_trap |
|
1106 | 1106 | stats.print_stats(*lims) |
|
1107 | 1107 | finally: |
|
1108 | 1108 | sys.stdout = sys_stdout |
|
1109 | 1109 | output = stdout_trap.getvalue() |
|
1110 | 1110 | output = output.rstrip() |
|
1111 | 1111 | |
|
1112 | 1112 | page(output,screen_lines=self.shell.rc.screen_length) |
|
1113 | 1113 | print sys_exit, |
|
1114 | 1114 | |
|
1115 | 1115 | dump_file = opts.D[0] |
|
1116 | 1116 | text_file = opts.T[0] |
|
1117 | 1117 | if dump_file: |
|
1118 | 1118 | prof.dump_stats(dump_file) |
|
1119 | 1119 | print '\n*** Profile stats marshalled to file',\ |
|
1120 | 1120 | `dump_file`+'.',sys_exit |
|
1121 | 1121 | if text_file: |
|
1122 | 1122 | file(text_file,'w').write(output) |
|
1123 | 1123 | print '\n*** Profile printout saved to text file',\ |
|
1124 | 1124 | `text_file`+'.',sys_exit |
|
1125 | 1125 | |
|
1126 | 1126 | if opts.has_key('r'): |
|
1127 | 1127 | return stats |
|
1128 | 1128 | else: |
|
1129 | 1129 | return None |
|
1130 | 1130 | |
|
1131 | 1131 | def magic_run(self, parameter_s ='',runner=None): |
|
1132 | 1132 | """Run the named file inside IPython as a program. |
|
1133 | 1133 | |
|
1134 | 1134 | Usage:\\ |
|
1135 | 1135 | %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args] |
|
1136 | 1136 | |
|
1137 | 1137 | Parameters after the filename are passed as command-line arguments to |
|
1138 | 1138 | the program (put in sys.argv). Then, control returns to IPython's |
|
1139 | 1139 | prompt. |
|
1140 | 1140 | |
|
1141 | 1141 | This is similar to running at a system prompt:\\ |
|
1142 | 1142 | $ python file args\\ |
|
1143 | 1143 | but with the advantage of giving you IPython's tracebacks, and of |
|
1144 | 1144 | loading all variables into your interactive namespace for further use |
|
1145 | 1145 | (unless -p is used, see below). |
|
1146 | 1146 | |
|
1147 | 1147 | The file is executed in a namespace initially consisting only of |
|
1148 | 1148 | __name__=='__main__' and sys.argv constructed as indicated. It thus |
|
1149 | 1149 | sees its environment as if it were being run as a stand-alone |
|
1150 | 1150 | program. But after execution, the IPython interactive namespace gets |
|
1151 | 1151 | updated with all variables defined in the program (except for __name__ |
|
1152 | 1152 | and sys.argv). This allows for very convenient loading of code for |
|
1153 | 1153 | interactive work, while giving each program a 'clean sheet' to run in. |
|
1154 | 1154 | |
|
1155 | 1155 | Options: |
|
1156 | 1156 | |
|
1157 | 1157 | -n: __name__ is NOT set to '__main__', but to the running file's name |
|
1158 | 1158 | without extension (as python does under import). This allows running |
|
1159 | 1159 | scripts and reloading the definitions in them without calling code |
|
1160 | 1160 | protected by an ' if __name__ == "__main__" ' clause. |
|
1161 | 1161 | |
|
1162 | 1162 | -i: run the file in IPython's namespace instead of an empty one. This |
|
1163 | 1163 | is useful if you are experimenting with code written in a text editor |
|
1164 | 1164 | which depends on variables defined interactively. |
|
1165 | 1165 | |
|
1166 | 1166 | -e: ignore sys.exit() calls or SystemExit exceptions in the script |
|
1167 | 1167 | being run. This is particularly useful if IPython is being used to |
|
1168 | 1168 | run unittests, which always exit with a sys.exit() call. In such |
|
1169 | 1169 | cases you are interested in the output of the test results, not in |
|
1170 | 1170 | seeing a traceback of the unittest module. |
|
1171 | 1171 | |
|
1172 | 1172 | -t: print timing information at the end of the run. IPython will give |
|
1173 | 1173 | you an estimated CPU time consumption for your script, which under |
|
1174 | 1174 | Unix uses the resource module to avoid the wraparound problems of |
|
1175 | 1175 | time.clock(). Under Unix, an estimate of time spent on system tasks |
|
1176 | 1176 | is also given (for Windows platforms this is reported as 0.0). |
|
1177 | 1177 | |
|
1178 | 1178 | If -t is given, an additional -N<N> option can be given, where <N> |
|
1179 | 1179 | must be an integer indicating how many times you want the script to |
|
1180 | 1180 | run. The final timing report will include total and per run results. |
|
1181 | 1181 | |
|
1182 | 1182 | For example (testing the script uniq_stable.py): |
|
1183 | 1183 | |
|
1184 | 1184 | In [1]: run -t uniq_stable |
|
1185 | 1185 | |
|
1186 | 1186 | IPython CPU timings (estimated):\\ |
|
1187 | 1187 | User : 0.19597 s.\\ |
|
1188 | 1188 | System: 0.0 s.\\ |
|
1189 | 1189 | |
|
1190 | 1190 | In [2]: run -t -N5 uniq_stable |
|
1191 | 1191 | |
|
1192 | 1192 | IPython CPU timings (estimated):\\ |
|
1193 | 1193 | Total runs performed: 5\\ |
|
1194 | 1194 | Times : Total Per run\\ |
|
1195 | 1195 | User : 0.910862 s, 0.1821724 s.\\ |
|
1196 | 1196 | System: 0.0 s, 0.0 s. |
|
1197 | 1197 | |
|
1198 | 1198 | -d: run your program under the control of pdb, the Python debugger. |
|
1199 | 1199 | This allows you to execute your program step by step, watch variables, |
|
1200 | 1200 | etc. Internally, what IPython does is similar to calling: |
|
1201 | 1201 | |
|
1202 | 1202 | pdb.run('execfile("YOURFILENAME")') |
|
1203 | 1203 | |
|
1204 | 1204 | with a breakpoint set on line 1 of your file. You can change the line |
|
1205 | 1205 | number for this automatic breakpoint to be <N> by using the -bN option |
|
1206 | 1206 | (where N must be an integer). For example: |
|
1207 | 1207 | |
|
1208 | 1208 | %run -d -b40 myscript |
|
1209 | 1209 | |
|
1210 | 1210 | will set the first breakpoint at line 40 in myscript.py. Note that |
|
1211 | 1211 | the first breakpoint must be set on a line which actually does |
|
1212 | 1212 | something (not a comment or docstring) for it to stop execution. |
|
1213 | 1213 | |
|
1214 | 1214 | When the pdb debugger starts, you will see a (Pdb) prompt. You must |
|
1215 | 1215 | first enter 'c' (without qoutes) to start execution up to the first |
|
1216 | 1216 | breakpoint. |
|
1217 | 1217 | |
|
1218 | 1218 | Entering 'help' gives information about the use of the debugger. You |
|
1219 | 1219 | can easily see pdb's full documentation with "import pdb;pdb.help()" |
|
1220 | 1220 | at a prompt. |
|
1221 | 1221 | |
|
1222 | 1222 | -p: run program under the control of the Python profiler module (which |
|
1223 | 1223 | prints a detailed report of execution times, function calls, etc). |
|
1224 | 1224 | |
|
1225 | 1225 | You can pass other options after -p which affect the behavior of the |
|
1226 | 1226 | profiler itself. See the docs for %prun for details. |
|
1227 | 1227 | |
|
1228 | 1228 | In this mode, the program's variables do NOT propagate back to the |
|
1229 | 1229 | IPython interactive namespace (because they remain in the namespace |
|
1230 | 1230 | where the profiler executes them). |
|
1231 | 1231 | |
|
1232 | 1232 | Internally this triggers a call to %prun, see its documentation for |
|
1233 | 1233 | details on the options available specifically for profiling.""" |
|
1234 | 1234 | |
|
1235 | 1235 | # get arguments and set sys.argv for program to be run. |
|
1236 | 1236 | opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e', |
|
1237 | 1237 | mode='list',list_all=1) |
|
1238 | 1238 | |
|
1239 | 1239 | try: |
|
1240 | 1240 | filename = get_py_filename(arg_lst[0]) |
|
1241 | 1241 | except IndexError: |
|
1242 | 1242 | warn('you must provide at least a filename.') |
|
1243 | 1243 | print '\n%run:\n',OInspect.getdoc(self.magic_run) |
|
1244 | 1244 | return |
|
1245 | 1245 | except IOError,msg: |
|
1246 | 1246 | error(msg) |
|
1247 | 1247 | return |
|
1248 | 1248 | |
|
1249 | 1249 | # Control the response to exit() calls made by the script being run |
|
1250 | 1250 | exit_ignore = opts.has_key('e') |
|
1251 | 1251 | |
|
1252 | 1252 | # Make sure that the running script gets a proper sys.argv as if it |
|
1253 | 1253 | # were run from a system shell. |
|
1254 | 1254 | save_argv = sys.argv # save it for later restoring |
|
1255 | 1255 | sys.argv = [filename]+ arg_lst[1:] # put in the proper filename |
|
1256 | 1256 | |
|
1257 | 1257 | if opts.has_key('i'): |
|
1258 | 1258 | prog_ns = self.shell.user_ns |
|
1259 | 1259 | __name__save = self.shell.user_ns['__name__'] |
|
1260 | 1260 | prog_ns['__name__'] = '__main__' |
|
1261 | 1261 | else: |
|
1262 | 1262 | if opts.has_key('n'): |
|
1263 | 1263 | name = os.path.splitext(os.path.basename(filename))[0] |
|
1264 | 1264 | else: |
|
1265 | 1265 | name = '__main__' |
|
1266 | 1266 | prog_ns = {'__name__':name} |
|
1267 | 1267 | |
|
1268 | 1268 | # pickle fix. See iplib for an explanation |
|
1269 | 1269 | sys.modules[prog_ns['__name__']] = FakeModule(prog_ns) |
|
1270 | 1270 | |
|
1271 | 1271 | stats = None |
|
1272 | 1272 | try: |
|
1273 | 1273 | if opts.has_key('p'): |
|
1274 | 1274 | stats = self.magic_prun('',0,opts,arg_lst,prog_ns) |
|
1275 | 1275 | else: |
|
1276 | 1276 | if opts.has_key('d'): |
|
1277 | 1277 | deb = pdb.Pdb() |
|
1278 | 1278 | # reset Breakpoint state, which is moronically kept |
|
1279 | 1279 | # in a class |
|
1280 | 1280 | bdb.Breakpoint.next = 1 |
|
1281 | 1281 | bdb.Breakpoint.bplist = {} |
|
1282 | 1282 | bdb.Breakpoint.bpbynumber = [None] |
|
1283 | 1283 | # Set an initial breakpoint to stop execution |
|
1284 | 1284 | maxtries = 10 |
|
1285 | 1285 | bp = int(opts.get('b',[1])[0]) |
|
1286 | 1286 | checkline = deb.checkline(filename,bp) |
|
1287 | 1287 | if not checkline: |
|
1288 | 1288 | for bp in range(bp+1,bp+maxtries+1): |
|
1289 | 1289 | if deb.checkline(filename,bp): |
|
1290 | 1290 | break |
|
1291 | 1291 | else: |
|
1292 | 1292 | msg = ("\nI failed to find a valid line to set " |
|
1293 | 1293 | "a breakpoint\n" |
|
1294 | 1294 | "after trying up to line: %s.\n" |
|
1295 | 1295 | "Please set a valid breakpoint manually " |
|
1296 | 1296 | "with the -b option." % bp) |
|
1297 | 1297 | error(msg) |
|
1298 | 1298 | return |
|
1299 | 1299 | # if we find a good linenumber, set the breakpoint |
|
1300 | 1300 | deb.do_break('%s:%s' % (filename,bp)) |
|
1301 | 1301 | # Start file run |
|
1302 | 1302 | print "NOTE: Enter 'c' at the", |
|
1303 | 1303 | print "(Pdb) prompt to start your script." |
|
1304 | 1304 | deb.run('execfile("%s")' % filename,prog_ns) |
|
1305 | 1305 | else: |
|
1306 | 1306 | if runner is None: |
|
1307 | 1307 | runner = self.shell.safe_execfile |
|
1308 | 1308 | if opts.has_key('t'): |
|
1309 | 1309 | try: |
|
1310 | 1310 | nruns = int(opts['N'][0]) |
|
1311 | 1311 | if nruns < 1: |
|
1312 | 1312 | error('Number of runs must be >=1') |
|
1313 | 1313 | return |
|
1314 | 1314 | except (KeyError): |
|
1315 | 1315 | nruns = 1 |
|
1316 | 1316 | if nruns == 1: |
|
1317 | 1317 | t0 = clock2() |
|
1318 | 1318 | runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore) |
|
1319 | 1319 | t1 = clock2() |
|
1320 | 1320 | t_usr = t1[0]-t0[0] |
|
1321 | 1321 | t_sys = t1[1]-t1[1] |
|
1322 | 1322 | print "\nIPython CPU timings (estimated):" |
|
1323 | 1323 | print " User : %10s s." % t_usr |
|
1324 | 1324 | print " System: %10s s." % t_sys |
|
1325 | 1325 | else: |
|
1326 | 1326 | runs = range(nruns) |
|
1327 | 1327 | t0 = clock2() |
|
1328 | 1328 | for nr in runs: |
|
1329 | 1329 | runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore) |
|
1330 | 1330 | t1 = clock2() |
|
1331 | 1331 | t_usr = t1[0]-t0[0] |
|
1332 | 1332 | t_sys = t1[1]-t1[1] |
|
1333 | 1333 | print "\nIPython CPU timings (estimated):" |
|
1334 | 1334 | print "Total runs performed:",nruns |
|
1335 | 1335 | print " Times : %10s %10s" % ('Total','Per run') |
|
1336 | 1336 | print " User : %10s s, %10s s." % (t_usr,t_usr/nruns) |
|
1337 | 1337 | print " System: %10s s, %10s s." % (t_sys,t_sys/nruns) |
|
1338 | 1338 | |
|
1339 | 1339 | else: |
|
1340 | 1340 | runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore) |
|
1341 | 1341 | if opts.has_key('i'): |
|
1342 | 1342 | self.shell.user_ns['__name__'] = __name__save |
|
1343 | 1343 | else: |
|
1344 | 1344 | # update IPython interactive namespace |
|
1345 | 1345 | del prog_ns['__name__'] |
|
1346 | 1346 | self.shell.user_ns.update(prog_ns) |
|
1347 | 1347 | finally: |
|
1348 | 1348 | sys.argv = save_argv |
|
1349 | 1349 | return stats |
|
1350 | 1350 | |
|
1351 | 1351 | def magic_runlog(self, parameter_s =''): |
|
1352 | 1352 | """Run files as logs. |
|
1353 | 1353 | |
|
1354 | 1354 | Usage:\\ |
|
1355 | 1355 | %runlog file1 file2 ... |
|
1356 | 1356 | |
|
1357 | 1357 | Run the named files (treating them as log files) in sequence inside |
|
1358 | 1358 | the interpreter, and return to the prompt. This is much slower than |
|
1359 | 1359 | %run because each line is executed in a try/except block, but it |
|
1360 | 1360 | allows running files with syntax errors in them. |
|
1361 | 1361 | |
|
1362 | 1362 | Normally IPython will guess when a file is one of its own logfiles, so |
|
1363 | 1363 | you can typically use %run even for logs. This shorthand allows you to |
|
1364 | 1364 | force any file to be treated as a log file.""" |
|
1365 | 1365 | |
|
1366 | 1366 | for f in parameter_s.split(): |
|
1367 | 1367 | self.shell.safe_execfile(f,self.shell.user_ns, |
|
1368 | 1368 | self.shell.user_ns,islog=1) |
|
1369 | 1369 | |
|
1370 | 1370 | def magic_time(self,parameter_s = ''): |
|
1371 | 1371 | """Time execution of a Python statement or expression. |
|
1372 | 1372 | |
|
1373 | 1373 | The CPU and wall clock times are printed, and the value of the |
|
1374 | 1374 | expression (if any) is returned. Note that under Win32, system time |
|
1375 | 1375 | is always reported as 0, since it can not be measured. |
|
1376 | 1376 | |
|
1377 | 1377 | This function provides very basic timing functionality. In Python |
|
1378 | 1378 | 2.3, the timeit module offers more control and sophistication, but for |
|
1379 | 1379 | now IPython supports Python 2.2, so we can not rely on timeit being |
|
1380 | 1380 | present. |
|
1381 | 1381 | |
|
1382 | 1382 | Some examples: |
|
1383 | 1383 | |
|
1384 | 1384 | In [1]: time 2**128 |
|
1385 | 1385 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1386 | 1386 | Wall time: 0.00 |
|
1387 | 1387 | Out[1]: 340282366920938463463374607431768211456L |
|
1388 | 1388 | |
|
1389 | 1389 | In [2]: n = 1000000 |
|
1390 | 1390 | |
|
1391 | 1391 | In [3]: time sum(range(n)) |
|
1392 | 1392 | CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s |
|
1393 | 1393 | Wall time: 1.37 |
|
1394 | 1394 | Out[3]: 499999500000L |
|
1395 | 1395 | |
|
1396 | 1396 | In [4]: time print 'hello world' |
|
1397 | 1397 | hello world |
|
1398 | 1398 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1399 | 1399 | Wall time: 0.00 |
|
1400 | 1400 | """ |
|
1401 | 1401 | |
|
1402 | 1402 | # fail immediately if the given expression can't be compiled |
|
1403 | 1403 | try: |
|
1404 | 1404 | mode = 'eval' |
|
1405 | 1405 | code = compile(parameter_s,'<timed eval>',mode) |
|
1406 | 1406 | except SyntaxError: |
|
1407 | 1407 | mode = 'exec' |
|
1408 | 1408 | code = compile(parameter_s,'<timed exec>',mode) |
|
1409 | 1409 | # skew measurement as little as possible |
|
1410 | 1410 | glob = self.shell.user_ns |
|
1411 | 1411 | clk = clock2 |
|
1412 | 1412 | wtime = time.time |
|
1413 | 1413 | # time execution |
|
1414 | 1414 | wall_st = wtime() |
|
1415 | 1415 | if mode=='eval': |
|
1416 | 1416 | st = clk() |
|
1417 | 1417 | out = eval(code,glob) |
|
1418 | 1418 | end = clk() |
|
1419 | 1419 | else: |
|
1420 | 1420 | st = clk() |
|
1421 | 1421 | exec code in glob |
|
1422 | 1422 | end = clk() |
|
1423 | 1423 | out = None |
|
1424 | 1424 | wall_end = wtime() |
|
1425 | 1425 | # Compute actual times and report |
|
1426 | 1426 | wall_time = wall_end-wall_st |
|
1427 | 1427 | cpu_user = end[0]-st[0] |
|
1428 | 1428 | cpu_sys = end[1]-st[1] |
|
1429 | 1429 | cpu_tot = cpu_user+cpu_sys |
|
1430 | 1430 | print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \ |
|
1431 | 1431 | (cpu_user,cpu_sys,cpu_tot) |
|
1432 | 1432 | print "Wall time: %.2f" % wall_time |
|
1433 | 1433 | return out |
|
1434 | 1434 | |
|
1435 | 1435 | def magic_macro(self,parameter_s = ''): |
|
1436 | 1436 | """Define a set of input lines as a macro for future re-execution. |
|
1437 | 1437 | |
|
1438 | 1438 | Usage:\\ |
|
1439 | 1439 | %macro name n1:n2 n3:n4 ... n5 .. n6 ... |
|
1440 | 1440 | |
|
1441 | 1441 | This will define a global variable called `name` which is a string |
|
1442 | 1442 | made of joining the slices and lines you specify (n1,n2,... numbers |
|
1443 | 1443 | above) from your input history into a single string. This variable |
|
1444 | 1444 | acts like an automatic function which re-executes those lines as if |
|
1445 | 1445 | you had typed them. You just type 'name' at the prompt and the code |
|
1446 | 1446 | executes. |
|
1447 | 1447 | |
|
1448 | 1448 | Note that the slices use the standard Python slicing notation (5:8 |
|
1449 | 1449 | means include lines numbered 5,6,7). |
|
1450 | 1450 | |
|
1451 | 1451 | For example, if your history contains (%hist prints it): |
|
1452 | 1452 | |
|
1453 | 1453 | 44: x=1\\ |
|
1454 | 1454 | 45: y=3\\ |
|
1455 | 1455 | 46: z=x+y\\ |
|
1456 | 1456 | 47: print x\\ |
|
1457 | 1457 | 48: a=5\\ |
|
1458 | 1458 | 49: print 'x',x,'y',y\\ |
|
1459 | 1459 | |
|
1460 | 1460 | you can create a macro with lines 44 through 47 (included) and line 49 |
|
1461 | 1461 | called my_macro with: |
|
1462 | 1462 | |
|
1463 | 1463 | In [51]: %macro my_macro 44:48 49 |
|
1464 | 1464 | |
|
1465 | 1465 | Now, typing `my_macro` (without quotes) will re-execute all this code |
|
1466 | 1466 | in one pass. |
|
1467 | 1467 | |
|
1468 | 1468 | You don't need to give the line-numbers in order, and any given line |
|
1469 | 1469 | number can appear multiple times. You can assemble macros with any |
|
1470 | 1470 | lines from your input history in any order. |
|
1471 | 1471 | |
|
1472 | 1472 | The macro is a simple object which holds its value in an attribute, |
|
1473 | 1473 | but IPython's display system checks for macros and executes them as |
|
1474 | 1474 | code instead of printing them when you type their name. |
|
1475 | 1475 | |
|
1476 | 1476 | You can view a macro's contents by explicitly printing it with: |
|
1477 | 1477 | |
|
1478 | 1478 | 'print macro_name'. |
|
1479 | 1479 | |
|
1480 | 1480 | For one-off cases which DON'T contain magic function calls in them you |
|
1481 | 1481 | can obtain similar results by explicitly executing slices from your |
|
1482 | 1482 | input history with: |
|
1483 | 1483 | |
|
1484 | 1484 | In [60]: exec In[44:48]+In[49]""" |
|
1485 | 1485 | |
|
1486 | 1486 | args = parameter_s.split() |
|
1487 | 1487 | name,ranges = args[0], args[1:] |
|
1488 | 1488 | #print 'rng',ranges # dbg |
|
1489 | 1489 | cmds = self.extract_input_slices(ranges) |
|
1490 | 1490 | macro = Macro(cmds) |
|
1491 | 1491 | self.shell.user_ns.update({name:macro}) |
|
1492 | 1492 | print 'Macro `%s` created. To execute, type its name (without quotes).' % name |
|
1493 | 1493 | print 'Macro contents:' |
|
1494 | 1494 | print str(macro).rstrip(), |
|
1495 | 1495 | |
|
1496 | 1496 | def magic_save(self,parameter_s = ''): |
|
1497 | 1497 | """Save a set of lines to a given filename. |
|
1498 | 1498 | |
|
1499 | 1499 | Usage:\\ |
|
1500 | 1500 | %save filename n1:n2 n3:n4 ... n5 .. n6 ... |
|
1501 | 1501 | |
|
1502 | 1502 | This function uses the same syntax as %macro for line extraction, but |
|
1503 | 1503 | instead of creating a macro it saves the resulting string to the |
|
1504 | 1504 | filename you specify. |
|
1505 | 1505 | |
|
1506 | 1506 | It adds a '.py' extension to the file if you don't do so yourself, and |
|
1507 | 1507 | it asks for confirmation before overwriting existing files.""" |
|
1508 | 1508 | |
|
1509 | 1509 | args = parameter_s.split() |
|
1510 | 1510 | fname,ranges = args[0], args[1:] |
|
1511 | 1511 | if not fname.endswith('.py'): |
|
1512 | 1512 | fname += '.py' |
|
1513 | 1513 | if os.path.isfile(fname): |
|
1514 | 1514 | ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname) |
|
1515 | 1515 | if ans.lower() not in ['y','yes']: |
|
1516 | 1516 | print 'Operation cancelled.' |
|
1517 | 1517 | return |
|
1518 | 1518 | cmds = ''.join(self.extract_input_slices(ranges)) |
|
1519 | 1519 | f = file(fname,'w') |
|
1520 | 1520 | f.write(cmds) |
|
1521 | 1521 | f.close() |
|
1522 | 1522 | print 'The following commands were written to file `%s`:' % fname |
|
1523 | 1523 | print cmds |
|
1524 | 1524 | |
|
1525 | 1525 | def magic_ed(self,parameter_s = ''): |
|
1526 | 1526 | """Alias to %edit.""" |
|
1527 | 1527 | return self.magic_edit(parameter_s) |
|
1528 | 1528 | |
|
1529 | 1529 | def magic_edit(self,parameter_s = '',last_call=['','']): |
|
1530 | 1530 | """Bring up an editor and execute the resulting code. |
|
1531 | 1531 | |
|
1532 | 1532 | Usage: |
|
1533 | 1533 | %edit [options] [args] |
|
1534 | 1534 | |
|
1535 | 1535 | %edit runs IPython's editor hook. The default version of this hook is |
|
1536 | 1536 | set to call the __IPYTHON__.rc.editor command. This is read from your |
|
1537 | 1537 | environment variable $EDITOR. If this isn't found, it will default to |
|
1538 | 1538 | vi under Linux/Unix and to notepad under Windows. See the end of this |
|
1539 | 1539 | docstring for how to change the editor hook. |
|
1540 | 1540 | |
|
1541 | 1541 | You can also set the value of this editor via the command line option |
|
1542 | 1542 | '-editor' or in your ipythonrc file. This is useful if you wish to use |
|
1543 | 1543 | specifically for IPython an editor different from your typical default |
|
1544 | 1544 | (and for Windows users who typically don't set environment variables). |
|
1545 | 1545 | |
|
1546 | 1546 | This command allows you to conveniently edit multi-line code right in |
|
1547 | 1547 | your IPython session. |
|
1548 | 1548 | |
|
1549 | 1549 | If called without arguments, %edit opens up an empty editor with a |
|
1550 | 1550 | temporary file and will execute the contents of this file when you |
|
1551 | 1551 | close it (don't forget to save it!). |
|
1552 | 1552 | |
|
1553 | 1553 | Options: |
|
1554 | 1554 | |
|
1555 | 1555 | -p: this will call the editor with the same data as the previous time |
|
1556 | 1556 | it was used, regardless of how long ago (in your current session) it |
|
1557 | 1557 | was. |
|
1558 | 1558 | |
|
1559 | 1559 | -x: do not execute the edited code immediately upon exit. This is |
|
1560 | 1560 | mainly useful if you are editing programs which need to be called with |
|
1561 | 1561 | command line arguments, which you can then do using %run. |
|
1562 | 1562 | |
|
1563 | 1563 | Arguments: |
|
1564 | 1564 | |
|
1565 | 1565 | If arguments are given, the following possibilites exist: |
|
1566 | 1566 | |
|
1567 | 1567 | - The arguments are numbers or pairs of colon-separated numbers (like |
|
1568 | 1568 | 1 4:8 9). These are interpreted as lines of previous input to be |
|
1569 | 1569 | loaded into the editor. The syntax is the same of the %macro command. |
|
1570 | 1570 | |
|
1571 | 1571 | - If the argument doesn't start with a number, it is evaluated as a |
|
1572 | 1572 | variable and its contents loaded into the editor. You can thus edit |
|
1573 | 1573 | any string which contains python code (including the result of |
|
1574 | 1574 | previous edits). |
|
1575 | 1575 | |
|
1576 | 1576 | - If the argument is the name of an object (other than a string), |
|
1577 | 1577 | IPython will try to locate the file where it was defined and open the |
|
1578 | 1578 | editor at the point where it is defined. You can use `%edit function` |
|
1579 | 1579 | to load an editor exactly at the point where 'function' is defined, |
|
1580 | 1580 | edit it and have the file be executed automatically. |
|
1581 | 1581 | |
|
1582 | 1582 | Note: opening at an exact line is only supported under Unix, and some |
|
1583 | 1583 | editors (like kedit and gedit up to Gnome 2.8) do not understand the |
|
1584 | 1584 | '+NUMBER' parameter necessary for this feature. Good editors like |
|
1585 | 1585 | (X)Emacs, vi, jed, pico and joe all do. |
|
1586 | 1586 | |
|
1587 | 1587 | - If the argument is not found as a variable, IPython will look for a |
|
1588 | 1588 | file with that name (adding .py if necessary) and load it into the |
|
1589 | 1589 | editor. It will execute its contents with execfile() when you exit, |
|
1590 | 1590 | loading any code in the file into your interactive namespace. |
|
1591 | 1591 | |
|
1592 | 1592 | After executing your code, %edit will return as output the code you |
|
1593 | 1593 | typed in the editor (except when it was an existing file). This way |
|
1594 | 1594 | you can reload the code in further invocations of %edit as a variable, |
|
1595 | 1595 | via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of |
|
1596 | 1596 | the output. |
|
1597 | 1597 | |
|
1598 | 1598 | Note that %edit is also available through the alias %ed. |
|
1599 | 1599 | |
|
1600 | 1600 | This is an example of creating a simple function inside the editor and |
|
1601 | 1601 | then modifying it. First, start up the editor: |
|
1602 | 1602 | |
|
1603 | 1603 | In [1]: ed\\ |
|
1604 | 1604 | Editing... done. Executing edited code...\\ |
|
1605 | 1605 | Out[1]: 'def foo():\\n print "foo() was defined in an editing session"\\n' |
|
1606 | 1606 | |
|
1607 | 1607 | We can then call the function foo(): |
|
1608 | 1608 | |
|
1609 | 1609 | In [2]: foo()\\ |
|
1610 | 1610 | foo() was defined in an editing session |
|
1611 | 1611 | |
|
1612 | 1612 | Now we edit foo. IPython automatically loads the editor with the |
|
1613 | 1613 | (temporary) file where foo() was previously defined: |
|
1614 | 1614 | |
|
1615 | 1615 | In [3]: ed foo\\ |
|
1616 | 1616 | Editing... done. Executing edited code... |
|
1617 | 1617 | |
|
1618 | 1618 | And if we call foo() again we get the modified version: |
|
1619 | 1619 | |
|
1620 | 1620 | In [4]: foo()\\ |
|
1621 | 1621 | foo() has now been changed! |
|
1622 | 1622 | |
|
1623 | 1623 | Here is an example of how to edit a code snippet successive |
|
1624 | 1624 | times. First we call the editor: |
|
1625 | 1625 | |
|
1626 | 1626 | In [8]: ed\\ |
|
1627 | 1627 | Editing... done. Executing edited code...\\ |
|
1628 | 1628 | hello\\ |
|
1629 | 1629 | Out[8]: "print 'hello'\\n" |
|
1630 | 1630 | |
|
1631 | 1631 | Now we call it again with the previous output (stored in _): |
|
1632 | 1632 | |
|
1633 | 1633 | In [9]: ed _\\ |
|
1634 | 1634 | Editing... done. Executing edited code...\\ |
|
1635 | 1635 | hello world\\ |
|
1636 | 1636 | Out[9]: "print 'hello world'\\n" |
|
1637 | 1637 | |
|
1638 | 1638 | Now we call it with the output #8 (stored in _8, also as Out[8]): |
|
1639 | 1639 | |
|
1640 | 1640 | In [10]: ed _8\\ |
|
1641 | 1641 | Editing... done. Executing edited code...\\ |
|
1642 | 1642 | hello again\\ |
|
1643 | 1643 | Out[10]: "print 'hello again'\\n" |
|
1644 | 1644 | |
|
1645 | 1645 | |
|
1646 | 1646 | Changing the default editor hook: |
|
1647 | 1647 | |
|
1648 | 1648 | If you wish to write your own editor hook, you can put it in a |
|
1649 | 1649 | configuration file which you load at startup time. The default hook |
|
1650 | 1650 | is defined in the IPython.hooks module, and you can use that as a |
|
1651 | 1651 | starting example for further modifications. That file also has |
|
1652 | 1652 | general instructions on how to set a new hook for use once you've |
|
1653 | 1653 | defined it.""" |
|
1654 | 1654 | |
|
1655 | 1655 | # FIXME: This function has become a convoluted mess. It needs a |
|
1656 | 1656 | # ground-up rewrite with clean, simple logic. |
|
1657 | 1657 | |
|
1658 | 1658 | def make_filename(arg): |
|
1659 | 1659 | "Make a filename from the given args" |
|
1660 | 1660 | try: |
|
1661 | 1661 | filename = get_py_filename(arg) |
|
1662 | 1662 | except IOError: |
|
1663 | 1663 | if args.endswith('.py'): |
|
1664 | 1664 | filename = arg |
|
1665 | 1665 | else: |
|
1666 | 1666 | filename = None |
|
1667 | 1667 | return filename |
|
1668 | 1668 | |
|
1669 | 1669 | # custom exceptions |
|
1670 | 1670 | class DataIsObject(Exception): pass |
|
1671 | 1671 | |
|
1672 | 1672 | opts,args = self.parse_options(parameter_s,'px') |
|
1673 | 1673 | |
|
1674 | 1674 | # Default line number value |
|
1675 | 1675 | lineno = None |
|
1676 | 1676 | if opts.has_key('p'): |
|
1677 | 1677 | args = '_%s' % last_call[0] |
|
1678 | 1678 | if not self.shell.user_ns.has_key(args): |
|
1679 | 1679 | args = last_call[1] |
|
1680 | 1680 | |
|
1681 | 1681 | # use last_call to remember the state of the previous call, but don't |
|
1682 | 1682 | # let it be clobbered by successive '-p' calls. |
|
1683 | 1683 | try: |
|
1684 | 1684 | last_call[0] = self.shell.outputcache.prompt_count |
|
1685 | 1685 | if not opts.has_key('p'): |
|
1686 | 1686 | last_call[1] = parameter_s |
|
1687 | 1687 | except: |
|
1688 | 1688 | pass |
|
1689 | 1689 | |
|
1690 | 1690 | # by default this is done with temp files, except when the given |
|
1691 | 1691 | # arg is a filename |
|
1692 | 1692 | use_temp = 1 |
|
1693 | 1693 | |
|
1694 | 1694 | if re.match(r'\d',args): |
|
1695 | 1695 | # Mode where user specifies ranges of lines, like in %macro. |
|
1696 | 1696 | # This means that you can't edit files whose names begin with |
|
1697 | 1697 | # numbers this way. Tough. |
|
1698 | 1698 | ranges = args.split() |
|
1699 | 1699 | data = ''.join(self.extract_input_slices(ranges)) |
|
1700 | 1700 | elif args.endswith('.py'): |
|
1701 | 1701 | filename = make_filename(args) |
|
1702 | 1702 | data = '' |
|
1703 | 1703 | use_temp = 0 |
|
1704 | 1704 | elif args: |
|
1705 | 1705 | try: |
|
1706 | 1706 | # Load the parameter given as a variable. If not a string, |
|
1707 | 1707 | # process it as an object instead (below) |
|
1708 | 1708 | |
|
1709 | 1709 | #print '*** args',args,'type',type(args) # dbg |
|
1710 | 1710 | data = eval(args,self.shell.user_ns) |
|
1711 | 1711 | if not type(data) in StringTypes: |
|
1712 | 1712 | raise DataIsObject |
|
1713 | 1713 | except (NameError,SyntaxError): |
|
1714 | 1714 | # given argument is not a variable, try as a filename |
|
1715 | 1715 | filename = make_filename(args) |
|
1716 | 1716 | if filename is None: |
|
1717 | 1717 | warn("Argument given (%s) can't be found as a variable " |
|
1718 | 1718 | "or as a filename." % args) |
|
1719 | 1719 | return |
|
1720 | 1720 | data = '' |
|
1721 | 1721 | use_temp = 0 |
|
1722 | 1722 | except DataIsObject: |
|
1723 | 1723 | # For objects, try to edit the file where they are defined |
|
1724 | 1724 | try: |
|
1725 | 1725 | filename = inspect.getabsfile(data) |
|
1726 | 1726 | datafile = 1 |
|
1727 | 1727 | except TypeError: |
|
1728 | 1728 | filename = make_filename(args) |
|
1729 | 1729 | datafile = 1 |
|
1730 | 1730 | warn('Could not find file where `%s` is defined.\n' |
|
1731 | 1731 | 'Opening a file named `%s`' % (args,filename)) |
|
1732 | 1732 | # Now, make sure we can actually read the source (if it was in |
|
1733 | 1733 | # a temp file it's gone by now). |
|
1734 | 1734 | if datafile: |
|
1735 | 1735 | try: |
|
1736 | 1736 | lineno = inspect.getsourcelines(data)[1] |
|
1737 | 1737 | except IOError: |
|
1738 | 1738 | filename = make_filename(args) |
|
1739 | 1739 | if filename is None: |
|
1740 | 1740 | warn('The file `%s` where `%s` was defined cannot ' |
|
1741 | 1741 | 'be read.' % (filename,data)) |
|
1742 | 1742 | return |
|
1743 | 1743 | use_temp = 0 |
|
1744 | 1744 | else: |
|
1745 | 1745 | data = '' |
|
1746 | 1746 | |
|
1747 | 1747 | if use_temp: |
|
1748 | 1748 | filename = tempfile.mktemp('.py') |
|
1749 | 1749 | self.shell.tempfiles.append(filename) |
|
1750 | 1750 | |
|
1751 | 1751 | if data and use_temp: |
|
1752 | 1752 | tmp_file = open(filename,'w') |
|
1753 | 1753 | tmp_file.write(data) |
|
1754 | 1754 | tmp_file.close() |
|
1755 | 1755 | |
|
1756 | 1756 | # do actual editing here |
|
1757 | 1757 | print 'Editing...', |
|
1758 | 1758 | sys.stdout.flush() |
|
1759 | 1759 | self.shell.hooks.editor(filename,lineno) |
|
1760 | 1760 | if opts.has_key('x'): # -x prevents actual execution |
|
1761 | 1761 | |
|
1762 | 1762 | else: |
|
1763 | 1763 | print 'done. Executing edited code...' |
|
1764 | 1764 | try: |
|
1765 | 1765 | execfile(filename,self.shell.user_ns) |
|
1766 | 1766 | except IOError,msg: |
|
1767 | 1767 | if msg.filename == filename: |
|
1768 | 1768 | warn('File not found. Did you forget to save?') |
|
1769 | 1769 | return |
|
1770 | 1770 | else: |
|
1771 | 1771 | self.shell.showtraceback() |
|
1772 | 1772 | except: |
|
1773 | 1773 | self.shell.showtraceback() |
|
1774 | 1774 | if use_temp: |
|
1775 | 1775 | contents = open(filename).read() |
|
1776 | 1776 | return contents |
|
1777 | 1777 | |
|
1778 | 1778 | def magic_xmode(self,parameter_s = ''): |
|
1779 | 1779 | """Switch modes for the exception handlers. |
|
1780 | 1780 | |
|
1781 | 1781 | Valid modes: Plain, Context and Verbose. |
|
1782 | 1782 | |
|
1783 | 1783 | If called without arguments, acts as a toggle.""" |
|
1784 | 1784 | |
|
1785 | 1785 | new_mode = parameter_s.strip().capitalize() |
|
1786 | 1786 | try: |
|
1787 | 1787 | self.InteractiveTB.set_mode(mode = new_mode) |
|
1788 | 1788 | print 'Exception reporting mode:',self.InteractiveTB.mode |
|
1789 | 1789 | except: |
|
1790 | 1790 | warn('Error changing exception modes.\n' + str(sys.exc_info()[1])) |
|
1791 | 1791 | |
|
1792 | 1792 | def magic_colors(self,parameter_s = ''): |
|
1793 | 1793 | """Switch color scheme for prompts, info system and exception handlers. |
|
1794 | 1794 | |
|
1795 | 1795 | Currently implemented schemes: NoColor, Linux, LightBG. |
|
1796 | 1796 | |
|
1797 | 1797 | Color scheme names are not case-sensitive.""" |
|
1798 | 1798 | |
|
1799 | 1799 | new_scheme = parameter_s.strip() |
|
1800 | 1800 | if not new_scheme: |
|
1801 | 1801 | print 'You must specify a color scheme.' |
|
1802 | 1802 | return |
|
1803 | 1803 | # Under Windows, check for Gary Bishop's readline, which is necessary |
|
1804 | 1804 | # for ANSI coloring |
|
1805 | 1805 | if os.name in ['nt','dos']: |
|
1806 | 1806 | try: |
|
1807 | 1807 | import readline |
|
1808 | 1808 | except ImportError: |
|
1809 | 1809 | has_readline = 0 |
|
1810 | 1810 | else: |
|
1811 | 1811 | try: |
|
1812 | 1812 | readline.GetOutputFile() |
|
1813 | 1813 | except AttributeError: |
|
1814 | 1814 | has_readline = 0 |
|
1815 | 1815 | else: |
|
1816 | 1816 | has_readline = 1 |
|
1817 | 1817 | if not has_readline: |
|
1818 | 1818 | msg = """\ |
|
1819 | 1819 | Proper color support under MS Windows requires Gary Bishop's readline library. |
|
1820 | 1820 | You can find it at: |
|
1821 | 1821 | http://sourceforge.net/projects/uncpythontools |
|
1822 | 1822 | Gary's readline needs the ctypes module, from: |
|
1823 | 1823 | http://starship.python.net/crew/theller/ctypes |
|
1824 | 1824 | |
|
1825 | 1825 | Defaulting color scheme to 'NoColor'""" |
|
1826 | 1826 | new_scheme = 'NoColor' |
|
1827 | 1827 | warn(msg) |
|
1828 | 1828 | |
|
1829 | 1829 | # Set prompt colors |
|
1830 | 1830 | try: |
|
1831 | 1831 | self.shell.outputcache.set_colors(new_scheme) |
|
1832 | 1832 | except: |
|
1833 | 1833 | warn('Error changing prompt color schemes.\n' |
|
1834 | 1834 | + str(sys.exc_info()[1])) |
|
1835 | 1835 | else: |
|
1836 | 1836 | self.shell.rc.colors = \ |
|
1837 | 1837 | self.shell.outputcache.color_table.active_scheme_name |
|
1838 | 1838 | # Set exception colors |
|
1839 | 1839 | try: |
|
1840 | 1840 | self.shell.InteractiveTB.set_colors(scheme = new_scheme) |
|
1841 | 1841 | self.shell.SyntaxTB.set_colors(scheme = new_scheme) |
|
1842 | 1842 | except: |
|
1843 | 1843 | warn('Error changing exception color schemes.\n' |
|
1844 | 1844 | + str(sys.exc_info()[1])) |
|
1845 | 1845 | # Set info (for 'object?') colors |
|
1846 | 1846 | if self.shell.rc.color_info: |
|
1847 | 1847 | try: |
|
1848 | 1848 | self.shell.inspector.set_active_scheme(new_scheme) |
|
1849 | 1849 | except: |
|
1850 | 1850 | warn('Error changing object inspector color schemes.\n' |
|
1851 | 1851 | + str(sys.exc_info()[1])) |
|
1852 | 1852 | else: |
|
1853 | 1853 | self.shell.inspector.set_active_scheme('NoColor') |
|
1854 | 1854 | |
|
1855 | 1855 | def magic_color_info(self,parameter_s = ''): |
|
1856 | 1856 | """Toggle color_info. |
|
1857 | 1857 | |
|
1858 | 1858 | The color_info configuration parameter controls whether colors are |
|
1859 | 1859 | used for displaying object details (by things like %psource, %pfile or |
|
1860 | 1860 | the '?' system). This function toggles this value with each call. |
|
1861 | 1861 | |
|
1862 | 1862 | Note that unless you have a fairly recent pager (less works better |
|
1863 | 1863 | than more) in your system, using colored object information displays |
|
1864 | 1864 | will not work properly. Test it and see.""" |
|
1865 | 1865 | |
|
1866 | 1866 | self.shell.rc.color_info = 1 - self.shell.rc.color_info |
|
1867 | 1867 | self.magic_colors(self.shell.rc.colors) |
|
1868 | 1868 | print 'Object introspection functions have now coloring:', |
|
1869 | 1869 | print ['OFF','ON'][self.shell.rc.color_info] |
|
1870 | 1870 | |
|
1871 | 1871 | def magic_Pprint(self, parameter_s=''): |
|
1872 | 1872 | """Toggle pretty printing on/off.""" |
|
1873 | 1873 | |
|
1874 | 1874 | self.shell.outputcache.Pprint = 1 - self.shell.outputcache.Pprint |
|
1875 | 1875 | print 'Pretty printing has been turned', \ |
|
1876 | 1876 | ['OFF','ON'][self.shell.outputcache.Pprint] |
|
1877 | 1877 | |
|
1878 | 1878 | def magic_Exit(self, parameter_s=''): |
|
1879 | 1879 | """Exit IPython without confirmation.""" |
|
1880 | 1880 | |
|
1881 | 1881 | self.shell.exit_now = True |
|
1882 | 1882 | |
|
1883 | 1883 | def magic_Quit(self, parameter_s=''): |
|
1884 | 1884 | """Exit IPython without confirmation (like %Exit).""" |
|
1885 | 1885 | |
|
1886 | 1886 | self.shell.exit_now = True |
|
1887 | 1887 | |
|
1888 | 1888 | #...................................................................... |
|
1889 | 1889 | # Functions to implement unix shell-type things |
|
1890 | 1890 | |
|
1891 | 1891 | def magic_alias(self, parameter_s = ''): |
|
1892 | 1892 | """Define an alias for a system command. |
|
1893 | 1893 | |
|
1894 | 1894 | '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd' |
|
1895 | 1895 | |
|
1896 | 1896 | Then, typing 'alias_name params' will execute the system command 'cmd |
|
1897 | 1897 | params' (from your underlying operating system). |
|
1898 | 1898 | |
|
1899 | 1899 | Aliases have lower precedence than magic functions and Python normal |
|
1900 | 1900 | variables, so if 'foo' is both a Python variable and an alias, the |
|
1901 | 1901 | alias can not be executed until 'del foo' removes the Python variable. |
|
1902 | 1902 | |
|
1903 | 1903 | You can use the %l specifier in an alias definition to represent the |
|
1904 | 1904 | whole line when the alias is called. For example: |
|
1905 | 1905 | |
|
1906 | 1906 | In [2]: alias all echo "Input in brackets: <%l>"\\ |
|
1907 | 1907 | In [3]: all hello world\\ |
|
1908 | 1908 | Input in brackets: <hello world> |
|
1909 | 1909 | |
|
1910 | 1910 | You can also define aliases with parameters using %s specifiers (one |
|
1911 | 1911 | per parameter): |
|
1912 | 1912 | |
|
1913 | 1913 | In [1]: alias parts echo first %s second %s\\ |
|
1914 | 1914 | In [2]: %parts A B\\ |
|
1915 | 1915 | first A second B\\ |
|
1916 | 1916 | In [3]: %parts A\\ |
|
1917 | 1917 | Incorrect number of arguments: 2 expected.\\ |
|
1918 | 1918 | parts is an alias to: 'echo first %s second %s' |
|
1919 | 1919 | |
|
1920 | 1920 | Note that %l and %s are mutually exclusive. You can only use one or |
|
1921 | 1921 | the other in your aliases. |
|
1922 | 1922 | |
|
1923 | 1923 | Aliases expand Python variables just like system calls using ! or !! |
|
1924 | 1924 | do: all expressions prefixed with '$' get expanded. For details of |
|
1925 | 1925 | the semantic rules, see PEP-215: |
|
1926 | 1926 | http://www.python.org/peps/pep-0215.html. This is the library used by |
|
1927 | 1927 | IPython for variable expansion. If you want to access a true shell |
|
1928 | 1928 | variable, an extra $ is necessary to prevent its expansion by IPython: |
|
1929 | 1929 | |
|
1930 | 1930 | In [6]: alias show echo\\ |
|
1931 | 1931 | In [7]: PATH='A Python string'\\ |
|
1932 | 1932 | In [8]: show $PATH\\ |
|
1933 | 1933 | A Python string\\ |
|
1934 | 1934 | In [9]: show $$PATH\\ |
|
1935 | 1935 | /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:... |
|
1936 | 1936 | |
|
1937 | 1937 | You can use the alias facility to acess all of $PATH. See the %rehash |
|
1938 | 1938 | and %rehashx functions, which automatically create aliases for the |
|
1939 | 1939 | contents of your $PATH. |
|
1940 | 1940 | |
|
1941 | 1941 | If called with no parameters, %alias prints the current alias table.""" |
|
1942 | 1942 | |
|
1943 | 1943 | par = parameter_s.strip() |
|
1944 | 1944 | if not par: |
|
1945 | 1945 | if self.shell.rc.automagic: |
|
1946 | 1946 | prechar = '' |
|
1947 | 1947 | else: |
|
1948 | 1948 | prechar = self.shell.ESC_MAGIC |
|
1949 | 1949 | print 'Alias\t\tSystem Command\n'+'-'*30 |
|
1950 | 1950 | atab = self.shell.alias_table |
|
1951 | 1951 | aliases = atab.keys() |
|
1952 | 1952 | aliases.sort() |
|
1953 | 1953 | for alias in aliases: |
|
1954 | 1954 | print prechar+alias+'\t\t'+atab[alias][1] |
|
1955 | 1955 | print '-'*30+'\nTotal number of aliases:',len(aliases) |
|
1956 | 1956 | return |
|
1957 | 1957 | try: |
|
1958 | 1958 | alias,cmd = par.split(None,1) |
|
1959 | 1959 | except: |
|
1960 | 1960 | print OInspect.getdoc(self.magic_alias) |
|
1961 | 1961 | else: |
|
1962 | 1962 | nargs = cmd.count('%s') |
|
1963 | 1963 | if nargs>0 and cmd.find('%l')>=0: |
|
1964 | 1964 | error('The %s and %l specifiers are mutually exclusive ' |
|
1965 | 1965 | 'in alias definitions.') |
|
1966 | 1966 | else: # all looks OK |
|
1967 | 1967 | self.shell.alias_table[alias] = (nargs,cmd) |
|
1968 | 1968 | self.shell.alias_table_validate(verbose=1) |
|
1969 | 1969 | # end magic_alias |
|
1970 | 1970 | |
|
1971 | 1971 | def magic_unalias(self, parameter_s = ''): |
|
1972 | 1972 | """Remove an alias""" |
|
1973 | 1973 | |
|
1974 | 1974 | aname = parameter_s.strip() |
|
1975 | 1975 | if aname in self.shell.alias_table: |
|
1976 | 1976 | del self.shell.alias_table[aname] |
|
1977 | 1977 | |
|
1978 | 1978 | def magic_rehash(self, parameter_s = ''): |
|
1979 | 1979 | """Update the alias table with all entries in $PATH. |
|
1980 | 1980 | |
|
1981 | 1981 | This version does no checks on execute permissions or whether the |
|
1982 | 1982 | contents of $PATH are truly files (instead of directories or something |
|
1983 | 1983 | else). For such a safer (but slower) version, use %rehashx.""" |
|
1984 | 1984 | |
|
1985 | 1985 | # This function (and rehashx) manipulate the alias_table directly |
|
1986 | 1986 | # rather than calling magic_alias, for speed reasons. A rehash on a |
|
1987 | 1987 | # typical Linux box involves several thousand entries, so efficiency |
|
1988 | 1988 | # here is a top concern. |
|
1989 | 1989 | |
|
1990 | 1990 | path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep)) |
|
1991 | 1991 | alias_table = self.shell.alias_table |
|
1992 | 1992 | for pdir in path: |
|
1993 | 1993 | for ff in os.listdir(pdir): |
|
1994 | 1994 | # each entry in the alias table must be (N,name), where |
|
1995 | 1995 | # N is the number of positional arguments of the alias. |
|
1996 | 1996 | alias_table[ff] = (0,ff) |
|
1997 | 1997 | # Make sure the alias table doesn't contain keywords or builtins |
|
1998 | 1998 | self.shell.alias_table_validate() |
|
1999 | 1999 | # Call again init_auto_alias() so we get 'rm -i' and other modified |
|
2000 | 2000 | # aliases since %rehash will probably clobber them |
|
2001 | 2001 | self.shell.init_auto_alias() |
|
2002 | 2002 | |
|
2003 | 2003 | def magic_rehashx(self, parameter_s = ''): |
|
2004 | 2004 | """Update the alias table with all executable files in $PATH. |
|
2005 | 2005 | |
|
2006 | 2006 | This version explicitly checks that every entry in $PATH is a file |
|
2007 | 2007 | with execute access (os.X_OK), so it is much slower than %rehash. |
|
2008 | 2008 | |
|
2009 | 2009 | Under Windows, it checks executability as a match agains a |
|
2010 | 2010 | '|'-separated string of extensions, stored in the IPython config |
|
2011 | 2011 | variable win_exec_ext. This defaults to 'exe|com|bat'. """ |
|
2012 | 2012 | |
|
2013 | 2013 | path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep)) |
|
2014 | 2014 | alias_table = self.shell.alias_table |
|
2015 | 2015 | |
|
2016 | 2016 | if os.name == 'posix': |
|
2017 | 2017 | isexec = lambda fname:os.path.isfile(fname) and \ |
|
2018 | 2018 | os.access(fname,os.X_OK) |
|
2019 | 2019 | else: |
|
2020 | 2020 | |
|
2021 | 2021 | try: |
|
2022 | 2022 | winext = os.environ['pathext'].replace(';','|').replace('.','') |
|
2023 | 2023 | except KeyError: |
|
2024 | 2024 | winext = 'exe|com|bat' |
|
2025 | 2025 | |
|
2026 | 2026 | execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE) |
|
2027 | 2027 | isexec = lambda fname:os.path.isfile(fname) and execre.match(fname) |
|
2028 | 2028 | savedir = os.getcwd() |
|
2029 | 2029 | try: |
|
2030 | 2030 | # write the whole loop for posix/Windows so we don't have an if in |
|
2031 | 2031 | # the innermost part |
|
2032 | 2032 | if os.name == 'posix': |
|
2033 | 2033 | for pdir in path: |
|
2034 | 2034 | os.chdir(pdir) |
|
2035 | 2035 | for ff in os.listdir(pdir): |
|
2036 | 2036 | if isexec(ff): |
|
2037 | 2037 | # each entry in the alias table must be (N,name), |
|
2038 | 2038 | # where N is the number of positional arguments of the |
|
2039 | 2039 | # alias. |
|
2040 | 2040 | alias_table[ff] = (0,ff) |
|
2041 | 2041 | else: |
|
2042 | 2042 | for pdir in path: |
|
2043 | 2043 | os.chdir(pdir) |
|
2044 | 2044 | for ff in os.listdir(pdir): |
|
2045 | 2045 | if isexec(ff): |
|
2046 | 2046 | alias_table[execre.sub(r'\1',ff)] = (0,ff) |
|
2047 | 2047 | # Make sure the alias table doesn't contain keywords or builtins |
|
2048 | 2048 | self.shell.alias_table_validate() |
|
2049 | 2049 | # Call again init_auto_alias() so we get 'rm -i' and other |
|
2050 | 2050 | # modified aliases since %rehashx will probably clobber them |
|
2051 | 2051 | self.shell.init_auto_alias() |
|
2052 | 2052 | finally: |
|
2053 | 2053 | os.chdir(savedir) |
|
2054 | 2054 | |
|
2055 | 2055 | def magic_pwd(self, parameter_s = ''): |
|
2056 | 2056 | """Return the current working directory path.""" |
|
2057 | 2057 | return os.getcwd() |
|
2058 | 2058 | |
|
2059 | 2059 | def magic_cd(self, parameter_s=''): |
|
2060 | 2060 | """Change the current working directory. |
|
2061 | 2061 | |
|
2062 | 2062 | This command automatically maintains an internal list of directories |
|
2063 | 2063 | you visit during your IPython session, in the variable _dh. The |
|
2064 | 2064 | command %dhist shows this history nicely formatted. |
|
2065 | 2065 | |
|
2066 | 2066 | Usage: |
|
2067 | 2067 | |
|
2068 | 2068 | cd 'dir': changes to directory 'dir'. |
|
2069 | 2069 | |
|
2070 | 2070 | cd -: changes to the last visited directory. |
|
2071 | 2071 | |
|
2072 | 2072 | cd -<n>: changes to the n-th directory in the directory history. |
|
2073 | 2073 | |
|
2074 | 2074 | cd -b <bookmark_name>: jump to a bookmark set by %bookmark |
|
2075 | 2075 | (note: cd <bookmark_name> is enough if there is no |
|
2076 | 2076 | directory <bookmark_name>, but a bookmark with the name exists.) |
|
2077 | 2077 | |
|
2078 | 2078 | Options: |
|
2079 | 2079 | |
|
2080 | 2080 | -q: quiet. Do not print the working directory after the cd command is |
|
2081 | 2081 | executed. By default IPython's cd command does print this directory, |
|
2082 | 2082 | since the default prompts do not display path information. |
|
2083 | 2083 | |
|
2084 | 2084 | Note that !cd doesn't work for this purpose because the shell where |
|
2085 | 2085 | !command runs is immediately discarded after executing 'command'.""" |
|
2086 | 2086 | |
|
2087 | 2087 | parameter_s = parameter_s.strip() |
|
2088 | 2088 | bkms = self.shell.persist.get("bookmarks",{}) |
|
2089 | 2089 | |
|
2090 | 2090 | numcd = re.match(r'(-)(\d+)$',parameter_s) |
|
2091 | 2091 | # jump in directory history by number |
|
2092 | 2092 | if numcd: |
|
2093 | 2093 | nn = int(numcd.group(2)) |
|
2094 | 2094 | try: |
|
2095 | 2095 | ps = self.shell.user_ns['_dh'][nn] |
|
2096 | 2096 | except IndexError: |
|
2097 | 2097 | print 'The requested directory does not exist in history.' |
|
2098 | 2098 | return |
|
2099 | 2099 | else: |
|
2100 | 2100 | opts = {} |
|
2101 | 2101 | else: |
|
2102 | 2102 | opts,ps = self.parse_options(parameter_s,'qb',mode='string') |
|
2103 | 2103 | # jump to previous |
|
2104 | 2104 | if ps == '-': |
|
2105 | 2105 | try: |
|
2106 | 2106 | ps = self.shell.user_ns['_dh'][-2] |
|
2107 | 2107 | except IndexError: |
|
2108 | 2108 | print 'No previous directory to change to.' |
|
2109 | 2109 | return |
|
2110 | 2110 | # jump to bookmark |
|
2111 | 2111 | elif opts.has_key('b') or (bkms.has_key(ps) and not os.path.isdir(ps)): |
|
2112 | 2112 | if bkms.has_key(ps): |
|
2113 | 2113 | target = bkms[ps] |
|
2114 | 2114 | print '(bookmark:%s) -> %s' % (ps,target) |
|
2115 | 2115 | ps = target |
|
2116 | 2116 | else: |
|
2117 | 2117 | if bkms: |
|
2118 | 2118 | error("Bookmark '%s' not found. " |
|
2119 | 2119 | "Use '%bookmark -l' to see your bookmarks." % ps) |
|
2120 | 2120 | else: |
|
2121 | 2121 | print "Bookmarks not set - use %bookmark <bookmarkname>" |
|
2122 | 2122 | return |
|
2123 | 2123 | |
|
2124 | 2124 | # at this point ps should point to the target dir |
|
2125 | 2125 | if ps: |
|
2126 | 2126 | try: |
|
2127 | 2127 | os.chdir(os.path.expanduser(ps)) |
|
2128 | 2128 | except OSError: |
|
2129 | 2129 | print sys.exc_info()[1] |
|
2130 | 2130 | else: |
|
2131 | 2131 | self.shell.user_ns['_dh'].append(os.getcwd()) |
|
2132 | 2132 | else: |
|
2133 | 2133 | os.chdir(self.home_dir) |
|
2134 | 2134 | self.shell.user_ns['_dh'].append(os.getcwd()) |
|
2135 | 2135 | if not 'q' in opts: |
|
2136 | 2136 | print self.shell.user_ns['_dh'][-1] |
|
2137 | 2137 | |
|
2138 | 2138 | def magic_dhist(self, parameter_s=''): |
|
2139 | 2139 | """Print your history of visited directories. |
|
2140 | 2140 | |
|
2141 | 2141 | %dhist -> print full history\\ |
|
2142 | 2142 | %dhist n -> print last n entries only\\ |
|
2143 | 2143 | %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\ |
|
2144 | 2144 | |
|
2145 | 2145 | This history is automatically maintained by the %cd command, and |
|
2146 | 2146 | always available as the global list variable _dh. You can use %cd -<n> |
|
2147 | 2147 | to go to directory number <n>.""" |
|
2148 | 2148 | |
|
2149 | 2149 | dh = self.shell.user_ns['_dh'] |
|
2150 | 2150 | if parameter_s: |
|
2151 | 2151 | try: |
|
2152 | 2152 | args = map(int,parameter_s.split()) |
|
2153 | 2153 | except: |
|
2154 | 2154 | self.arg_err(Magic.magic_dhist) |
|
2155 | 2155 | return |
|
2156 | 2156 | if len(args) == 1: |
|
2157 | 2157 | ini,fin = max(len(dh)-(args[0]),0),len(dh) |
|
2158 | 2158 | elif len(args) == 2: |
|
2159 | 2159 | ini,fin = args |
|
2160 | 2160 | else: |
|
2161 | 2161 | self.arg_err(Magic.magic_dhist) |
|
2162 | 2162 | return |
|
2163 | 2163 | else: |
|
2164 | 2164 | ini,fin = 0,len(dh) |
|
2165 | 2165 | nlprint(dh, |
|
2166 | 2166 | header = 'Directory history (kept in _dh)', |
|
2167 | 2167 | start=ini,stop=fin) |
|
2168 | 2168 | |
|
2169 | 2169 | def magic_env(self, parameter_s=''): |
|
2170 | 2170 | """List environment variables.""" |
|
2171 | 2171 | |
|
2172 | 2172 | # environ is an instance of UserDict |
|
2173 | 2173 | return os.environ.data |
|
2174 | 2174 | |
|
2175 | 2175 | def magic_pushd(self, parameter_s=''): |
|
2176 | 2176 | """Place the current dir on stack and change directory. |
|
2177 | 2177 | |
|
2178 | 2178 | Usage:\\ |
|
2179 | 2179 | %pushd ['dirname'] |
|
2180 | 2180 | |
|
2181 | 2181 | %pushd with no arguments does a %pushd to your home directory. |
|
2182 | 2182 | """ |
|
2183 | 2183 | if parameter_s == '': parameter_s = '~' |
|
2184 | 2184 | if len(self.dir_stack)>0 and os.path.expanduser(parameter_s) != \ |
|
2185 | 2185 | os.path.expanduser(self.dir_stack[0]): |
|
2186 | 2186 | try: |
|
2187 | 2187 | self.magic_cd(parameter_s) |
|
2188 | 2188 | self.dir_stack.insert(0,os.getcwd().replace(self.home_dir,'~')) |
|
2189 | 2189 | self.magic_dirs() |
|
2190 | 2190 | except: |
|
2191 | 2191 | print 'Invalid directory' |
|
2192 | 2192 | else: |
|
2193 | 2193 | print 'You are already there!' |
|
2194 | 2194 | |
|
2195 | 2195 | def magic_popd(self, parameter_s=''): |
|
2196 | 2196 | """Change to directory popped off the top of the stack. |
|
2197 | 2197 | """ |
|
2198 | 2198 | if len (self.dir_stack) > 1: |
|
2199 | 2199 | self.dir_stack.pop(0) |
|
2200 | 2200 | self.magic_cd(self.dir_stack[0]) |
|
2201 | 2201 | print self.dir_stack[0] |
|
2202 | 2202 | else: |
|
2203 | 2203 | print "You can't remove the starting directory from the stack:",\ |
|
2204 | 2204 | self.dir_stack |
|
2205 | 2205 | |
|
2206 | 2206 | def magic_dirs(self, parameter_s=''): |
|
2207 | 2207 | """Return the current directory stack.""" |
|
2208 | 2208 | |
|
2209 | 2209 | return self.dir_stack[:] |
|
2210 | 2210 | |
|
2211 | 2211 | def magic_sc(self, parameter_s=''): |
|
2212 | 2212 | """Shell capture - execute a shell command and capture its output. |
|
2213 | 2213 | |
|
2214 | 2214 | %sc [options] varname=command |
|
2215 | 2215 | |
|
2216 | 2216 | IPython will run the given command using commands.getoutput(), and |
|
2217 | 2217 | will then update the user's interactive namespace with a variable |
|
2218 | 2218 | called varname, containing the value of the call. Your command can |
|
2219 | 2219 | contain shell wildcards, pipes, etc. |
|
2220 | 2220 | |
|
2221 | 2221 | The '=' sign in the syntax is mandatory, and the variable name you |
|
2222 | 2222 | supply must follow Python's standard conventions for valid names. |
|
2223 | 2223 | |
|
2224 | 2224 | Options: |
|
2225 | 2225 | |
|
2226 | 2226 | -l: list output. Split the output on newlines into a list before |
|
2227 | 2227 | assigning it to the given variable. By default the output is stored |
|
2228 | 2228 | as a single string. |
|
2229 | 2229 | |
|
2230 | 2230 | -v: verbose. Print the contents of the variable. |
|
2231 | 2231 | |
|
2232 | 2232 | In most cases you should not need to split as a list, because the |
|
2233 | 2233 | returned value is a special type of string which can automatically |
|
2234 | 2234 | provide its contents either as a list (split on newlines) or as a |
|
2235 | 2235 | space-separated string. These are convenient, respectively, either |
|
2236 | 2236 | for sequential processing or to be passed to a shell command. |
|
2237 | 2237 | |
|
2238 | 2238 | For example: |
|
2239 | 2239 | |
|
2240 | 2240 | # Capture into variable a |
|
2241 | 2241 | In [9]: sc a=ls *py |
|
2242 | 2242 | |
|
2243 | 2243 | # a is a string with embedded newlines |
|
2244 | 2244 | In [10]: a |
|
2245 | 2245 | Out[10]: 'setup.py\nwin32_manual_post_install.py' |
|
2246 | 2246 | |
|
2247 | 2247 | # which can be seen as a list: |
|
2248 | 2248 | In [11]: a.l |
|
2249 | 2249 | Out[11]: ['setup.py', 'win32_manual_post_install.py'] |
|
2250 | 2250 | |
|
2251 | 2251 | # or as a whitespace-separated string: |
|
2252 | 2252 | In [12]: a.s |
|
2253 | 2253 | Out[12]: 'setup.py win32_manual_post_install.py' |
|
2254 | 2254 | |
|
2255 | 2255 | # a.s is useful to pass as a single command line: |
|
2256 | 2256 | In [13]: !wc -l $a.s |
|
2257 | 2257 | 146 setup.py |
|
2258 | 2258 | 130 win32_manual_post_install.py |
|
2259 | 2259 | 276 total |
|
2260 | 2260 | |
|
2261 | 2261 | # while the list form is useful to loop over: |
|
2262 | 2262 | In [14]: for f in a.l: |
|
2263 | 2263 | ....: !wc -l $f |
|
2264 | 2264 | ....: |
|
2265 | 2265 | 146 setup.py |
|
2266 | 2266 | 130 win32_manual_post_install.py |
|
2267 | 2267 | |
|
2268 | 2268 | Similiarly, the lists returned by the -l option are also special, in |
|
2269 | 2269 | the sense that you can equally invoke the .s attribute on them to |
|
2270 | 2270 | automatically get a whitespace-separated string from their contents: |
|
2271 | 2271 | |
|
2272 | 2272 | In [1]: sc -l b=ls *py |
|
2273 | 2273 | |
|
2274 | 2274 | In [2]: b |
|
2275 | 2275 | Out[2]: ['setup.py', 'win32_manual_post_install.py'] |
|
2276 | 2276 | |
|
2277 | 2277 | In [3]: b.s |
|
2278 | 2278 | Out[3]: 'setup.py win32_manual_post_install.py' |
|
2279 | 2279 | |
|
2280 | 2280 | In summary, both the lists and strings used for ouptut capture have |
|
2281 | 2281 | the following special attributes: |
|
2282 | 2282 | |
|
2283 | 2283 | .l (or .list) : value as list. |
|
2284 | 2284 | .n (or .nlstr): value as newline-separated string. |
|
2285 | 2285 | .s (or .spstr): value as space-separated string. |
|
2286 | 2286 | """ |
|
2287 | 2287 | |
|
2288 | 2288 | opts,args = self.parse_options(parameter_s,'lv') |
|
2289 | 2289 | # Try to get a variable name and command to run |
|
2290 | 2290 | try: |
|
2291 | 2291 | # the variable name must be obtained from the parse_options |
|
2292 | 2292 | # output, which uses shlex.split to strip options out. |
|
2293 | 2293 | var,_ = args.split('=',1) |
|
2294 | 2294 | var = var.strip() |
|
2295 | 2295 | # But the the command has to be extracted from the original input |
|
2296 | 2296 | # parameter_s, not on what parse_options returns, to avoid the |
|
2297 | 2297 | # quote stripping which shlex.split performs on it. |
|
2298 | 2298 | _,cmd = parameter_s.split('=',1) |
|
2299 | 2299 | except ValueError: |
|
2300 | 2300 | var,cmd = '','' |
|
2301 | 2301 | if not var: |
|
2302 | 2302 | error('you must specify a variable to assign the command to.') |
|
2303 | 2303 | return |
|
2304 | 2304 | # If all looks ok, proceed |
|
2305 | 2305 | out,err = self.shell.getoutputerror(cmd) |
|
2306 | 2306 | if err: |
|
2307 | 2307 | print >> Term.cerr,err |
|
2308 | 2308 | if opts.has_key('l'): |
|
2309 | 2309 | out = SList(out.split('\n')) |
|
2310 | 2310 | else: |
|
2311 | 2311 | out = LSString(out) |
|
2312 | 2312 | if opts.has_key('v'): |
|
2313 | 2313 | print '%s ==\n%s' % (var,pformat(out)) |
|
2314 | 2314 | self.shell.user_ns.update({var:out}) |
|
2315 | 2315 | |
|
2316 | 2316 | def magic_sx(self, parameter_s=''): |
|
2317 | 2317 | """Shell execute - run a shell command and capture its output. |
|
2318 | 2318 | |
|
2319 | 2319 | %sx command |
|
2320 | 2320 | |
|
2321 | 2321 | IPython will run the given command using commands.getoutput(), and |
|
2322 | 2322 | return the result formatted as a list (split on '\\n'). Since the |
|
2323 | 2323 | output is _returned_, it will be stored in ipython's regular output |
|
2324 | 2324 | cache Out[N] and in the '_N' automatic variables. |
|
2325 | 2325 | |
|
2326 | 2326 | Notes: |
|
2327 | 2327 | |
|
2328 | 2328 | 1) If an input line begins with '!!', then %sx is automatically |
|
2329 | 2329 | invoked. That is, while: |
|
2330 | 2330 | !ls |
|
2331 | 2331 | causes ipython to simply issue system('ls'), typing |
|
2332 | 2332 | !!ls |
|
2333 | 2333 | is a shorthand equivalent to: |
|
2334 | 2334 | %sx ls |
|
2335 | 2335 | |
|
2336 | 2336 | 2) %sx differs from %sc in that %sx automatically splits into a list, |
|
2337 | 2337 | like '%sc -l'. The reason for this is to make it as easy as possible |
|
2338 | 2338 | to process line-oriented shell output via further python commands. |
|
2339 | 2339 | %sc is meant to provide much finer control, but requires more |
|
2340 | 2340 | typing. |
|
2341 | 2341 | |
|
2342 | 2342 | 3) Just like %sc -l, this is a list with special attributes: |
|
2343 | 2343 | |
|
2344 | 2344 | .l (or .list) : value as list. |
|
2345 | 2345 | .n (or .nlstr): value as newline-separated string. |
|
2346 | 2346 | .s (or .spstr): value as whitespace-separated string. |
|
2347 | 2347 | |
|
2348 | 2348 | This is very useful when trying to use such lists as arguments to |
|
2349 | 2349 | system commands.""" |
|
2350 | 2350 | |
|
2351 | 2351 | if parameter_s: |
|
2352 | 2352 | out,err = self.shell.getoutputerror(parameter_s) |
|
2353 | 2353 | if err: |
|
2354 | 2354 | print >> Term.cerr,err |
|
2355 | 2355 | return SList(out.split('\n')) |
|
2356 | 2356 | |
|
2357 | 2357 | def magic_bg(self, parameter_s=''): |
|
2358 | 2358 | """Run a job in the background, in a separate thread. |
|
2359 | 2359 | |
|
2360 | 2360 | For example, |
|
2361 | 2361 | |
|
2362 | 2362 | %bg myfunc(x,y,z=1) |
|
2363 | 2363 | |
|
2364 | 2364 | will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the |
|
2365 | 2365 | execution starts, a message will be printed indicating the job |
|
2366 | 2366 | number. If your job number is 5, you can use |
|
2367 | 2367 | |
|
2368 | 2368 | myvar = jobs.result(5) or myvar = jobs[5].result |
|
2369 | 2369 | |
|
2370 | 2370 | to assign this result to variable 'myvar'. |
|
2371 | 2371 | |
|
2372 | 2372 | IPython has a job manager, accessible via the 'jobs' object. You can |
|
2373 | 2373 | type jobs? to get more information about it, and use jobs.<TAB> to see |
|
2374 | 2374 | its attributes. All attributes not starting with an underscore are |
|
2375 | 2375 | meant for public use. |
|
2376 | 2376 | |
|
2377 | 2377 | In particular, look at the jobs.new() method, which is used to create |
|
2378 | 2378 | new jobs. This magic %bg function is just a convenience wrapper |
|
2379 | 2379 | around jobs.new(), for expression-based jobs. If you want to create a |
|
2380 | 2380 | new job with an explicit function object and arguments, you must call |
|
2381 | 2381 | jobs.new() directly. |
|
2382 | 2382 | |
|
2383 | 2383 | The jobs.new docstring also describes in detail several important |
|
2384 | 2384 | caveats associated with a thread-based model for background job |
|
2385 | 2385 | execution. Type jobs.new? for details. |
|
2386 | 2386 | |
|
2387 | 2387 | You can check the status of all jobs with jobs.status(). |
|
2388 | 2388 | |
|
2389 | 2389 | The jobs variable is set by IPython into the Python builtin namespace. |
|
2390 | 2390 | If you ever declare a variable named 'jobs', you will shadow this |
|
2391 | 2391 | name. You can either delete your global jobs variable to regain |
|
2392 | 2392 | access to the job manager, or make a new name and assign it manually |
|
2393 | 2393 | to the manager (stored in IPython's namespace). For example, to |
|
2394 | 2394 | assign the job manager to the Jobs name, use: |
|
2395 | 2395 | |
|
2396 | 2396 | Jobs = __builtins__.jobs""" |
|
2397 | 2397 | |
|
2398 | 2398 | self.shell.jobs.new(parameter_s,self.shell.user_ns) |
|
2399 | 2399 | |
|
2400 | 2400 | def magic_bookmark(self, parameter_s=''): |
|
2401 | 2401 | """Manage IPython's bookmark system. |
|
2402 | 2402 | |
|
2403 | 2403 | %bookmark <name> - set bookmark to current dir |
|
2404 | 2404 | %bookmark <name> <dir> - set bookmark to <dir> |
|
2405 | 2405 | %bookmark -l - list all bookmarks |
|
2406 | 2406 | %bookmark -d <name> - remove bookmark |
|
2407 | 2407 | %bookmark -r - remove all bookmarks |
|
2408 | 2408 | |
|
2409 | 2409 | You can later on access a bookmarked folder with: |
|
2410 | 2410 | %cd -b <name> |
|
2411 | 2411 | or simply '%cd <name>' if there is no directory called <name> AND |
|
2412 | 2412 | there is such a bookmark defined. |
|
2413 | 2413 | |
|
2414 | 2414 | Your bookmarks persist through IPython sessions, but they are |
|
2415 | 2415 | associated with each profile.""" |
|
2416 | 2416 | |
|
2417 | 2417 | opts,args = self.parse_options(parameter_s,'drl',mode='list') |
|
2418 | 2418 | if len(args) > 2: |
|
2419 | 2419 | error('You can only give at most two arguments') |
|
2420 | 2420 | return |
|
2421 | 2421 | |
|
2422 | 2422 | bkms = self.shell.persist.get('bookmarks',{}) |
|
2423 | 2423 | |
|
2424 | 2424 | if opts.has_key('d'): |
|
2425 | 2425 | try: |
|
2426 | 2426 | todel = args[0] |
|
2427 | 2427 | except IndexError: |
|
2428 | 2428 | error('You must provide a bookmark to delete') |
|
2429 | 2429 | else: |
|
2430 | 2430 | try: |
|
2431 | 2431 | del bkms[todel] |
|
2432 | 2432 | except: |
|
2433 | 2433 | error("Can't delete bookmark '%s'" % todel) |
|
2434 | 2434 | elif opts.has_key('r'): |
|
2435 | 2435 | bkms = {} |
|
2436 | 2436 | elif opts.has_key('l'): |
|
2437 | 2437 | bks = bkms.keys() |
|
2438 | 2438 | bks.sort() |
|
2439 | 2439 | if bks: |
|
2440 | 2440 | size = max(map(len,bks)) |
|
2441 | 2441 | else: |
|
2442 | 2442 | size = 0 |
|
2443 | 2443 | fmt = '%-'+str(size)+'s -> %s' |
|
2444 | 2444 | print 'Current bookmarks:' |
|
2445 | 2445 | for bk in bks: |
|
2446 | 2446 | print fmt % (bk,bkms[bk]) |
|
2447 | 2447 | else: |
|
2448 | 2448 | if not args: |
|
2449 | 2449 | error("You must specify the bookmark name") |
|
2450 | 2450 | elif len(args)==1: |
|
2451 | 2451 | bkms[args[0]] = os.getcwd() |
|
2452 | 2452 | elif len(args)==2: |
|
2453 | 2453 | bkms[args[0]] = args[1] |
|
2454 | 2454 | self.persist['bookmarks'] = bkms |
|
2455 | 2455 | |
|
2456 | 2456 | def magic_pycat(self, parameter_s=''): |
|
2457 | 2457 | """Show a syntax-highlighted file through a pager. |
|
2458 | 2458 | |
|
2459 | 2459 | This magic is similar to the cat utility, but it will assume the file |
|
2460 | 2460 | to be Python source and will show it with syntax highlighting. """ |
|
2461 | 2461 | |
|
2462 | 2462 | try: |
|
2463 | 2463 | filename = get_py_filename(parameter_s) |
|
2464 | 2464 | except IndexError: |
|
2465 | 2465 | warn('you must provide at least a filename.') |
|
2466 | return | |
|
2466 | 2467 | fobj=open(filename,'r') |
|
2467 | 2468 | source = fobj.read() |
|
2468 | 2469 | fobj.close() |
|
2469 | 2470 | colorize = Parser().format |
|
2470 | 2471 | colorized_src = colorize(source,'str',self.shell.rc['colors']) |
|
2471 | 2472 | page(colorized_src,screen_lines=self.shell.rc.screen_length) |
|
2472 | 2473 | |
|
2473 | 2474 | # end Magic |
@@ -1,178 +1,201 b'' | |||
|
1 | 1 | """Module for interactive demos using IPython. |
|
2 | 2 | |
|
3 | 3 | Sorry, but this uses Python 2.3 features, so it won't work in 2.2 environments. |
|
4 | 4 | """ |
|
5 | 5 | #***************************************************************************** |
|
6 | 6 | # Copyright (C) 2005 Fernando Perez. <Fernando.Perez@colorado.edu> |
|
7 | 7 | # |
|
8 | 8 | # Distributed under the terms of the BSD License. The full license is in |
|
9 | 9 | # the file COPYING, distributed as part of this software. |
|
10 | 10 | # |
|
11 | 11 | #***************************************************************************** |
|
12 | 12 | |
|
13 | 13 | import sys |
|
14 | 14 | import exceptions |
|
15 | 15 | import re |
|
16 | 16 | |
|
17 | 17 | from IPython.PyColorize import Parser |
|
18 | 18 | from IPython.genutils import marquee, shlex_split |
|
19 | 19 | |
|
20 | 20 | class DemoError(exceptions.Exception): pass |
|
21 | 21 | |
|
22 | 22 | class Demo: |
|
23 | 23 | def __init__(self,fname,arg_str='',mark_pause='# pause', |
|
24 | mark_silent='# silent',auto=False): | |
|
24 | mark_silent='# silent',mark_auto='# auto',auto=False): | |
|
25 | 25 | """Make a new demo object. To run the demo, simply call the object. |
|
26 | 26 | |
|
27 | 27 | Inputs: |
|
28 | 28 | |
|
29 | 29 | - fname = filename. |
|
30 | 30 | |
|
31 | 31 | Optional inputs: |
|
32 | 32 | |
|
33 | 33 | - arg_str(''): a string of arguments, internally converted to a list |
|
34 | 34 | just like sys.argv, so the demo script can see a similar |
|
35 | 35 | environment. |
|
36 | 36 | |
|
37 |
- mark_pause ('# pause') |
|
|
38 | (block boundaries) and to tag blocks as silent. The marks are | |
|
39 | turned into regexps which match them as standalone in a line, with | |
|
40 | all leading/trailing whitespace ignored. | |
|
41 | ||
|
42 | - auto(False): flag to run each block automatically without | |
|
43 |
|
|
|
44 | executed. This flag is an attribute of the object, and can be | |
|
45 | changed at runtime simply by reassigning it. | |
|
37 | - mark_pause ('# pause'): marks for pausing (block boundaries). The | |
|
38 | marks are turned into regexps which match them as standalone in a | |
|
39 | line, with all leading/trailing whitespace ignored. | |
|
40 | ||
|
41 | - mark_silent('# silent'): mark blocks as silent, which means that | |
|
42 | they are executed without printing their content to screen. Silent | |
|
43 | blocks are always automatically executed. | |
|
44 | ||
|
45 | - mark_auto ('# auto'): mark individual blocks as automatically | |
|
46 | executed (without asking for confirmation). | |
|
47 | ||
|
48 | - auto(False): global flag to run all blocks automatically without | |
|
49 | confirmation. This attribute overrides the block-level tags and | |
|
50 | applies to the whole demo. It is an attribute of the object, and | |
|
51 | can be changed at runtime simply by reassigning it to a boolean | |
|
52 | value. | |
|
46 | 53 | """ |
|
47 | 54 | |
|
48 | self.fname = fname | |
|
49 | self.mark_pause = mark_pause | |
|
50 | self.re_pause = re.compile(r'^\s*%s\s*$' % mark_pause,re.MULTILINE) | |
|
55 | self.fname = fname | |
|
56 | self.sys_argv = [fname] + shlex_split(arg_str) | |
|
57 | self.mark_pause = mark_pause | |
|
51 | 58 | self.mark_silent = mark_silent |
|
52 |
self.re_ |
|
|
53 | self.auto = auto | |
|
54 | self.sys_argv = [fname]+shlex_split(arg_str) | |
|
59 | self.re_pause = re.compile(r'^\s*%s\s*$' % mark_pause,re.MULTILINE) | |
|
60 | self.re_silent = re.compile(r'^\s*%s\s*$' % mark_silent,re.MULTILINE) | |
|
61 | self.re_auto = re.compile(r'^\s*%s\s*$' % mark_auto,re.MULTILINE) | |
|
62 | self.auto = auto | |
|
55 | 63 | |
|
56 | 64 | # get a few things from ipython. While it's a bit ugly design-wise, |
|
57 | 65 | # it ensures that things like color scheme and the like are always in |
|
58 | 66 | # sync with the ipython mode being used. This class is only meant to |
|
59 | 67 | # be used inside ipython anyways, so it's OK. |
|
60 |
self.ip_showt |
|
|
61 | self.ip_ns = __IPYTHON__.user_ns | |
|
68 | self.ip_showtb = __IPYTHON__.showtraceback | |
|
69 | self.ip_ns = __IPYTHON__.user_ns | |
|
62 | 70 | self.ip_colors = __IPYTHON__.rc['colors'] |
|
71 | self.colorize = Parser().format | |
|
72 | ||
|
73 | # load user data and initialize data structures | |
|
74 | self.reload() | |
|
63 | 75 | |
|
76 | def reload(self): | |
|
77 | """Reload source from disk and initialize state.""" | |
|
64 | 78 | # read data and parse into blocks |
|
65 | fobj = file(fname,'r') | |
|
79 | fobj = file(self.fname,'r') | |
|
66 | 80 | self.src = fobj.read() |
|
67 | 81 | fobj.close() |
|
68 |
|
|
|
69 |
self.silent = [bool(self.re_silent.findall(b)) for b in |
|
|
70 | self.nblocks = len(self.src_blocks) | |
|
82 | src_blocks = [b.strip() for b in self.re_pause.split(self.src) if b] | |
|
83 | self._silent = [bool(self.re_silent.findall(b)) for b in src_blocks] | |
|
84 | self._auto = [bool(self.re_auto.findall(b)) for b in src_blocks] | |
|
85 | # strip out the 'auto' markers | |
|
86 | src_b = [] | |
|
87 | auto_strip = lambda s: self.re_auto.sub('',s) | |
|
88 | for i,b in enumerate(src_blocks): | |
|
89 | if self._auto[i]: | |
|
90 | src_b.append(auto_strip(b)) | |
|
91 | else: | |
|
92 | src_b.append(b) | |
|
93 | self.nblocks = len(src_b) | |
|
94 | self.src_blocks = src_b | |
|
71 | 95 | |
|
72 | 96 | # try to colorize blocks |
|
73 | colorize = Parser().format | |
|
74 | 97 | col_scheme = self.ip_colors |
|
75 | self.src_blocks_colored = [colorize(s_blk,'str',col_scheme) | |
|
98 | self.src_blocks_colored = [self.colorize(s_blk,'str',col_scheme) | |
|
76 | 99 | for s_blk in self.src_blocks] |
|
77 | ||
|
78 | # finish initialization | |
|
100 | # ensure clean namespace and seek offset | |
|
79 | 101 | self.reset() |
|
80 | 102 | |
|
81 | 103 | def reset(self): |
|
82 | 104 | """Reset the namespace and seek pointer to restart the demo""" |
|
83 | 105 | self.user_ns = {} |
|
84 | 106 | self.finished = False |
|
85 | 107 | self.block_index = 0 |
|
86 | 108 | |
|
87 | 109 | def again(self): |
|
88 | 110 | """Repeat the last block""" |
|
89 | 111 | self.block_index -= 1 |
|
90 | 112 | self.finished = False |
|
91 | 113 | self() |
|
92 | 114 | |
|
93 | 115 | def _validate_index(self,index): |
|
94 | 116 | if index<0 or index>=self.nblocks: |
|
95 | 117 | raise ValueError('invalid block index %s' % index) |
|
96 | 118 | |
|
97 | 119 | def seek(self,index): |
|
98 | 120 | """Move the current seek pointer to the given block""" |
|
99 | 121 | self._validate_index(index) |
|
100 |
self.block_index = index |
|
|
122 | self.block_index = index | |
|
101 | 123 | self.finished = False |
|
102 | 124 | |
|
103 |
def show |
|
|
125 | def show(self,index=None): | |
|
104 | 126 | """Show a single block on screen""" |
|
105 | 127 | if index is None: |
|
106 | 128 | if self.finished: |
|
107 | 129 | print 'Demo finished. Use reset() if you want to rerun it.' |
|
108 | 130 | return |
|
109 | 131 | index = self.block_index |
|
110 | 132 | else: |
|
111 | 133 | self._validate_index(index) |
|
112 | 134 | print marquee('<%s> block # %s (%s remaining)' % |
|
113 | 135 | (self.fname,index,self.nblocks-index-1)) |
|
114 | 136 | print self.src_blocks_colored[index], |
|
115 | 137 | |
|
116 | def show(self): | |
|
138 | def show_all(self): | |
|
117 | 139 | """Show entire demo on screen, block by block""" |
|
118 | 140 | |
|
119 | 141 | fname = self.fname |
|
120 | 142 | nblocks = self.nblocks |
|
121 | silent = self.silent | |
|
143 | silent = self._silent | |
|
122 | 144 | for index,block in enumerate(self.src_blocks_colored): |
|
123 | 145 | if silent[index]: |
|
124 | 146 | print marquee('<%s> SILENT block # %s (%s remaining)' % |
|
125 | 147 | (fname,index,nblocks-index-1)) |
|
126 | 148 | else: |
|
127 | 149 | print marquee('<%s> block # %s (%s remaining)' % |
|
128 | 150 | (fname,index,nblocks-index-1)) |
|
129 | 151 | print block, |
|
130 | 152 | |
|
131 | 153 | def __call__(self,index=None): |
|
132 | 154 | """run a block of the demo. |
|
133 | 155 | |
|
134 | 156 | If index is given, it should be an integer >=1 and <= nblocks. This |
|
135 | 157 | means that the calling convention is one off from typical Python |
|
136 | 158 | lists. The reason for the inconsistency is that the demo always |
|
137 | 159 | prints 'Block n/N, and N is the total, so it would be very odd to use |
|
138 | 160 | zero-indexing here.""" |
|
139 | 161 | |
|
140 | 162 | if index is None and self.finished: |
|
141 | 163 | print 'Demo finished. Use reset() if you want to rerun it.' |
|
142 | 164 | return |
|
143 | 165 | if index is None: |
|
144 | 166 | index = self.block_index |
|
145 | 167 | self._validate_index(index) |
|
146 | 168 | try: |
|
147 | 169 | next_block = self.src_blocks[index] |
|
148 | 170 | self.block_index += 1 |
|
149 | if self.silent[index]: | |
|
171 | if self._silent[index]: | |
|
150 | 172 | print marquee('Executing silent block # %s (%s remaining)' % |
|
151 | 173 | (index,self.nblocks-index-1)) |
|
152 | 174 | else: |
|
153 |
self.show |
|
|
154 | if self.auto: | |
|
175 | self.show(index) | |
|
176 | if self.auto or self._auto[index]: | |
|
155 | 177 | print marquee('output') |
|
156 | 178 | else: |
|
157 | 179 | print marquee('Press <q> to quit, <Enter> to execute...'), |
|
158 | 180 | ans = raw_input().strip() |
|
159 | 181 | if ans: |
|
160 | 182 | print marquee('Block NOT executed') |
|
161 | 183 | return |
|
162 | 184 | try: |
|
163 | 185 | save_argv = sys.argv |
|
164 | 186 | sys.argv = self.sys_argv |
|
165 | 187 | exec next_block in self.user_ns |
|
166 | 188 | finally: |
|
167 | 189 | sys.argv = save_argv |
|
168 | 190 | |
|
169 | 191 | except: |
|
170 |
self.ip_showt |
|
|
192 | self.ip_showtb(filename=self.fname) | |
|
171 | 193 | else: |
|
172 | 194 | self.ip_ns.update(self.user_ns) |
|
173 | 195 | |
|
174 | 196 | if self.block_index == self.nblocks: |
|
175 | 197 | |
|
176 | 198 | print marquee(' END OF DEMO ') |
|
177 | 199 | print marquee('Use reset() if you want to rerun it.') |
|
178 | 200 | self.finished = True |
|
201 |
|
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