Show More
@@ -1,3024 +1,3014 b'' | |||
|
1 | 1 | # -*- coding: utf-8 -*- |
|
2 | 2 | """Magic functions for InteractiveShell. |
|
3 | 3 | |
|
4 |
$Id: Magic.py 18 |
|
|
4 | $Id: Magic.py 1845 2006-10-27 20:35:47Z fptest $""" | |
|
5 | 5 | |
|
6 | 6 | #***************************************************************************** |
|
7 | 7 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and |
|
8 | 8 | # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu> |
|
9 | 9 | # |
|
10 | 10 | # Distributed under the terms of the BSD License. The full license is in |
|
11 | 11 | # the file COPYING, distributed as part of this software. |
|
12 | 12 | #***************************************************************************** |
|
13 | 13 | |
|
14 | 14 | #**************************************************************************** |
|
15 | 15 | # Modules and globals |
|
16 | 16 | |
|
17 | 17 | from IPython import Release |
|
18 | 18 | __author__ = '%s <%s>\n%s <%s>' % \ |
|
19 | 19 | ( Release.authors['Janko'] + Release.authors['Fernando'] ) |
|
20 | 20 | __license__ = Release.license |
|
21 | 21 | |
|
22 | 22 | # Python standard modules |
|
23 | 23 | import __builtin__ |
|
24 | 24 | import bdb |
|
25 | 25 | import inspect |
|
26 | 26 | import os |
|
27 | 27 | import pdb |
|
28 | 28 | import pydoc |
|
29 | import shlex | |
|
30 | 29 | import sys |
|
31 | 30 | import re |
|
32 | 31 | import tempfile |
|
33 | 32 | import time |
|
34 | 33 | import cPickle as pickle |
|
35 | 34 | import textwrap |
|
36 | 35 | from cStringIO import StringIO |
|
37 | 36 | from getopt import getopt,GetoptError |
|
38 | 37 | from pprint import pprint, pformat |
|
39 | 38 | |
|
40 | 39 | # profile isn't bundled by default in Debian for license reasons |
|
41 | 40 | try: |
|
42 | 41 | import profile,pstats |
|
43 | 42 | except ImportError: |
|
44 | 43 | profile = pstats = None |
|
45 | 44 | |
|
46 | 45 | # Homebrewed |
|
47 | 46 | import IPython |
|
48 | 47 | from IPython import Debugger, OInspect, wildcard |
|
49 | 48 | from IPython.FakeModule import FakeModule |
|
50 | 49 | from IPython.Itpl import Itpl, itpl, printpl,itplns |
|
51 | 50 | from IPython.PyColorize import Parser |
|
52 | 51 | from IPython.ipstruct import Struct |
|
53 | 52 | from IPython.macro import Macro |
|
54 | 53 | from IPython.genutils import * |
|
55 | 54 | from IPython import platutils |
|
56 | 55 | |
|
57 | 56 | #*************************************************************************** |
|
58 | 57 | # Utility functions |
|
59 | 58 | def on_off(tag): |
|
60 | 59 | """Return an ON/OFF string for a 1/0 input. Simple utility function.""" |
|
61 | 60 | return ['OFF','ON'][tag] |
|
62 | 61 | |
|
63 | 62 | class Bunch: pass |
|
64 | 63 | |
|
65 | def arg_split(s,posix=True): | |
|
66 | """Split a command line's arguments in a shell-like manner. | |
|
67 | ||
|
68 | This is a modified version of the standard library's shlex.split() | |
|
69 | function, but with a default of posix=False for splitting, so that quotes | |
|
70 | in inputs are respected.""" | |
|
71 | ||
|
72 | lex = shlex.shlex(s, posix=posix) | |
|
73 | lex.whitespace_split = True | |
|
74 | return list(lex) | |
|
75 | ||
|
76 | 64 | #*************************************************************************** |
|
77 | 65 | # Main class implementing Magic functionality |
|
78 | 66 | class Magic: |
|
79 | 67 | """Magic functions for InteractiveShell. |
|
80 | 68 | |
|
81 | 69 | Shell functions which can be reached as %function_name. All magic |
|
82 | 70 | functions should accept a string, which they can parse for their own |
|
83 | 71 | needs. This can make some functions easier to type, eg `%cd ../` |
|
84 | 72 | vs. `%cd("../")` |
|
85 | 73 | |
|
86 | 74 | ALL definitions MUST begin with the prefix magic_. The user won't need it |
|
87 | 75 | at the command line, but it is is needed in the definition. """ |
|
88 | 76 | |
|
89 | 77 | # class globals |
|
90 | 78 | auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.', |
|
91 | 79 | 'Automagic is ON, % prefix NOT needed for magic functions.'] |
|
92 | 80 | |
|
93 | 81 | #...................................................................... |
|
94 | 82 | # some utility functions |
|
95 | 83 | |
|
96 | 84 | def __init__(self,shell): |
|
97 | 85 | |
|
98 | 86 | self.options_table = {} |
|
99 | 87 | if profile is None: |
|
100 | 88 | self.magic_prun = self.profile_missing_notice |
|
101 | 89 | self.shell = shell |
|
102 | 90 | |
|
103 | 91 | # namespace for holding state we may need |
|
104 | 92 | self._magic_state = Bunch() |
|
105 | 93 | |
|
106 | 94 | def profile_missing_notice(self, *args, **kwargs): |
|
107 | 95 | error("""\ |
|
108 | 96 | The profile module could not be found. If you are a Debian user, |
|
109 | 97 | it has been removed from the standard Debian package because of its non-free |
|
110 | 98 | license. To use profiling, please install"python2.3-profiler" from non-free.""") |
|
111 | 99 | |
|
112 | 100 | def default_option(self,fn,optstr): |
|
113 | 101 | """Make an entry in the options_table for fn, with value optstr""" |
|
114 | 102 | |
|
115 | 103 | if fn not in self.lsmagic(): |
|
116 | 104 | error("%s is not a magic function" % fn) |
|
117 | 105 | self.options_table[fn] = optstr |
|
118 | 106 | |
|
119 | 107 | def lsmagic(self): |
|
120 | 108 | """Return a list of currently available magic functions. |
|
121 | 109 | |
|
122 | 110 | Gives a list of the bare names after mangling (['ls','cd', ...], not |
|
123 | 111 | ['magic_ls','magic_cd',...]""" |
|
124 | 112 | |
|
125 | 113 | # FIXME. This needs a cleanup, in the way the magics list is built. |
|
126 | 114 | |
|
127 | 115 | # magics in class definition |
|
128 | 116 | class_magic = lambda fn: fn.startswith('magic_') and \ |
|
129 | 117 | callable(Magic.__dict__[fn]) |
|
130 | 118 | # in instance namespace (run-time user additions) |
|
131 | 119 | inst_magic = lambda fn: fn.startswith('magic_') and \ |
|
132 | 120 | callable(self.__dict__[fn]) |
|
133 | 121 | # and bound magics by user (so they can access self): |
|
134 | 122 | inst_bound_magic = lambda fn: fn.startswith('magic_') and \ |
|
135 | 123 | callable(self.__class__.__dict__[fn]) |
|
136 | 124 | magics = filter(class_magic,Magic.__dict__.keys()) + \ |
|
137 | 125 | filter(inst_magic,self.__dict__.keys()) + \ |
|
138 | 126 | filter(inst_bound_magic,self.__class__.__dict__.keys()) |
|
139 | 127 | out = [] |
|
140 | 128 | for fn in magics: |
|
141 | 129 | out.append(fn.replace('magic_','',1)) |
|
142 | 130 | out.sort() |
|
143 | 131 | return out |
|
144 | 132 | |
|
145 | 133 | def extract_input_slices(self,slices,raw=False): |
|
146 | 134 | """Return as a string a set of input history slices. |
|
147 | 135 | |
|
148 | 136 | Inputs: |
|
149 | 137 | |
|
150 | 138 | - slices: the set of slices is given as a list of strings (like |
|
151 | 139 | ['1','4:8','9'], since this function is for use by magic functions |
|
152 | 140 | which get their arguments as strings. |
|
153 | 141 | |
|
154 | 142 | Optional inputs: |
|
155 | 143 | |
|
156 | 144 | - raw(False): by default, the processed input is used. If this is |
|
157 | 145 | true, the raw input history is used instead. |
|
158 | 146 | |
|
159 | 147 | Note that slices can be called with two notations: |
|
160 | 148 | |
|
161 | 149 | N:M -> standard python form, means including items N...(M-1). |
|
162 | 150 | |
|
163 | 151 | N-M -> include items N..M (closed endpoint).""" |
|
164 | 152 | |
|
165 | 153 | if raw: |
|
166 | 154 | hist = self.shell.input_hist_raw |
|
167 | 155 | else: |
|
168 | 156 | hist = self.shell.input_hist |
|
169 | 157 | |
|
170 | 158 | cmds = [] |
|
171 | 159 | for chunk in slices: |
|
172 | 160 | if ':' in chunk: |
|
173 | 161 | ini,fin = map(int,chunk.split(':')) |
|
174 | 162 | elif '-' in chunk: |
|
175 | 163 | ini,fin = map(int,chunk.split('-')) |
|
176 | 164 | fin += 1 |
|
177 | 165 | else: |
|
178 | 166 | ini = int(chunk) |
|
179 | 167 | fin = ini+1 |
|
180 | 168 | cmds.append(hist[ini:fin]) |
|
181 | 169 | return cmds |
|
182 | 170 | |
|
183 | 171 | def _ofind(self, oname, namespaces=None): |
|
184 | 172 | """Find an object in the available namespaces. |
|
185 | 173 | |
|
186 | 174 | self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic |
|
187 | 175 | |
|
188 | 176 | Has special code to detect magic functions. |
|
189 | 177 | """ |
|
190 | 178 | |
|
191 | 179 | oname = oname.strip() |
|
192 | 180 | |
|
193 | 181 | alias_ns = None |
|
194 | 182 | if namespaces is None: |
|
195 | 183 | # Namespaces to search in: |
|
196 | 184 | # Put them in a list. The order is important so that we |
|
197 | 185 | # find things in the same order that Python finds them. |
|
198 | 186 | namespaces = [ ('Interactive', self.shell.user_ns), |
|
199 | 187 | ('IPython internal', self.shell.internal_ns), |
|
200 | 188 | ('Python builtin', __builtin__.__dict__), |
|
201 | 189 | ('Alias', self.shell.alias_table), |
|
202 | 190 | ] |
|
203 | 191 | alias_ns = self.shell.alias_table |
|
204 | 192 | |
|
205 | 193 | # initialize results to 'null' |
|
206 | 194 | found = 0; obj = None; ospace = None; ds = None; |
|
207 | 195 | ismagic = 0; isalias = 0; parent = None |
|
208 | 196 | |
|
209 | 197 | # Look for the given name by splitting it in parts. If the head is |
|
210 | 198 | # found, then we look for all the remaining parts as members, and only |
|
211 | 199 | # declare success if we can find them all. |
|
212 | 200 | oname_parts = oname.split('.') |
|
213 | 201 | oname_head, oname_rest = oname_parts[0],oname_parts[1:] |
|
214 | 202 | for nsname,ns in namespaces: |
|
215 | 203 | try: |
|
216 | 204 | obj = ns[oname_head] |
|
217 | 205 | except KeyError: |
|
218 | 206 | continue |
|
219 | 207 | else: |
|
220 | 208 | for part in oname_rest: |
|
221 | 209 | try: |
|
222 | 210 | parent = obj |
|
223 | 211 | obj = getattr(obj,part) |
|
224 | 212 | except: |
|
225 | 213 | # Blanket except b/c some badly implemented objects |
|
226 | 214 | # allow __getattr__ to raise exceptions other than |
|
227 | 215 | # AttributeError, which then crashes IPython. |
|
228 | 216 | break |
|
229 | 217 | else: |
|
230 | 218 | # If we finish the for loop (no break), we got all members |
|
231 | 219 | found = 1 |
|
232 | 220 | ospace = nsname |
|
233 | 221 | if ns == alias_ns: |
|
234 | 222 | isalias = 1 |
|
235 | 223 | break # namespace loop |
|
236 | 224 | |
|
237 | 225 | # Try to see if it's magic |
|
238 | 226 | if not found: |
|
239 | 227 | if oname.startswith(self.shell.ESC_MAGIC): |
|
240 | 228 | oname = oname[1:] |
|
241 | 229 | obj = getattr(self,'magic_'+oname,None) |
|
242 | 230 | if obj is not None: |
|
243 | 231 | found = 1 |
|
244 | 232 | ospace = 'IPython internal' |
|
245 | 233 | ismagic = 1 |
|
246 | 234 | |
|
247 | 235 | # Last try: special-case some literals like '', [], {}, etc: |
|
248 | 236 | if not found and oname_head in ["''",'""','[]','{}','()']: |
|
249 | 237 | obj = eval(oname_head) |
|
250 | 238 | found = 1 |
|
251 | 239 | ospace = 'Interactive' |
|
252 | 240 | |
|
253 | 241 | return {'found':found, 'obj':obj, 'namespace':ospace, |
|
254 | 242 | 'ismagic':ismagic, 'isalias':isalias, 'parent':parent} |
|
255 | 243 | |
|
256 | 244 | def arg_err(self,func): |
|
257 | 245 | """Print docstring if incorrect arguments were passed""" |
|
258 | 246 | print 'Error in arguments:' |
|
259 | 247 | print OInspect.getdoc(func) |
|
260 | 248 | |
|
261 | 249 | def format_latex(self,strng): |
|
262 | 250 | """Format a string for latex inclusion.""" |
|
263 | 251 | |
|
264 | 252 | # Characters that need to be escaped for latex: |
|
265 | 253 | escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE) |
|
266 | 254 | # Magic command names as headers: |
|
267 | 255 | cmd_name_re = re.compile(r'^(%s.*?):' % self.shell.ESC_MAGIC, |
|
268 | 256 | re.MULTILINE) |
|
269 | 257 | # Magic commands |
|
270 | 258 | cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % self.shell.ESC_MAGIC, |
|
271 | 259 | re.MULTILINE) |
|
272 | 260 | # Paragraph continue |
|
273 | 261 | par_re = re.compile(r'\\$',re.MULTILINE) |
|
274 | 262 | |
|
275 | 263 | # The "\n" symbol |
|
276 | 264 | newline_re = re.compile(r'\\n') |
|
277 | 265 | |
|
278 | 266 | # Now build the string for output: |
|
279 | 267 | #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng) |
|
280 | 268 | strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:', |
|
281 | 269 | strng) |
|
282 | 270 | strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng) |
|
283 | 271 | strng = par_re.sub(r'\\\\',strng) |
|
284 | 272 | strng = escape_re.sub(r'\\\1',strng) |
|
285 | 273 | strng = newline_re.sub(r'\\textbackslash{}n',strng) |
|
286 | 274 | return strng |
|
287 | 275 | |
|
288 | 276 | def format_screen(self,strng): |
|
289 | 277 | """Format a string for screen printing. |
|
290 | 278 | |
|
291 | 279 | This removes some latex-type format codes.""" |
|
292 | 280 | # Paragraph continue |
|
293 | 281 | par_re = re.compile(r'\\$',re.MULTILINE) |
|
294 | 282 | strng = par_re.sub('',strng) |
|
295 | 283 | return strng |
|
296 | 284 | |
|
297 | 285 | def parse_options(self,arg_str,opt_str,*long_opts,**kw): |
|
298 | 286 | """Parse options passed to an argument string. |
|
299 | 287 | |
|
300 | 288 | The interface is similar to that of getopt(), but it returns back a |
|
301 | 289 | Struct with the options as keys and the stripped argument string still |
|
302 | 290 | as a string. |
|
303 | 291 | |
|
304 | 292 | arg_str is quoted as a true sys.argv vector by using shlex.split. |
|
305 | 293 | This allows us to easily expand variables, glob files, quote |
|
306 | 294 | arguments, etc. |
|
307 | 295 | |
|
308 | 296 | Options: |
|
309 | 297 | -mode: default 'string'. If given as 'list', the argument string is |
|
310 | 298 | returned as a list (split on whitespace) instead of a string. |
|
311 | 299 | |
|
312 | 300 | -list_all: put all option values in lists. Normally only options |
|
313 | 301 | appearing more than once are put in a list. |
|
314 | 302 | |
|
315 | 303 | -posix (True): whether to split the input line in POSIX mode or not, |
|
316 | 304 | as per the conventions outlined in the shlex module from the |
|
317 | 305 | standard library.""" |
|
318 | 306 | |
|
319 | 307 | # inject default options at the beginning of the input line |
|
320 | 308 | caller = sys._getframe(1).f_code.co_name.replace('magic_','') |
|
321 | 309 | arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str) |
|
322 | 310 | |
|
323 | 311 | mode = kw.get('mode','string') |
|
324 | 312 | if mode not in ['string','list']: |
|
325 | 313 | raise ValueError,'incorrect mode given: %s' % mode |
|
326 | 314 | # Get options |
|
327 | 315 | list_all = kw.get('list_all',0) |
|
328 | 316 | posix = kw.get('posix',True) |
|
329 | 317 | |
|
330 | 318 | # Check if we have more than one argument to warrant extra processing: |
|
331 | 319 | odict = {} # Dictionary with options |
|
332 | 320 | args = arg_str.split() |
|
333 | 321 | if len(args) >= 1: |
|
334 | 322 | # If the list of inputs only has 0 or 1 thing in it, there's no |
|
335 | 323 | # need to look for options |
|
336 | 324 | argv = arg_split(arg_str,posix) |
|
337 | 325 | # Do regular option processing |
|
338 | 326 | try: |
|
339 | 327 | opts,args = getopt(argv,opt_str,*long_opts) |
|
340 | 328 | except GetoptError,e: |
|
341 | 329 | raise GetoptError('%s ( allowed: "%s" %s)' % (e.msg,opt_str, |
|
342 | 330 | " ".join(long_opts))) |
|
343 | 331 | for o,a in opts: |
|
344 | 332 | if o.startswith('--'): |
|
345 | 333 | o = o[2:] |
|
346 | 334 | else: |
|
347 | 335 | o = o[1:] |
|
348 | 336 | try: |
|
349 | 337 | odict[o].append(a) |
|
350 | 338 | except AttributeError: |
|
351 | 339 | odict[o] = [odict[o],a] |
|
352 | 340 | except KeyError: |
|
353 | 341 | if list_all: |
|
354 | 342 | odict[o] = [a] |
|
355 | 343 | else: |
|
356 | 344 | odict[o] = a |
|
357 | 345 | |
|
358 | 346 | # Prepare opts,args for return |
|
359 | 347 | opts = Struct(odict) |
|
360 | 348 | if mode == 'string': |
|
361 | 349 | args = ' '.join(args) |
|
362 | 350 | |
|
363 | 351 | return opts,args |
|
364 | 352 | |
|
365 | 353 | #...................................................................... |
|
366 | 354 | # And now the actual magic functions |
|
367 | 355 | |
|
368 | 356 | # Functions for IPython shell work (vars,funcs, config, etc) |
|
369 | 357 | def magic_lsmagic(self, parameter_s = ''): |
|
370 | 358 | """List currently available magic functions.""" |
|
371 | 359 | mesc = self.shell.ESC_MAGIC |
|
372 | 360 | print 'Available magic functions:\n'+mesc+\ |
|
373 | 361 | (' '+mesc).join(self.lsmagic()) |
|
374 | 362 | print '\n' + Magic.auto_status[self.shell.rc.automagic] |
|
375 | 363 | return None |
|
376 | 364 | |
|
377 | 365 | def magic_magic(self, parameter_s = ''): |
|
378 | 366 | """Print information about the magic function system.""" |
|
379 | 367 | |
|
380 | 368 | mode = '' |
|
381 | 369 | try: |
|
382 | 370 | if parameter_s.split()[0] == '-latex': |
|
383 | 371 | mode = 'latex' |
|
384 | 372 | if parameter_s.split()[0] == '-brief': |
|
385 | 373 | mode = 'brief' |
|
386 | 374 | except: |
|
387 | 375 | pass |
|
388 | 376 | |
|
389 | 377 | magic_docs = [] |
|
390 | 378 | for fname in self.lsmagic(): |
|
391 | 379 | mname = 'magic_' + fname |
|
392 | 380 | for space in (Magic,self,self.__class__): |
|
393 | 381 | try: |
|
394 | 382 | fn = space.__dict__[mname] |
|
395 | 383 | except KeyError: |
|
396 | 384 | pass |
|
397 | 385 | else: |
|
398 | 386 | break |
|
399 | 387 | if mode == 'brief': |
|
400 | 388 | # only first line |
|
401 | 389 | fndoc = fn.__doc__.split('\n',1)[0] |
|
402 | 390 | else: |
|
403 | 391 | fndoc = fn.__doc__ |
|
404 | 392 | |
|
405 | 393 | magic_docs.append('%s%s:\n\t%s\n' %(self.shell.ESC_MAGIC, |
|
406 | 394 | fname,fndoc)) |
|
407 | 395 | magic_docs = ''.join(magic_docs) |
|
408 | 396 | |
|
409 | 397 | if mode == 'latex': |
|
410 | 398 | print self.format_latex(magic_docs) |
|
411 | 399 | return |
|
412 | 400 | else: |
|
413 | 401 | magic_docs = self.format_screen(magic_docs) |
|
414 | 402 | if mode == 'brief': |
|
415 | 403 | return magic_docs |
|
416 | 404 | |
|
417 | 405 | outmsg = """ |
|
418 | 406 | IPython's 'magic' functions |
|
419 | 407 | =========================== |
|
420 | 408 | |
|
421 | 409 | The magic function system provides a series of functions which allow you to |
|
422 | 410 | control the behavior of IPython itself, plus a lot of system-type |
|
423 | 411 | features. All these functions are prefixed with a % character, but parameters |
|
424 | 412 | are given without parentheses or quotes. |
|
425 | 413 | |
|
426 | 414 | NOTE: If you have 'automagic' enabled (via the command line option or with the |
|
427 | 415 | %automagic function), you don't need to type in the % explicitly. By default, |
|
428 | 416 | IPython ships with automagic on, so you should only rarely need the % escape. |
|
429 | 417 | |
|
430 | 418 | Example: typing '%cd mydir' (without the quotes) changes you working directory |
|
431 | 419 | to 'mydir', if it exists. |
|
432 | 420 | |
|
433 | 421 | You can define your own magic functions to extend the system. See the supplied |
|
434 | 422 | ipythonrc and example-magic.py files for details (in your ipython |
|
435 | 423 | configuration directory, typically $HOME/.ipython/). |
|
436 | 424 | |
|
437 | 425 | You can also define your own aliased names for magic functions. In your |
|
438 | 426 | ipythonrc file, placing a line like: |
|
439 | 427 | |
|
440 | 428 | execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile |
|
441 | 429 | |
|
442 | 430 | will define %pf as a new name for %profile. |
|
443 | 431 | |
|
444 | 432 | You can also call magics in code using the ipmagic() function, which IPython |
|
445 | 433 | automatically adds to the builtin namespace. Type 'ipmagic?' for details. |
|
446 | 434 | |
|
447 | 435 | For a list of the available magic functions, use %lsmagic. For a description |
|
448 | 436 | of any of them, type %magic_name?, e.g. '%cd?'. |
|
449 | 437 | |
|
450 | 438 | Currently the magic system has the following functions:\n""" |
|
451 | 439 | |
|
452 | 440 | mesc = self.shell.ESC_MAGIC |
|
453 | 441 | outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):" |
|
454 | 442 | "\n\n%s%s\n\n%s" % (outmsg, |
|
455 | 443 | magic_docs,mesc,mesc, |
|
456 | 444 | (' '+mesc).join(self.lsmagic()), |
|
457 | 445 | Magic.auto_status[self.shell.rc.automagic] ) ) |
|
458 | 446 | |
|
459 | 447 | page(outmsg,screen_lines=self.shell.rc.screen_length) |
|
460 | 448 | |
|
461 | 449 | def magic_automagic(self, parameter_s = ''): |
|
462 | 450 | """Make magic functions callable without having to type the initial %. |
|
463 | 451 | |
|
464 | 452 | Toggles on/off (when off, you must call it as %automagic, of |
|
465 | 453 | course). Note that magic functions have lowest priority, so if there's |
|
466 | 454 | a variable whose name collides with that of a magic fn, automagic |
|
467 | 455 | won't work for that function (you get the variable instead). However, |
|
468 | 456 | if you delete the variable (del var), the previously shadowed magic |
|
469 | 457 | function becomes visible to automagic again.""" |
|
470 | 458 | |
|
471 | 459 | rc = self.shell.rc |
|
472 | 460 | rc.automagic = not rc.automagic |
|
473 | 461 | print '\n' + Magic.auto_status[rc.automagic] |
|
474 | 462 | |
|
475 | 463 | def magic_autocall(self, parameter_s = ''): |
|
476 | 464 | """Make functions callable without having to type parentheses. |
|
477 | 465 | |
|
478 | 466 | Usage: |
|
479 | 467 | |
|
480 | 468 | %autocall [mode] |
|
481 | 469 | |
|
482 | 470 | The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the |
|
483 | 471 | value is toggled on and off (remembering the previous state).""" |
|
484 | 472 | |
|
485 | 473 | rc = self.shell.rc |
|
486 | 474 | |
|
487 | 475 | if parameter_s: |
|
488 | 476 | arg = int(parameter_s) |
|
489 | 477 | else: |
|
490 | 478 | arg = 'toggle' |
|
491 | 479 | |
|
492 | 480 | if not arg in (0,1,2,'toggle'): |
|
493 | 481 | error('Valid modes: (0->Off, 1->Smart, 2->Full') |
|
494 | 482 | return |
|
495 | 483 | |
|
496 | 484 | if arg in (0,1,2): |
|
497 | 485 | rc.autocall = arg |
|
498 | 486 | else: # toggle |
|
499 | 487 | if rc.autocall: |
|
500 | 488 | self._magic_state.autocall_save = rc.autocall |
|
501 | 489 | rc.autocall = 0 |
|
502 | 490 | else: |
|
503 | 491 | try: |
|
504 | 492 | rc.autocall = self._magic_state.autocall_save |
|
505 | 493 | except AttributeError: |
|
506 | 494 | rc.autocall = self._magic_state.autocall_save = 1 |
|
507 | 495 | |
|
508 | 496 | print "Automatic calling is:",['OFF','Smart','Full'][rc.autocall] |
|
509 | 497 | |
|
510 | 498 | def magic_autoindent(self, parameter_s = ''): |
|
511 | 499 | """Toggle autoindent on/off (if available).""" |
|
512 | 500 | |
|
513 | 501 | self.shell.set_autoindent() |
|
514 | 502 | print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent] |
|
515 | 503 | |
|
516 | 504 | def magic_system_verbose(self, parameter_s = ''): |
|
517 | 505 | """Toggle verbose printing of system calls on/off.""" |
|
518 | 506 | |
|
519 | 507 | self.shell.rc_set_toggle('system_verbose') |
|
520 | 508 | print "System verbose printing is:",\ |
|
521 | 509 | ['OFF','ON'][self.shell.rc.system_verbose] |
|
522 | 510 | |
|
523 | 511 | def magic_history(self, parameter_s = ''): |
|
524 | 512 | """Print input history (_i<n> variables), with most recent last. |
|
525 | 513 | |
|
526 | 514 | %history -> print at most 40 inputs (some may be multi-line)\\ |
|
527 | 515 | %history n -> print at most n inputs\\ |
|
528 | 516 | %history n1 n2 -> print inputs between n1 and n2 (n2 not included)\\ |
|
529 | 517 | |
|
530 | 518 | Each input's number <n> is shown, and is accessible as the |
|
531 | 519 | automatically generated variable _i<n>. Multi-line statements are |
|
532 | 520 | printed starting at a new line for easy copy/paste. |
|
533 | 521 | |
|
534 | 522 | |
|
535 | 523 | Options: |
|
536 | 524 | |
|
537 | 525 | -n: do NOT print line numbers. This is useful if you want to get a |
|
538 | 526 | printout of many lines which can be directly pasted into a text |
|
539 | 527 | editor. |
|
540 | 528 | |
|
541 | 529 | This feature is only available if numbered prompts are in use. |
|
542 | 530 | |
|
543 | 531 | -r: print the 'raw' history. IPython filters your input and |
|
544 | 532 | converts it all into valid Python source before executing it (things |
|
545 | 533 | like magics or aliases are turned into function calls, for |
|
546 | 534 | example). With this option, you'll see the unfiltered history |
|
547 | 535 | instead of the filtered version: '%cd /' will be seen as '%cd /' |
|
548 | 536 | instead of '_ip.magic("%cd /")'. |
|
549 | 537 | """ |
|
550 | 538 | |
|
551 | 539 | shell = self.shell |
|
552 | 540 | if not shell.outputcache.do_full_cache: |
|
553 | 541 | print 'This feature is only available if numbered prompts are in use.' |
|
554 | 542 | return |
|
555 | 543 | opts,args = self.parse_options(parameter_s,'nr',mode='list') |
|
556 | 544 | |
|
557 | 545 | if opts.has_key('r'): |
|
558 | 546 | input_hist = shell.input_hist_raw |
|
559 | 547 | else: |
|
560 | 548 | input_hist = shell.input_hist |
|
561 | 549 | |
|
562 | 550 | default_length = 40 |
|
563 | 551 | if len(args) == 0: |
|
564 | 552 | final = len(input_hist) |
|
565 | 553 | init = max(1,final-default_length) |
|
566 | 554 | elif len(args) == 1: |
|
567 | 555 | final = len(input_hist) |
|
568 | 556 | init = max(1,final-int(args[0])) |
|
569 | 557 | elif len(args) == 2: |
|
570 | 558 | init,final = map(int,args) |
|
571 | 559 | else: |
|
572 | 560 | warn('%hist takes 0, 1 or 2 arguments separated by spaces.') |
|
573 | 561 | print self.magic_hist.__doc__ |
|
574 | 562 | return |
|
575 | 563 | width = len(str(final)) |
|
576 | 564 | line_sep = ['','\n'] |
|
577 | 565 | print_nums = not opts.has_key('n') |
|
578 | 566 | for in_num in range(init,final): |
|
579 | 567 | inline = input_hist[in_num] |
|
580 | 568 | multiline = int(inline.count('\n') > 1) |
|
581 | 569 | if print_nums: |
|
582 | 570 | print '%s:%s' % (str(in_num).ljust(width),line_sep[multiline]), |
|
583 | 571 | print inline, |
|
584 | 572 | |
|
585 | 573 | def magic_hist(self, parameter_s=''): |
|
586 | 574 | """Alternate name for %history.""" |
|
587 | 575 | return self.magic_history(parameter_s) |
|
588 | 576 | |
|
589 | 577 | def magic_p(self, parameter_s=''): |
|
590 | 578 | """Just a short alias for Python's 'print'.""" |
|
591 | 579 | exec 'print ' + parameter_s in self.shell.user_ns |
|
592 | 580 | |
|
593 | 581 | def magic_r(self, parameter_s=''): |
|
594 | 582 | """Repeat previous input. |
|
595 | 583 | |
|
596 | 584 | If given an argument, repeats the previous command which starts with |
|
597 | 585 | the same string, otherwise it just repeats the previous input. |
|
598 | 586 | |
|
599 | 587 | Shell escaped commands (with ! as first character) are not recognized |
|
600 | 588 | by this system, only pure python code and magic commands. |
|
601 | 589 | """ |
|
602 | 590 | |
|
603 | 591 | start = parameter_s.strip() |
|
604 | 592 | esc_magic = self.shell.ESC_MAGIC |
|
605 | 593 | # Identify magic commands even if automagic is on (which means |
|
606 | 594 | # the in-memory version is different from that typed by the user). |
|
607 | 595 | if self.shell.rc.automagic: |
|
608 | 596 | start_magic = esc_magic+start |
|
609 | 597 | else: |
|
610 | 598 | start_magic = start |
|
611 | 599 | # Look through the input history in reverse |
|
612 | 600 | for n in range(len(self.shell.input_hist)-2,0,-1): |
|
613 | 601 | input = self.shell.input_hist[n] |
|
614 | 602 | # skip plain 'r' lines so we don't recurse to infinity |
|
615 | 603 | if input != '_ip.magic("r")\n' and \ |
|
616 | 604 | (input.startswith(start) or input.startswith(start_magic)): |
|
617 | 605 | #print 'match',`input` # dbg |
|
618 | 606 | print 'Executing:',input, |
|
619 | 607 | self.shell.runlines(input) |
|
620 | 608 | return |
|
621 | 609 | print 'No previous input matching `%s` found.' % start |
|
622 | 610 | |
|
623 | 611 | def magic_page(self, parameter_s=''): |
|
624 | 612 | """Pretty print the object and display it through a pager. |
|
625 | 613 | |
|
626 | 614 | If no parameter is given, use _ (last output).""" |
|
627 | 615 | # After a function contributed by Olivier Aubert, slightly modified. |
|
628 | 616 | |
|
629 | 617 | oname = parameter_s and parameter_s or '_' |
|
630 | 618 | info = self._ofind(oname) |
|
631 | 619 | if info['found']: |
|
632 | 620 | page(pformat(info['obj'])) |
|
633 | 621 | else: |
|
634 | 622 | print 'Object `%s` not found' % oname |
|
635 | 623 | |
|
636 | 624 | def magic_profile(self, parameter_s=''): |
|
637 | 625 | """Print your currently active IPyhton profile.""" |
|
638 | 626 | if self.shell.rc.profile: |
|
639 | 627 | printpl('Current IPython profile: $self.shell.rc.profile.') |
|
640 | 628 | else: |
|
641 | 629 | print 'No profile active.' |
|
642 | 630 | |
|
643 | 631 | def _inspect(self,meth,oname,namespaces=None,**kw): |
|
644 | 632 | """Generic interface to the inspector system. |
|
645 | 633 | |
|
646 | 634 | This function is meant to be called by pdef, pdoc & friends.""" |
|
647 | 635 | |
|
648 | 636 | oname = oname.strip() |
|
649 | 637 | info = Struct(self._ofind(oname, namespaces)) |
|
650 | 638 | |
|
651 | 639 | if info.found: |
|
652 | 640 | # Get the docstring of the class property if it exists. |
|
653 | 641 | path = oname.split('.') |
|
654 | 642 | root = '.'.join(path[:-1]) |
|
655 | 643 | if info.parent is not None: |
|
656 | 644 | try: |
|
657 | 645 | target = getattr(info.parent, '__class__') |
|
658 | 646 | # The object belongs to a class instance. |
|
659 | 647 | try: |
|
660 | 648 | target = getattr(target, path[-1]) |
|
661 | 649 | # The class defines the object. |
|
662 | 650 | if isinstance(target, property): |
|
663 | 651 | oname = root + '.__class__.' + path[-1] |
|
664 | 652 | info = Struct(self._ofind(oname)) |
|
665 | 653 | except AttributeError: pass |
|
666 | 654 | except AttributeError: pass |
|
667 | 655 | |
|
668 | 656 | pmethod = getattr(self.shell.inspector,meth) |
|
669 | 657 | formatter = info.ismagic and self.format_screen or None |
|
670 | 658 | if meth == 'pdoc': |
|
671 | 659 | pmethod(info.obj,oname,formatter) |
|
672 | 660 | elif meth == 'pinfo': |
|
673 | 661 | pmethod(info.obj,oname,formatter,info,**kw) |
|
674 | 662 | else: |
|
675 | 663 | pmethod(info.obj,oname) |
|
676 | 664 | else: |
|
677 | 665 | print 'Object `%s` not found.' % oname |
|
678 | 666 | return 'not found' # so callers can take other action |
|
679 | 667 | |
|
680 | 668 | def magic_pdef(self, parameter_s='', namespaces=None): |
|
681 | 669 | """Print the definition header for any callable object. |
|
682 | 670 | |
|
683 | 671 | If the object is a class, print the constructor information.""" |
|
684 | 672 | print "+++" |
|
685 | 673 | self._inspect('pdef',parameter_s, namespaces) |
|
686 | 674 | |
|
687 | 675 | def magic_pdoc(self, parameter_s='', namespaces=None): |
|
688 | 676 | """Print the docstring for an object. |
|
689 | 677 | |
|
690 | 678 | If the given object is a class, it will print both the class and the |
|
691 | 679 | constructor docstrings.""" |
|
692 | 680 | self._inspect('pdoc',parameter_s, namespaces) |
|
693 | 681 | |
|
694 | 682 | def magic_psource(self, parameter_s='', namespaces=None): |
|
695 | 683 | """Print (or run through pager) the source code for an object.""" |
|
696 | 684 | self._inspect('psource',parameter_s, namespaces) |
|
697 | 685 | |
|
698 | 686 | def magic_pfile(self, parameter_s=''): |
|
699 | 687 | """Print (or run through pager) the file where an object is defined. |
|
700 | 688 | |
|
701 | 689 | The file opens at the line where the object definition begins. IPython |
|
702 | 690 | will honor the environment variable PAGER if set, and otherwise will |
|
703 | 691 | do its best to print the file in a convenient form. |
|
704 | 692 | |
|
705 | 693 | If the given argument is not an object currently defined, IPython will |
|
706 | 694 | try to interpret it as a filename (automatically adding a .py extension |
|
707 | 695 | if needed). You can thus use %pfile as a syntax highlighting code |
|
708 | 696 | viewer.""" |
|
709 | 697 | |
|
710 | 698 | # first interpret argument as an object name |
|
711 | 699 | out = self._inspect('pfile',parameter_s) |
|
712 | 700 | # if not, try the input as a filename |
|
713 | 701 | if out == 'not found': |
|
714 | 702 | try: |
|
715 | 703 | filename = get_py_filename(parameter_s) |
|
716 | 704 | except IOError,msg: |
|
717 | 705 | print msg |
|
718 | 706 | return |
|
719 | 707 | page(self.shell.inspector.format(file(filename).read())) |
|
720 | 708 | |
|
721 | 709 | def magic_pinfo(self, parameter_s='', namespaces=None): |
|
722 | 710 | """Provide detailed information about an object. |
|
723 | 711 | |
|
724 | 712 | '%pinfo object' is just a synonym for object? or ?object.""" |
|
725 | 713 | |
|
726 | 714 | #print 'pinfo par: <%s>' % parameter_s # dbg |
|
727 | 715 | |
|
728 | 716 | # detail_level: 0 -> obj? , 1 -> obj?? |
|
729 | 717 | detail_level = 0 |
|
730 | 718 | # We need to detect if we got called as 'pinfo pinfo foo', which can |
|
731 | 719 | # happen if the user types 'pinfo foo?' at the cmd line. |
|
732 | 720 | pinfo,qmark1,oname,qmark2 = \ |
|
733 | 721 | re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups() |
|
734 | 722 | if pinfo or qmark1 or qmark2: |
|
735 | 723 | detail_level = 1 |
|
736 | 724 | if "*" in oname: |
|
737 | 725 | self.magic_psearch(oname) |
|
738 | 726 | else: |
|
739 | 727 | self._inspect('pinfo', oname, detail_level=detail_level, |
|
740 | 728 | namespaces=namespaces) |
|
741 | 729 | |
|
742 | 730 | def magic_psearch(self, parameter_s=''): |
|
743 | 731 | """Search for object in namespaces by wildcard. |
|
744 | 732 | |
|
745 | 733 | %psearch [options] PATTERN [OBJECT TYPE] |
|
746 | 734 | |
|
747 | 735 | Note: ? can be used as a synonym for %psearch, at the beginning or at |
|
748 | 736 | the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the |
|
749 | 737 | rest of the command line must be unchanged (options come first), so |
|
750 | 738 | for example the following forms are equivalent |
|
751 | 739 | |
|
752 | 740 | %psearch -i a* function |
|
753 | 741 | -i a* function? |
|
754 | 742 | ?-i a* function |
|
755 | 743 | |
|
756 | 744 | Arguments: |
|
757 | 745 | |
|
758 | 746 | PATTERN |
|
759 | 747 | |
|
760 | 748 | where PATTERN is a string containing * as a wildcard similar to its |
|
761 | 749 | use in a shell. The pattern is matched in all namespaces on the |
|
762 | 750 | search path. By default objects starting with a single _ are not |
|
763 | 751 | matched, many IPython generated objects have a single |
|
764 | 752 | underscore. The default is case insensitive matching. Matching is |
|
765 | 753 | also done on the attributes of objects and not only on the objects |
|
766 | 754 | in a module. |
|
767 | 755 | |
|
768 | 756 | [OBJECT TYPE] |
|
769 | 757 | |
|
770 | 758 | Is the name of a python type from the types module. The name is |
|
771 | 759 | given in lowercase without the ending type, ex. StringType is |
|
772 | 760 | written string. By adding a type here only objects matching the |
|
773 | 761 | given type are matched. Using all here makes the pattern match all |
|
774 | 762 | types (this is the default). |
|
775 | 763 | |
|
776 | 764 | Options: |
|
777 | 765 | |
|
778 | 766 | -a: makes the pattern match even objects whose names start with a |
|
779 | 767 | single underscore. These names are normally ommitted from the |
|
780 | 768 | search. |
|
781 | 769 | |
|
782 | 770 | -i/-c: make the pattern case insensitive/sensitive. If neither of |
|
783 | 771 | these options is given, the default is read from your ipythonrc |
|
784 | 772 | file. The option name which sets this value is |
|
785 | 773 | 'wildcards_case_sensitive'. If this option is not specified in your |
|
786 | 774 | ipythonrc file, IPython's internal default is to do a case sensitive |
|
787 | 775 | search. |
|
788 | 776 | |
|
789 | 777 | -e/-s NAMESPACE: exclude/search a given namespace. The pattern you |
|
790 | 778 | specifiy can be searched in any of the following namespaces: |
|
791 | 779 | 'builtin', 'user', 'user_global','internal', 'alias', where |
|
792 | 780 | 'builtin' and 'user' are the search defaults. Note that you should |
|
793 | 781 | not use quotes when specifying namespaces. |
|
794 | 782 | |
|
795 | 783 | 'Builtin' contains the python module builtin, 'user' contains all |
|
796 | 784 | user data, 'alias' only contain the shell aliases and no python |
|
797 | 785 | objects, 'internal' contains objects used by IPython. The |
|
798 | 786 | 'user_global' namespace is only used by embedded IPython instances, |
|
799 | 787 | and it contains module-level globals. You can add namespaces to the |
|
800 | 788 | search with -s or exclude them with -e (these options can be given |
|
801 | 789 | more than once). |
|
802 | 790 | |
|
803 | 791 | Examples: |
|
804 | 792 | |
|
805 | 793 | %psearch a* -> objects beginning with an a |
|
806 | 794 | %psearch -e builtin a* -> objects NOT in the builtin space starting in a |
|
807 | 795 | %psearch a* function -> all functions beginning with an a |
|
808 | 796 | %psearch re.e* -> objects beginning with an e in module re |
|
809 | 797 | %psearch r*.e* -> objects that start with e in modules starting in r |
|
810 | 798 | %psearch r*.* string -> all strings in modules beginning with r |
|
811 | 799 | |
|
812 | 800 | Case sensitve search: |
|
813 | 801 | |
|
814 | 802 | %psearch -c a* list all object beginning with lower case a |
|
815 | 803 | |
|
816 | 804 | Show objects beginning with a single _: |
|
817 | 805 | |
|
818 | 806 | %psearch -a _* list objects beginning with a single underscore""" |
|
819 | 807 | |
|
820 | 808 | # default namespaces to be searched |
|
821 | 809 | def_search = ['user','builtin'] |
|
822 | 810 | |
|
823 | 811 | # Process options/args |
|
824 | 812 | opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True) |
|
825 | 813 | opt = opts.get |
|
826 | 814 | shell = self.shell |
|
827 | 815 | psearch = shell.inspector.psearch |
|
828 | 816 | |
|
829 | 817 | # select case options |
|
830 | 818 | if opts.has_key('i'): |
|
831 | 819 | ignore_case = True |
|
832 | 820 | elif opts.has_key('c'): |
|
833 | 821 | ignore_case = False |
|
834 | 822 | else: |
|
835 | 823 | ignore_case = not shell.rc.wildcards_case_sensitive |
|
836 | 824 | |
|
837 | 825 | # Build list of namespaces to search from user options |
|
838 | 826 | def_search.extend(opt('s',[])) |
|
839 | 827 | ns_exclude = ns_exclude=opt('e',[]) |
|
840 | 828 | ns_search = [nm for nm in def_search if nm not in ns_exclude] |
|
841 | 829 | |
|
842 | 830 | # Call the actual search |
|
843 | 831 | try: |
|
844 | 832 | psearch(args,shell.ns_table,ns_search, |
|
845 | 833 | show_all=opt('a'),ignore_case=ignore_case) |
|
846 | 834 | except: |
|
847 | 835 | shell.showtraceback() |
|
848 | 836 | |
|
849 | 837 | def magic_who_ls(self, parameter_s=''): |
|
850 | 838 | """Return a sorted list of all interactive variables. |
|
851 | 839 | |
|
852 | 840 | If arguments are given, only variables of types matching these |
|
853 | 841 | arguments are returned.""" |
|
854 | 842 | |
|
855 | 843 | user_ns = self.shell.user_ns |
|
856 | 844 | internal_ns = self.shell.internal_ns |
|
857 | 845 | user_config_ns = self.shell.user_config_ns |
|
858 | 846 | out = [] |
|
859 | 847 | typelist = parameter_s.split() |
|
860 | 848 | |
|
861 | 849 | for i in user_ns: |
|
862 | 850 | if not (i.startswith('_') or i.startswith('_i')) \ |
|
863 | 851 | and not (i in internal_ns or i in user_config_ns): |
|
864 | 852 | if typelist: |
|
865 | 853 | if type(user_ns[i]).__name__ in typelist: |
|
866 | 854 | out.append(i) |
|
867 | 855 | else: |
|
868 | 856 | out.append(i) |
|
869 | 857 | out.sort() |
|
870 | 858 | return out |
|
871 | 859 | |
|
872 | 860 | def magic_who(self, parameter_s=''): |
|
873 | 861 | """Print all interactive variables, with some minimal formatting. |
|
874 | 862 | |
|
875 | 863 | If any arguments are given, only variables whose type matches one of |
|
876 | 864 | these are printed. For example: |
|
877 | 865 | |
|
878 | 866 | %who function str |
|
879 | 867 | |
|
880 | 868 | will only list functions and strings, excluding all other types of |
|
881 | 869 | variables. To find the proper type names, simply use type(var) at a |
|
882 | 870 | command line to see how python prints type names. For example: |
|
883 | 871 | |
|
884 | 872 | In [1]: type('hello')\\ |
|
885 | 873 | Out[1]: <type 'str'> |
|
886 | 874 | |
|
887 | 875 | indicates that the type name for strings is 'str'. |
|
888 | 876 | |
|
889 | 877 | %who always excludes executed names loaded through your configuration |
|
890 | 878 | file and things which are internal to IPython. |
|
891 | 879 | |
|
892 | 880 | This is deliberate, as typically you may load many modules and the |
|
893 | 881 | purpose of %who is to show you only what you've manually defined.""" |
|
894 | 882 | |
|
895 | 883 | varlist = self.magic_who_ls(parameter_s) |
|
896 | 884 | if not varlist: |
|
897 | 885 | print 'Interactive namespace is empty.' |
|
898 | 886 | return |
|
899 | 887 | |
|
900 | 888 | # if we have variables, move on... |
|
901 | 889 | |
|
902 | 890 | # stupid flushing problem: when prompts have no separators, stdout is |
|
903 | 891 | # getting lost. I'm starting to think this is a python bug. I'm having |
|
904 | 892 | # to force a flush with a print because even a sys.stdout.flush |
|
905 | 893 | # doesn't seem to do anything! |
|
906 | 894 | |
|
907 | 895 | count = 0 |
|
908 | 896 | for i in varlist: |
|
909 | 897 | print i+'\t', |
|
910 | 898 | count += 1 |
|
911 | 899 | if count > 8: |
|
912 | 900 | count = 0 |
|
913 | 901 | |
|
914 | 902 | sys.stdout.flush() # FIXME. Why the hell isn't this flushing??? |
|
915 | 903 | |
|
916 | 904 | print # well, this does force a flush at the expense of an extra \n |
|
917 | 905 | |
|
918 | 906 | def magic_whos(self, parameter_s=''): |
|
919 | 907 | """Like %who, but gives some extra information about each variable. |
|
920 | 908 | |
|
921 | 909 | The same type filtering of %who can be applied here. |
|
922 | 910 | |
|
923 | 911 | For all variables, the type is printed. Additionally it prints: |
|
924 | 912 | |
|
925 | 913 | - For {},[],(): their length. |
|
926 | 914 | |
|
927 | 915 | - For Numeric arrays, a summary with shape, number of elements, |
|
928 | 916 | typecode and size in memory. |
|
929 | 917 | |
|
930 | 918 | - Everything else: a string representation, snipping their middle if |
|
931 | 919 | too long.""" |
|
932 | 920 | |
|
933 | 921 | varnames = self.magic_who_ls(parameter_s) |
|
934 | 922 | if not varnames: |
|
935 | 923 | print 'Interactive namespace is empty.' |
|
936 | 924 | return |
|
937 | 925 | |
|
938 | 926 | # if we have variables, move on... |
|
939 | 927 | |
|
940 | 928 | # for these types, show len() instead of data: |
|
941 | 929 | seq_types = [types.DictType,types.ListType,types.TupleType] |
|
942 | 930 | |
|
943 | 931 | # for Numeric arrays, display summary info |
|
944 | 932 | try: |
|
945 | 933 | import Numeric |
|
946 | 934 | except ImportError: |
|
947 | 935 | array_type = None |
|
948 | 936 | else: |
|
949 | 937 | array_type = Numeric.ArrayType.__name__ |
|
950 | 938 | |
|
951 | 939 | # Find all variable names and types so we can figure out column sizes |
|
952 | 940 | get_vars = lambda i: self.shell.user_ns[i] |
|
953 | 941 | type_name = lambda v: type(v).__name__ |
|
954 | 942 | varlist = map(get_vars,varnames) |
|
955 | 943 | |
|
956 | 944 | typelist = [] |
|
957 | 945 | for vv in varlist: |
|
958 | 946 | tt = type_name(vv) |
|
959 | 947 | if tt=='instance': |
|
960 | 948 | typelist.append(str(vv.__class__)) |
|
961 | 949 | else: |
|
962 | 950 | typelist.append(tt) |
|
963 | 951 | |
|
964 | 952 | # column labels and # of spaces as separator |
|
965 | 953 | varlabel = 'Variable' |
|
966 | 954 | typelabel = 'Type' |
|
967 | 955 | datalabel = 'Data/Info' |
|
968 | 956 | colsep = 3 |
|
969 | 957 | # variable format strings |
|
970 | 958 | vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)" |
|
971 | 959 | vfmt_short = '$vstr[:25]<...>$vstr[-25:]' |
|
972 | 960 | aformat = "%s: %s elems, type `%s`, %s bytes" |
|
973 | 961 | # find the size of the columns to format the output nicely |
|
974 | 962 | varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep |
|
975 | 963 | typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep |
|
976 | 964 | # table header |
|
977 | 965 | print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \ |
|
978 | 966 | ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1) |
|
979 | 967 | # and the table itself |
|
980 | 968 | kb = 1024 |
|
981 | 969 | Mb = 1048576 # kb**2 |
|
982 | 970 | for vname,var,vtype in zip(varnames,varlist,typelist): |
|
983 | 971 | print itpl(vformat), |
|
984 | 972 | if vtype in seq_types: |
|
985 | 973 | print len(var) |
|
986 | 974 | elif vtype==array_type: |
|
987 | 975 | vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1] |
|
988 | 976 | vsize = Numeric.size(var) |
|
989 | 977 | vbytes = vsize*var.itemsize() |
|
990 | 978 | if vbytes < 100000: |
|
991 | 979 | print aformat % (vshape,vsize,var.typecode(),vbytes) |
|
992 | 980 | else: |
|
993 | 981 | print aformat % (vshape,vsize,var.typecode(),vbytes), |
|
994 | 982 | if vbytes < Mb: |
|
995 | 983 | print '(%s kb)' % (vbytes/kb,) |
|
996 | 984 | else: |
|
997 | 985 | print '(%s Mb)' % (vbytes/Mb,) |
|
998 | 986 | else: |
|
999 | 987 | vstr = str(var).replace('\n','\\n') |
|
1000 | 988 | if len(vstr) < 50: |
|
1001 | 989 | print vstr |
|
1002 | 990 | else: |
|
1003 | 991 | printpl(vfmt_short) |
|
1004 | 992 | |
|
1005 | 993 | def magic_reset(self, parameter_s=''): |
|
1006 | 994 | """Resets the namespace by removing all names defined by the user. |
|
1007 | 995 | |
|
1008 | 996 | Input/Output history are left around in case you need them.""" |
|
1009 | 997 | |
|
1010 | 998 | ans = self.shell.ask_yes_no( |
|
1011 | 999 | "Once deleted, variables cannot be recovered. Proceed (y/[n])? ") |
|
1012 | 1000 | if not ans: |
|
1013 | 1001 | print 'Nothing done.' |
|
1014 | 1002 | return |
|
1015 | 1003 | user_ns = self.shell.user_ns |
|
1016 | 1004 | for i in self.magic_who_ls(): |
|
1017 | 1005 | del(user_ns[i]) |
|
1018 | 1006 | |
|
1019 | 1007 | def magic_config(self,parameter_s=''): |
|
1020 | 1008 | """Show IPython's internal configuration.""" |
|
1021 | 1009 | |
|
1022 | 1010 | page('Current configuration structure:\n'+ |
|
1023 | 1011 | pformat(self.shell.rc.dict())) |
|
1024 | 1012 | |
|
1025 | 1013 | def magic_logstart(self,parameter_s=''): |
|
1026 | 1014 | """Start logging anywhere in a session. |
|
1027 | 1015 | |
|
1028 | 1016 | %logstart [-o|-r|-t] [log_name [log_mode]] |
|
1029 | 1017 | |
|
1030 | 1018 | If no name is given, it defaults to a file named 'ipython_log.py' in your |
|
1031 | 1019 | current directory, in 'rotate' mode (see below). |
|
1032 | 1020 | |
|
1033 | 1021 | '%logstart name' saves to file 'name' in 'backup' mode. It saves your |
|
1034 | 1022 | history up to that point and then continues logging. |
|
1035 | 1023 | |
|
1036 | 1024 | %logstart takes a second optional parameter: logging mode. This can be one |
|
1037 | 1025 | of (note that the modes are given unquoted):\\ |
|
1038 | 1026 | append: well, that says it.\\ |
|
1039 | 1027 | backup: rename (if exists) to name~ and start name.\\ |
|
1040 | 1028 | global: single logfile in your home dir, appended to.\\ |
|
1041 | 1029 | over : overwrite existing log.\\ |
|
1042 | 1030 | rotate: create rotating logs name.1~, name.2~, etc. |
|
1043 | 1031 | |
|
1044 | 1032 | Options: |
|
1045 | 1033 | |
|
1046 | 1034 | -o: log also IPython's output. In this mode, all commands which |
|
1047 | 1035 | generate an Out[NN] prompt are recorded to the logfile, right after |
|
1048 | 1036 | their corresponding input line. The output lines are always |
|
1049 | 1037 | prepended with a '#[Out]# ' marker, so that the log remains valid |
|
1050 | 1038 | Python code. |
|
1051 | 1039 | |
|
1052 | 1040 | Since this marker is always the same, filtering only the output from |
|
1053 | 1041 | a log is very easy, using for example a simple awk call: |
|
1054 | 1042 | |
|
1055 | 1043 | awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py |
|
1056 | 1044 | |
|
1057 | 1045 | -r: log 'raw' input. Normally, IPython's logs contain the processed |
|
1058 | 1046 | input, so that user lines are logged in their final form, converted |
|
1059 | 1047 | into valid Python. For example, %Exit is logged as |
|
1060 | 1048 | '_ip.magic("Exit"). If the -r flag is given, all input is logged |
|
1061 | 1049 | exactly as typed, with no transformations applied. |
|
1062 | 1050 | |
|
1063 | 1051 | -t: put timestamps before each input line logged (these are put in |
|
1064 | 1052 | comments).""" |
|
1065 | 1053 | |
|
1066 | 1054 | opts,par = self.parse_options(parameter_s,'ort') |
|
1067 | 1055 | log_output = 'o' in opts |
|
1068 | 1056 | log_raw_input = 'r' in opts |
|
1069 | 1057 | timestamp = 't' in opts |
|
1070 | 1058 | |
|
1071 | 1059 | rc = self.shell.rc |
|
1072 | 1060 | logger = self.shell.logger |
|
1073 | 1061 | |
|
1074 | 1062 | # if no args are given, the defaults set in the logger constructor by |
|
1075 | 1063 | # ipytohn remain valid |
|
1076 | 1064 | if par: |
|
1077 | 1065 | try: |
|
1078 | 1066 | logfname,logmode = par.split() |
|
1079 | 1067 | except: |
|
1080 | 1068 | logfname = par |
|
1081 | 1069 | logmode = 'backup' |
|
1082 | 1070 | else: |
|
1083 | 1071 | logfname = logger.logfname |
|
1084 | 1072 | logmode = logger.logmode |
|
1085 | 1073 | # put logfname into rc struct as if it had been called on the command |
|
1086 | 1074 | # line, so it ends up saved in the log header Save it in case we need |
|
1087 | 1075 | # to restore it... |
|
1088 | 1076 | old_logfile = rc.opts.get('logfile','') |
|
1089 | 1077 | if logfname: |
|
1090 | 1078 | logfname = os.path.expanduser(logfname) |
|
1091 | 1079 | rc.opts.logfile = logfname |
|
1092 | 1080 | loghead = self.shell.loghead_tpl % (rc.opts,rc.args) |
|
1093 | 1081 | try: |
|
1094 | 1082 | started = logger.logstart(logfname,loghead,logmode, |
|
1095 | 1083 | log_output,timestamp,log_raw_input) |
|
1096 | 1084 | except: |
|
1097 | 1085 | rc.opts.logfile = old_logfile |
|
1098 | 1086 | warn("Couldn't start log: %s" % sys.exc_info()[1]) |
|
1099 | 1087 | else: |
|
1100 | 1088 | # log input history up to this point, optionally interleaving |
|
1101 | 1089 | # output if requested |
|
1102 | 1090 | |
|
1103 | 1091 | if timestamp: |
|
1104 | 1092 | # disable timestamping for the previous history, since we've |
|
1105 | 1093 | # lost those already (no time machine here). |
|
1106 | 1094 | logger.timestamp = False |
|
1107 | 1095 | |
|
1108 | 1096 | if log_raw_input: |
|
1109 | 1097 | input_hist = self.shell.input_hist_raw |
|
1110 | 1098 | else: |
|
1111 | 1099 | input_hist = self.shell.input_hist |
|
1112 | 1100 | |
|
1113 | 1101 | if log_output: |
|
1114 | 1102 | log_write = logger.log_write |
|
1115 | 1103 | output_hist = self.shell.output_hist |
|
1116 | 1104 | for n in range(1,len(input_hist)-1): |
|
1117 | 1105 | log_write(input_hist[n].rstrip()) |
|
1118 | 1106 | if n in output_hist: |
|
1119 | 1107 | log_write(repr(output_hist[n]),'output') |
|
1120 | 1108 | else: |
|
1121 | 1109 | logger.log_write(input_hist[1:]) |
|
1122 | 1110 | if timestamp: |
|
1123 | 1111 | # re-enable timestamping |
|
1124 | 1112 | logger.timestamp = True |
|
1125 | 1113 | |
|
1126 | 1114 | print ('Activating auto-logging. ' |
|
1127 | 1115 | 'Current session state plus future input saved.') |
|
1128 | 1116 | logger.logstate() |
|
1129 | 1117 | |
|
1130 | 1118 | def magic_logoff(self,parameter_s=''): |
|
1131 | 1119 | """Temporarily stop logging. |
|
1132 | 1120 | |
|
1133 | 1121 | You must have previously started logging.""" |
|
1134 | 1122 | self.shell.logger.switch_log(0) |
|
1135 | 1123 | |
|
1136 | 1124 | def magic_logon(self,parameter_s=''): |
|
1137 | 1125 | """Restart logging. |
|
1138 | 1126 | |
|
1139 | 1127 | This function is for restarting logging which you've temporarily |
|
1140 | 1128 | stopped with %logoff. For starting logging for the first time, you |
|
1141 | 1129 | must use the %logstart function, which allows you to specify an |
|
1142 | 1130 | optional log filename.""" |
|
1143 | 1131 | |
|
1144 | 1132 | self.shell.logger.switch_log(1) |
|
1145 | 1133 | |
|
1146 | 1134 | def magic_logstate(self,parameter_s=''): |
|
1147 | 1135 | """Print the status of the logging system.""" |
|
1148 | 1136 | |
|
1149 | 1137 | self.shell.logger.logstate() |
|
1150 | 1138 | |
|
1151 | 1139 | def magic_pdb(self, parameter_s=''): |
|
1152 | 1140 | """Control the calling of the pdb interactive debugger. |
|
1153 | 1141 | |
|
1154 | 1142 | Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without |
|
1155 | 1143 | argument it works as a toggle. |
|
1156 | 1144 | |
|
1157 | 1145 | When an exception is triggered, IPython can optionally call the |
|
1158 | 1146 | interactive pdb debugger after the traceback printout. %pdb toggles |
|
1159 | 1147 | this feature on and off.""" |
|
1160 | 1148 | |
|
1161 | 1149 | par = parameter_s.strip().lower() |
|
1162 | 1150 | |
|
1163 | 1151 | if par: |
|
1164 | 1152 | try: |
|
1165 | 1153 | new_pdb = {'off':0,'0':0,'on':1,'1':1}[par] |
|
1166 | 1154 | except KeyError: |
|
1167 | 1155 | print ('Incorrect argument. Use on/1, off/0, ' |
|
1168 | 1156 | 'or nothing for a toggle.') |
|
1169 | 1157 | return |
|
1170 | 1158 | else: |
|
1171 | 1159 | # toggle |
|
1172 | 1160 | new_pdb = not self.shell.InteractiveTB.call_pdb |
|
1173 | 1161 | |
|
1174 | 1162 | # set on the shell |
|
1175 | 1163 | self.shell.call_pdb = new_pdb |
|
1176 | 1164 | print 'Automatic pdb calling has been turned',on_off(new_pdb) |
|
1177 | 1165 | |
|
1178 | 1166 | def magic_prun(self, parameter_s ='',user_mode=1, |
|
1179 | 1167 | opts=None,arg_lst=None,prog_ns=None): |
|
1180 | 1168 | |
|
1181 | 1169 | """Run a statement through the python code profiler. |
|
1182 | 1170 | |
|
1183 | 1171 | Usage:\\ |
|
1184 | 1172 | %prun [options] statement |
|
1185 | 1173 | |
|
1186 | 1174 | The given statement (which doesn't require quote marks) is run via the |
|
1187 | 1175 | python profiler in a manner similar to the profile.run() function. |
|
1188 | 1176 | Namespaces are internally managed to work correctly; profile.run |
|
1189 | 1177 | cannot be used in IPython because it makes certain assumptions about |
|
1190 | 1178 | namespaces which do not hold under IPython. |
|
1191 | 1179 | |
|
1192 | 1180 | Options: |
|
1193 | 1181 | |
|
1194 | 1182 | -l <limit>: you can place restrictions on what or how much of the |
|
1195 | 1183 | profile gets printed. The limit value can be: |
|
1196 | 1184 | |
|
1197 | 1185 | * A string: only information for function names containing this string |
|
1198 | 1186 | is printed. |
|
1199 | 1187 | |
|
1200 | 1188 | * An integer: only these many lines are printed. |
|
1201 | 1189 | |
|
1202 | 1190 | * A float (between 0 and 1): this fraction of the report is printed |
|
1203 | 1191 | (for example, use a limit of 0.4 to see the topmost 40% only). |
|
1204 | 1192 | |
|
1205 | 1193 | You can combine several limits with repeated use of the option. For |
|
1206 | 1194 | example, '-l __init__ -l 5' will print only the topmost 5 lines of |
|
1207 | 1195 | information about class constructors. |
|
1208 | 1196 | |
|
1209 | 1197 | -r: return the pstats.Stats object generated by the profiling. This |
|
1210 | 1198 | object has all the information about the profile in it, and you can |
|
1211 | 1199 | later use it for further analysis or in other functions. |
|
1212 | 1200 | |
|
1213 | 1201 | Since magic functions have a particular form of calling which prevents |
|
1214 | 1202 | you from writing something like:\\ |
|
1215 | 1203 | In [1]: p = %prun -r print 4 # invalid!\\ |
|
1216 | 1204 | you must instead use IPython's automatic variables to assign this:\\ |
|
1217 | 1205 | In [1]: %prun -r print 4 \\ |
|
1218 | 1206 | Out[1]: <pstats.Stats instance at 0x8222cec>\\ |
|
1219 | 1207 | In [2]: stats = _ |
|
1220 | 1208 | |
|
1221 | 1209 | If you really need to assign this value via an explicit function call, |
|
1222 | 1210 | you can always tap directly into the true name of the magic function |
|
1223 | 1211 | by using the _ip.magic function:\\ |
|
1224 | 1212 | In [3]: stats = _ip.magic('prun','-r print 4') |
|
1225 | 1213 | |
|
1226 | 1214 | You can type _ip.magic? for more details. |
|
1227 | 1215 | |
|
1228 | 1216 | -s <key>: sort profile by given key. You can provide more than one key |
|
1229 | 1217 | by using the option several times: '-s key1 -s key2 -s key3...'. The |
|
1230 | 1218 | default sorting key is 'time'. |
|
1231 | 1219 | |
|
1232 | 1220 | The following is copied verbatim from the profile documentation |
|
1233 | 1221 | referenced below: |
|
1234 | 1222 | |
|
1235 | 1223 | When more than one key is provided, additional keys are used as |
|
1236 | 1224 | secondary criteria when the there is equality in all keys selected |
|
1237 | 1225 | before them. |
|
1238 | 1226 | |
|
1239 | 1227 | Abbreviations can be used for any key names, as long as the |
|
1240 | 1228 | abbreviation is unambiguous. The following are the keys currently |
|
1241 | 1229 | defined: |
|
1242 | 1230 | |
|
1243 | 1231 | Valid Arg Meaning\\ |
|
1244 | 1232 | "calls" call count\\ |
|
1245 | 1233 | "cumulative" cumulative time\\ |
|
1246 | 1234 | "file" file name\\ |
|
1247 | 1235 | "module" file name\\ |
|
1248 | 1236 | "pcalls" primitive call count\\ |
|
1249 | 1237 | "line" line number\\ |
|
1250 | 1238 | "name" function name\\ |
|
1251 | 1239 | "nfl" name/file/line\\ |
|
1252 | 1240 | "stdname" standard name\\ |
|
1253 | 1241 | "time" internal time |
|
1254 | 1242 | |
|
1255 | 1243 | Note that all sorts on statistics are in descending order (placing |
|
1256 | 1244 | most time consuming items first), where as name, file, and line number |
|
1257 | 1245 | searches are in ascending order (i.e., alphabetical). The subtle |
|
1258 | 1246 | distinction between "nfl" and "stdname" is that the standard name is a |
|
1259 | 1247 | sort of the name as printed, which means that the embedded line |
|
1260 | 1248 | numbers get compared in an odd way. For example, lines 3, 20, and 40 |
|
1261 | 1249 | would (if the file names were the same) appear in the string order |
|
1262 | 1250 | "20" "3" and "40". In contrast, "nfl" does a numeric compare of the |
|
1263 | 1251 | line numbers. In fact, sort_stats("nfl") is the same as |
|
1264 | 1252 | sort_stats("name", "file", "line"). |
|
1265 | 1253 | |
|
1266 | 1254 | -T <filename>: save profile results as shown on screen to a text |
|
1267 | 1255 | file. The profile is still shown on screen. |
|
1268 | 1256 | |
|
1269 | 1257 | -D <filename>: save (via dump_stats) profile statistics to given |
|
1270 | 1258 | filename. This data is in a format understod by the pstats module, and |
|
1271 | 1259 | is generated by a call to the dump_stats() method of profile |
|
1272 | 1260 | objects. The profile is still shown on screen. |
|
1273 | 1261 | |
|
1274 | 1262 | If you want to run complete programs under the profiler's control, use |
|
1275 | 1263 | '%run -p [prof_opts] filename.py [args to program]' where prof_opts |
|
1276 | 1264 | contains profiler specific options as described here. |
|
1277 | 1265 | |
|
1278 | 1266 | You can read the complete documentation for the profile module with:\\ |
|
1279 | 1267 | In [1]: import profile; profile.help() """ |
|
1280 | 1268 | |
|
1281 | 1269 | opts_def = Struct(D=[''],l=[],s=['time'],T=['']) |
|
1282 | 1270 | # protect user quote marks |
|
1283 | 1271 | parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'") |
|
1284 | 1272 | |
|
1285 | 1273 | if user_mode: # regular user call |
|
1286 | 1274 | opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:', |
|
1287 | 1275 | list_all=1) |
|
1288 | 1276 | namespace = self.shell.user_ns |
|
1289 | 1277 | else: # called to run a program by %run -p |
|
1290 | 1278 | try: |
|
1291 | 1279 | filename = get_py_filename(arg_lst[0]) |
|
1292 | 1280 | except IOError,msg: |
|
1293 | 1281 | error(msg) |
|
1294 | 1282 | return |
|
1295 | 1283 | |
|
1296 | 1284 | arg_str = 'execfile(filename,prog_ns)' |
|
1297 | 1285 | namespace = locals() |
|
1298 | 1286 | |
|
1299 | 1287 | opts.merge(opts_def) |
|
1300 | 1288 | |
|
1301 | 1289 | prof = profile.Profile() |
|
1302 | 1290 | try: |
|
1303 | 1291 | prof = prof.runctx(arg_str,namespace,namespace) |
|
1304 | 1292 | sys_exit = '' |
|
1305 | 1293 | except SystemExit: |
|
1306 | 1294 | sys_exit = """*** SystemExit exception caught in code being profiled.""" |
|
1307 | 1295 | |
|
1308 | 1296 | stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s) |
|
1309 | 1297 | |
|
1310 | 1298 | lims = opts.l |
|
1311 | 1299 | if lims: |
|
1312 | 1300 | lims = [] # rebuild lims with ints/floats/strings |
|
1313 | 1301 | for lim in opts.l: |
|
1314 | 1302 | try: |
|
1315 | 1303 | lims.append(int(lim)) |
|
1316 | 1304 | except ValueError: |
|
1317 | 1305 | try: |
|
1318 | 1306 | lims.append(float(lim)) |
|
1319 | 1307 | except ValueError: |
|
1320 | 1308 | lims.append(lim) |
|
1321 | 1309 | |
|
1322 | 1310 | # trap output |
|
1323 | 1311 | sys_stdout = sys.stdout |
|
1324 | 1312 | stdout_trap = StringIO() |
|
1325 | 1313 | try: |
|
1326 | 1314 | sys.stdout = stdout_trap |
|
1327 | 1315 | stats.print_stats(*lims) |
|
1328 | 1316 | finally: |
|
1329 | 1317 | sys.stdout = sys_stdout |
|
1330 | 1318 | output = stdout_trap.getvalue() |
|
1331 | 1319 | output = output.rstrip() |
|
1332 | 1320 | |
|
1333 | 1321 | page(output,screen_lines=self.shell.rc.screen_length) |
|
1334 | 1322 | print sys_exit, |
|
1335 | 1323 | |
|
1336 | 1324 | dump_file = opts.D[0] |
|
1337 | 1325 | text_file = opts.T[0] |
|
1338 | 1326 | if dump_file: |
|
1339 | 1327 | prof.dump_stats(dump_file) |
|
1340 | 1328 | print '\n*** Profile stats marshalled to file',\ |
|
1341 | 1329 | `dump_file`+'.',sys_exit |
|
1342 | 1330 | if text_file: |
|
1343 | 1331 | file(text_file,'w').write(output) |
|
1344 | 1332 | print '\n*** Profile printout saved to text file',\ |
|
1345 | 1333 | `text_file`+'.',sys_exit |
|
1346 | 1334 | |
|
1347 | 1335 | if opts.has_key('r'): |
|
1348 | 1336 | return stats |
|
1349 | 1337 | else: |
|
1350 | 1338 | return None |
|
1351 | 1339 | |
|
1352 | 1340 | def magic_run(self, parameter_s ='',runner=None): |
|
1353 | 1341 | """Run the named file inside IPython as a program. |
|
1354 | 1342 | |
|
1355 | 1343 | Usage:\\ |
|
1356 | 1344 | %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args] |
|
1357 | 1345 | |
|
1358 | 1346 | Parameters after the filename are passed as command-line arguments to |
|
1359 | 1347 | the program (put in sys.argv). Then, control returns to IPython's |
|
1360 | 1348 | prompt. |
|
1361 | 1349 | |
|
1362 | 1350 | This is similar to running at a system prompt:\\ |
|
1363 | 1351 | $ python file args\\ |
|
1364 | 1352 | but with the advantage of giving you IPython's tracebacks, and of |
|
1365 | 1353 | loading all variables into your interactive namespace for further use |
|
1366 | 1354 | (unless -p is used, see below). |
|
1367 | 1355 | |
|
1368 | 1356 | The file is executed in a namespace initially consisting only of |
|
1369 | 1357 | __name__=='__main__' and sys.argv constructed as indicated. It thus |
|
1370 | 1358 | sees its environment as if it were being run as a stand-alone |
|
1371 | 1359 | program. But after execution, the IPython interactive namespace gets |
|
1372 | 1360 | updated with all variables defined in the program (except for __name__ |
|
1373 | 1361 | and sys.argv). This allows for very convenient loading of code for |
|
1374 | 1362 | interactive work, while giving each program a 'clean sheet' to run in. |
|
1375 | 1363 | |
|
1376 | 1364 | Options: |
|
1377 | 1365 | |
|
1378 | 1366 | -n: __name__ is NOT set to '__main__', but to the running file's name |
|
1379 | 1367 | without extension (as python does under import). This allows running |
|
1380 | 1368 | scripts and reloading the definitions in them without calling code |
|
1381 | 1369 | protected by an ' if __name__ == "__main__" ' clause. |
|
1382 | 1370 | |
|
1383 | 1371 | -i: run the file in IPython's namespace instead of an empty one. This |
|
1384 | 1372 | is useful if you are experimenting with code written in a text editor |
|
1385 | 1373 | which depends on variables defined interactively. |
|
1386 | 1374 | |
|
1387 | 1375 | -e: ignore sys.exit() calls or SystemExit exceptions in the script |
|
1388 | 1376 | being run. This is particularly useful if IPython is being used to |
|
1389 | 1377 | run unittests, which always exit with a sys.exit() call. In such |
|
1390 | 1378 | cases you are interested in the output of the test results, not in |
|
1391 | 1379 | seeing a traceback of the unittest module. |
|
1392 | 1380 | |
|
1393 | 1381 | -t: print timing information at the end of the run. IPython will give |
|
1394 | 1382 | you an estimated CPU time consumption for your script, which under |
|
1395 | 1383 | Unix uses the resource module to avoid the wraparound problems of |
|
1396 | 1384 | time.clock(). Under Unix, an estimate of time spent on system tasks |
|
1397 | 1385 | is also given (for Windows platforms this is reported as 0.0). |
|
1398 | 1386 | |
|
1399 | 1387 | If -t is given, an additional -N<N> option can be given, where <N> |
|
1400 | 1388 | must be an integer indicating how many times you want the script to |
|
1401 | 1389 | run. The final timing report will include total and per run results. |
|
1402 | 1390 | |
|
1403 | 1391 | For example (testing the script uniq_stable.py): |
|
1404 | 1392 | |
|
1405 | 1393 | In [1]: run -t uniq_stable |
|
1406 | 1394 | |
|
1407 | 1395 | IPython CPU timings (estimated):\\ |
|
1408 | 1396 | User : 0.19597 s.\\ |
|
1409 | 1397 | System: 0.0 s.\\ |
|
1410 | 1398 | |
|
1411 | 1399 | In [2]: run -t -N5 uniq_stable |
|
1412 | 1400 | |
|
1413 | 1401 | IPython CPU timings (estimated):\\ |
|
1414 | 1402 | Total runs performed: 5\\ |
|
1415 | 1403 | Times : Total Per run\\ |
|
1416 | 1404 | User : 0.910862 s, 0.1821724 s.\\ |
|
1417 | 1405 | System: 0.0 s, 0.0 s. |
|
1418 | 1406 | |
|
1419 | 1407 | -d: run your program under the control of pdb, the Python debugger. |
|
1420 | 1408 | This allows you to execute your program step by step, watch variables, |
|
1421 | 1409 | etc. Internally, what IPython does is similar to calling: |
|
1422 | 1410 | |
|
1423 | 1411 | pdb.run('execfile("YOURFILENAME")') |
|
1424 | 1412 | |
|
1425 | 1413 | with a breakpoint set on line 1 of your file. You can change the line |
|
1426 | 1414 | number for this automatic breakpoint to be <N> by using the -bN option |
|
1427 | 1415 | (where N must be an integer). For example: |
|
1428 | 1416 | |
|
1429 | 1417 | %run -d -b40 myscript |
|
1430 | 1418 | |
|
1431 | 1419 | will set the first breakpoint at line 40 in myscript.py. Note that |
|
1432 | 1420 | the first breakpoint must be set on a line which actually does |
|
1433 | 1421 | something (not a comment or docstring) for it to stop execution. |
|
1434 | 1422 | |
|
1435 | 1423 | When the pdb debugger starts, you will see a (Pdb) prompt. You must |
|
1436 | 1424 | first enter 'c' (without qoutes) to start execution up to the first |
|
1437 | 1425 | breakpoint. |
|
1438 | 1426 | |
|
1439 | 1427 | Entering 'help' gives information about the use of the debugger. You |
|
1440 | 1428 | can easily see pdb's full documentation with "import pdb;pdb.help()" |
|
1441 | 1429 | at a prompt. |
|
1442 | 1430 | |
|
1443 | 1431 | -p: run program under the control of the Python profiler module (which |
|
1444 | 1432 | prints a detailed report of execution times, function calls, etc). |
|
1445 | 1433 | |
|
1446 | 1434 | You can pass other options after -p which affect the behavior of the |
|
1447 | 1435 | profiler itself. See the docs for %prun for details. |
|
1448 | 1436 | |
|
1449 | 1437 | In this mode, the program's variables do NOT propagate back to the |
|
1450 | 1438 | IPython interactive namespace (because they remain in the namespace |
|
1451 | 1439 | where the profiler executes them). |
|
1452 | 1440 | |
|
1453 | 1441 | Internally this triggers a call to %prun, see its documentation for |
|
1454 | 1442 | details on the options available specifically for profiling.""" |
|
1455 | 1443 | |
|
1456 | 1444 | # get arguments and set sys.argv for program to be run. |
|
1457 | 1445 | opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e', |
|
1458 | 1446 | mode='list',list_all=1) |
|
1459 | 1447 | |
|
1460 | 1448 | try: |
|
1461 | 1449 | filename = get_py_filename(arg_lst[0]) |
|
1462 | 1450 | except IndexError: |
|
1463 | 1451 | warn('you must provide at least a filename.') |
|
1464 | 1452 | print '\n%run:\n',OInspect.getdoc(self.magic_run) |
|
1465 | 1453 | return |
|
1466 | 1454 | except IOError,msg: |
|
1467 | 1455 | error(msg) |
|
1468 | 1456 | return |
|
1469 | 1457 | |
|
1470 | 1458 | # Control the response to exit() calls made by the script being run |
|
1471 | 1459 | exit_ignore = opts.has_key('e') |
|
1472 | 1460 | |
|
1473 | 1461 | # Make sure that the running script gets a proper sys.argv as if it |
|
1474 | 1462 | # were run from a system shell. |
|
1475 | 1463 | save_argv = sys.argv # save it for later restoring |
|
1476 | 1464 | sys.argv = [filename]+ arg_lst[1:] # put in the proper filename |
|
1477 | 1465 | |
|
1478 | 1466 | if opts.has_key('i'): |
|
1479 | 1467 | prog_ns = self.shell.user_ns |
|
1480 | 1468 | __name__save = self.shell.user_ns['__name__'] |
|
1481 | 1469 | prog_ns['__name__'] = '__main__' |
|
1482 | 1470 | else: |
|
1483 | 1471 | if opts.has_key('n'): |
|
1484 | 1472 | name = os.path.splitext(os.path.basename(filename))[0] |
|
1485 | 1473 | else: |
|
1486 | 1474 | name = '__main__' |
|
1487 | 1475 | prog_ns = {'__name__':name} |
|
1488 | 1476 | |
|
1489 | 1477 | # Since '%run foo' emulates 'python foo.py' at the cmd line, we must |
|
1490 | 1478 | # set the __file__ global in the script's namespace |
|
1491 | 1479 | prog_ns['__file__'] = filename |
|
1492 | ||
|
1480 | ||
|
1493 | 1481 | # pickle fix. See iplib for an explanation. But we need to make sure |
|
1494 | 1482 | # that, if we overwrite __main__, we replace it at the end |
|
1495 | 1483 | if prog_ns['__name__'] == '__main__': |
|
1496 | 1484 | restore_main = sys.modules['__main__'] |
|
1497 | 1485 | else: |
|
1498 | 1486 | restore_main = False |
|
1499 | 1487 | |
|
1500 | 1488 | sys.modules[prog_ns['__name__']] = FakeModule(prog_ns) |
|
1501 | 1489 | |
|
1502 | 1490 | stats = None |
|
1503 | 1491 | try: |
|
1504 | 1492 | if opts.has_key('p'): |
|
1505 | 1493 | stats = self.magic_prun('',0,opts,arg_lst,prog_ns) |
|
1506 | 1494 | else: |
|
1507 | 1495 | if opts.has_key('d'): |
|
1508 | 1496 | deb = Debugger.Pdb(self.shell.rc.colors) |
|
1509 | 1497 | # reset Breakpoint state, which is moronically kept |
|
1510 | 1498 | # in a class |
|
1511 | 1499 | bdb.Breakpoint.next = 1 |
|
1512 | 1500 | bdb.Breakpoint.bplist = {} |
|
1513 | 1501 | bdb.Breakpoint.bpbynumber = [None] |
|
1514 | 1502 | # Set an initial breakpoint to stop execution |
|
1515 | 1503 | maxtries = 10 |
|
1516 | 1504 | bp = int(opts.get('b',[1])[0]) |
|
1517 | 1505 | checkline = deb.checkline(filename,bp) |
|
1518 | 1506 | if not checkline: |
|
1519 | 1507 | for bp in range(bp+1,bp+maxtries+1): |
|
1520 | 1508 | if deb.checkline(filename,bp): |
|
1521 | 1509 | break |
|
1522 | 1510 | else: |
|
1523 | 1511 | msg = ("\nI failed to find a valid line to set " |
|
1524 | 1512 | "a breakpoint\n" |
|
1525 | 1513 | "after trying up to line: %s.\n" |
|
1526 | 1514 | "Please set a valid breakpoint manually " |
|
1527 | 1515 | "with the -b option." % bp) |
|
1528 | 1516 | error(msg) |
|
1529 | 1517 | return |
|
1530 | 1518 | # if we find a good linenumber, set the breakpoint |
|
1531 | 1519 | deb.do_break('%s:%s' % (filename,bp)) |
|
1532 | 1520 | # Start file run |
|
1533 | 1521 | print "NOTE: Enter 'c' at the", |
|
1534 | 1522 | print "ipdb> prompt to start your script." |
|
1535 | 1523 | try: |
|
1536 | 1524 | deb.run('execfile("%s")' % filename,prog_ns) |
|
1537 | 1525 | except: |
|
1538 | 1526 | etype, value, tb = sys.exc_info() |
|
1539 | 1527 | # Skip three frames in the traceback: the %run one, |
|
1540 | 1528 | # one inside bdb.py, and the command-line typed by the |
|
1541 | 1529 | # user (run by exec in pdb itself). |
|
1542 | 1530 | self.shell.InteractiveTB(etype,value,tb,tb_offset=3) |
|
1543 | 1531 | else: |
|
1544 | 1532 | if runner is None: |
|
1545 | 1533 | runner = self.shell.safe_execfile |
|
1546 | 1534 | if opts.has_key('t'): |
|
1547 | 1535 | try: |
|
1548 | 1536 | nruns = int(opts['N'][0]) |
|
1549 | 1537 | if nruns < 1: |
|
1550 | 1538 | error('Number of runs must be >=1') |
|
1551 | 1539 | return |
|
1552 | 1540 | except (KeyError): |
|
1553 | 1541 | nruns = 1 |
|
1554 | 1542 | if nruns == 1: |
|
1555 | 1543 | t0 = clock2() |
|
1556 |
runner(filename,prog_ns,prog_ns, |
|
|
1544 | runner(filename,prog_ns,prog_ns, | |
|
1545 | exit_ignore=exit_ignore) | |
|
1557 | 1546 | t1 = clock2() |
|
1558 | 1547 | t_usr = t1[0]-t0[0] |
|
1559 | 1548 | t_sys = t1[1]-t1[1] |
|
1560 | 1549 | print "\nIPython CPU timings (estimated):" |
|
1561 | 1550 | print " User : %10s s." % t_usr |
|
1562 | 1551 | print " System: %10s s." % t_sys |
|
1563 | 1552 | else: |
|
1564 | 1553 | runs = range(nruns) |
|
1565 | 1554 | t0 = clock2() |
|
1566 | 1555 | for nr in runs: |
|
1567 |
runner(filename,prog_ns,prog_ns, |
|
|
1556 | runner(filename,prog_ns,prog_ns, | |
|
1557 | exit_ignore=exit_ignore) | |
|
1568 | 1558 | t1 = clock2() |
|
1569 | 1559 | t_usr = t1[0]-t0[0] |
|
1570 | 1560 | t_sys = t1[1]-t1[1] |
|
1571 | 1561 | print "\nIPython CPU timings (estimated):" |
|
1572 | 1562 | print "Total runs performed:",nruns |
|
1573 | 1563 | print " Times : %10s %10s" % ('Total','Per run') |
|
1574 | 1564 | print " User : %10s s, %10s s." % (t_usr,t_usr/nruns) |
|
1575 | 1565 | print " System: %10s s, %10s s." % (t_sys,t_sys/nruns) |
|
1576 | 1566 | |
|
1577 | 1567 | else: |
|
1578 | 1568 | runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore) |
|
1579 | 1569 | if opts.has_key('i'): |
|
1580 | 1570 | self.shell.user_ns['__name__'] = __name__save |
|
1581 | 1571 | else: |
|
1582 | 1572 | # update IPython interactive namespace |
|
1583 | 1573 | del prog_ns['__name__'] |
|
1584 | 1574 | self.shell.user_ns.update(prog_ns) |
|
1585 | 1575 | finally: |
|
1586 | 1576 | sys.argv = save_argv |
|
1587 | 1577 | if restore_main: |
|
1588 | 1578 | sys.modules['__main__'] = restore_main |
|
1589 | 1579 | return stats |
|
1590 | 1580 | |
|
1591 | 1581 | def magic_runlog(self, parameter_s =''): |
|
1592 | 1582 | """Run files as logs. |
|
1593 | 1583 | |
|
1594 | 1584 | Usage:\\ |
|
1595 | 1585 | %runlog file1 file2 ... |
|
1596 | 1586 | |
|
1597 | 1587 | Run the named files (treating them as log files) in sequence inside |
|
1598 | 1588 | the interpreter, and return to the prompt. This is much slower than |
|
1599 | 1589 | %run because each line is executed in a try/except block, but it |
|
1600 | 1590 | allows running files with syntax errors in them. |
|
1601 | 1591 | |
|
1602 | 1592 | Normally IPython will guess when a file is one of its own logfiles, so |
|
1603 | 1593 | you can typically use %run even for logs. This shorthand allows you to |
|
1604 | 1594 | force any file to be treated as a log file.""" |
|
1605 | 1595 | |
|
1606 | 1596 | for f in parameter_s.split(): |
|
1607 | 1597 | self.shell.safe_execfile(f,self.shell.user_ns, |
|
1608 | 1598 | self.shell.user_ns,islog=1) |
|
1609 | 1599 | |
|
1610 | 1600 | def magic_timeit(self, parameter_s =''): |
|
1611 | 1601 | """Time execution of a Python statement or expression |
|
1612 | 1602 | |
|
1613 | 1603 | Usage:\\ |
|
1614 | 1604 | %timeit [-n<N> -r<R> [-t|-c]] statement |
|
1615 | 1605 | |
|
1616 | 1606 | Time execution of a Python statement or expression using the timeit |
|
1617 | 1607 | module. |
|
1618 | 1608 | |
|
1619 | 1609 | Options: |
|
1620 | 1610 | -n<N>: execute the given statement <N> times in a loop. If this value |
|
1621 | 1611 | is not given, a fitting value is chosen. |
|
1622 | 1612 | |
|
1623 | 1613 | -r<R>: repeat the loop iteration <R> times and take the best result. |
|
1624 | 1614 | Default: 3 |
|
1625 | 1615 | |
|
1626 | 1616 | -t: use time.time to measure the time, which is the default on Unix. |
|
1627 | 1617 | This function measures wall time. |
|
1628 | 1618 | |
|
1629 | 1619 | -c: use time.clock to measure the time, which is the default on |
|
1630 | 1620 | Windows and measures wall time. On Unix, resource.getrusage is used |
|
1631 | 1621 | instead and returns the CPU user time. |
|
1632 | 1622 | |
|
1633 | 1623 | -p<P>: use a precision of <P> digits to display the timing result. |
|
1634 | 1624 | Default: 3 |
|
1635 | 1625 | |
|
1636 | 1626 | |
|
1637 | 1627 | Examples:\\ |
|
1638 | 1628 | In [1]: %timeit pass |
|
1639 | 1629 | 10000000 loops, best of 3: 53.3 ns per loop |
|
1640 | 1630 | |
|
1641 | 1631 | In [2]: u = None |
|
1642 | 1632 | |
|
1643 | 1633 | In [3]: %timeit u is None |
|
1644 | 1634 | 10000000 loops, best of 3: 184 ns per loop |
|
1645 | 1635 | |
|
1646 | 1636 | In [4]: %timeit -r 4 u == None |
|
1647 | 1637 | 1000000 loops, best of 4: 242 ns per loop |
|
1648 | 1638 | |
|
1649 | 1639 | In [5]: import time |
|
1650 | 1640 | |
|
1651 | 1641 | In [6]: %timeit -n1 time.sleep(2) |
|
1652 | 1642 | 1 loops, best of 3: 2 s per loop |
|
1653 | 1643 | |
|
1654 | 1644 | |
|
1655 | 1645 | The times reported by %timeit will be slightly higher than those |
|
1656 | 1646 | reported by the timeit.py script when variables are accessed. This is |
|
1657 | 1647 | due to the fact that %timeit executes the statement in the namespace |
|
1658 | 1648 | of the shell, compared with timeit.py, which uses a single setup |
|
1659 | 1649 | statement to import function or create variables. Generally, the bias |
|
1660 | 1650 | does not matter as long as results from timeit.py are not mixed with |
|
1661 | 1651 | those from %timeit.""" |
|
1662 | 1652 | |
|
1663 | 1653 | import timeit |
|
1664 | 1654 | import math |
|
1665 | 1655 | |
|
1666 | 1656 | units = ["s", "ms", "\xc2\xb5s", "ns"] |
|
1667 | 1657 | scaling = [1, 1e3, 1e6, 1e9] |
|
1668 | 1658 | |
|
1669 | 1659 | opts, stmt = self.parse_options(parameter_s,'n:r:tcp:', |
|
1670 | 1660 | posix=False) |
|
1671 | 1661 | if stmt == "": |
|
1672 | 1662 | return |
|
1673 | 1663 | timefunc = timeit.default_timer |
|
1674 | 1664 | number = int(getattr(opts, "n", 0)) |
|
1675 | 1665 | repeat = int(getattr(opts, "r", timeit.default_repeat)) |
|
1676 | 1666 | precision = int(getattr(opts, "p", 3)) |
|
1677 | 1667 | if hasattr(opts, "t"): |
|
1678 | 1668 | timefunc = time.time |
|
1679 | 1669 | if hasattr(opts, "c"): |
|
1680 | 1670 | timefunc = clock |
|
1681 | 1671 | |
|
1682 | 1672 | timer = timeit.Timer(timer=timefunc) |
|
1683 | 1673 | # this code has tight coupling to the inner workings of timeit.Timer, |
|
1684 | 1674 | # but is there a better way to achieve that the code stmt has access |
|
1685 | 1675 | # to the shell namespace? |
|
1686 | 1676 | |
|
1687 | 1677 | src = timeit.template % {'stmt': timeit.reindent(stmt, 8), |
|
1688 | 1678 | 'setup': "pass"} |
|
1689 | 1679 | code = compile(src, "<magic-timeit>", "exec") |
|
1690 | 1680 | ns = {} |
|
1691 | 1681 | exec code in self.shell.user_ns, ns |
|
1692 | 1682 | timer.inner = ns["inner"] |
|
1693 | 1683 | |
|
1694 | 1684 | if number == 0: |
|
1695 | 1685 | # determine number so that 0.2 <= total time < 2.0 |
|
1696 | 1686 | number = 1 |
|
1697 | 1687 | for i in range(1, 10): |
|
1698 | 1688 | number *= 10 |
|
1699 | 1689 | if timer.timeit(number) >= 0.2: |
|
1700 | 1690 | break |
|
1701 | 1691 | |
|
1702 | 1692 | best = min(timer.repeat(repeat, number)) / number |
|
1703 | 1693 | |
|
1704 | 1694 | if best > 0.0: |
|
1705 | 1695 | order = min(-int(math.floor(math.log10(best)) // 3), 3) |
|
1706 | 1696 | else: |
|
1707 | 1697 | order = 3 |
|
1708 | 1698 | print "%d loops, best of %d: %.*g %s per loop" % (number, repeat, |
|
1709 | 1699 | precision, |
|
1710 | 1700 | best * scaling[order], |
|
1711 | 1701 | units[order]) |
|
1712 | 1702 | |
|
1713 | 1703 | def magic_time(self,parameter_s = ''): |
|
1714 | 1704 | """Time execution of a Python statement or expression. |
|
1715 | 1705 | |
|
1716 | 1706 | The CPU and wall clock times are printed, and the value of the |
|
1717 | 1707 | expression (if any) is returned. Note that under Win32, system time |
|
1718 | 1708 | is always reported as 0, since it can not be measured. |
|
1719 | 1709 | |
|
1720 | 1710 | This function provides very basic timing functionality. In Python |
|
1721 | 1711 | 2.3, the timeit module offers more control and sophistication, so this |
|
1722 | 1712 | could be rewritten to use it (patches welcome). |
|
1723 | 1713 | |
|
1724 | 1714 | Some examples: |
|
1725 | 1715 | |
|
1726 | 1716 | In [1]: time 2**128 |
|
1727 | 1717 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1728 | 1718 | Wall time: 0.00 |
|
1729 | 1719 | Out[1]: 340282366920938463463374607431768211456L |
|
1730 | 1720 | |
|
1731 | 1721 | In [2]: n = 1000000 |
|
1732 | 1722 | |
|
1733 | 1723 | In [3]: time sum(range(n)) |
|
1734 | 1724 | CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s |
|
1735 | 1725 | Wall time: 1.37 |
|
1736 | 1726 | Out[3]: 499999500000L |
|
1737 | 1727 | |
|
1738 | 1728 | In [4]: time print 'hello world' |
|
1739 | 1729 | hello world |
|
1740 | 1730 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1741 | 1731 | Wall time: 0.00 |
|
1742 | 1732 | """ |
|
1743 | 1733 | |
|
1744 | 1734 | # fail immediately if the given expression can't be compiled |
|
1745 | 1735 | try: |
|
1746 | 1736 | mode = 'eval' |
|
1747 | 1737 | code = compile(parameter_s,'<timed eval>',mode) |
|
1748 | 1738 | except SyntaxError: |
|
1749 | 1739 | mode = 'exec' |
|
1750 | 1740 | code = compile(parameter_s,'<timed exec>',mode) |
|
1751 | 1741 | # skew measurement as little as possible |
|
1752 | 1742 | glob = self.shell.user_ns |
|
1753 | 1743 | clk = clock2 |
|
1754 | 1744 | wtime = time.time |
|
1755 | 1745 | # time execution |
|
1756 | 1746 | wall_st = wtime() |
|
1757 | 1747 | if mode=='eval': |
|
1758 | 1748 | st = clk() |
|
1759 | 1749 | out = eval(code,glob) |
|
1760 | 1750 | end = clk() |
|
1761 | 1751 | else: |
|
1762 | 1752 | st = clk() |
|
1763 | 1753 | exec code in glob |
|
1764 | 1754 | end = clk() |
|
1765 | 1755 | out = None |
|
1766 | 1756 | wall_end = wtime() |
|
1767 | 1757 | # Compute actual times and report |
|
1768 | 1758 | wall_time = wall_end-wall_st |
|
1769 | 1759 | cpu_user = end[0]-st[0] |
|
1770 | 1760 | cpu_sys = end[1]-st[1] |
|
1771 | 1761 | cpu_tot = cpu_user+cpu_sys |
|
1772 | 1762 | print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \ |
|
1773 | 1763 | (cpu_user,cpu_sys,cpu_tot) |
|
1774 | 1764 | print "Wall time: %.2f" % wall_time |
|
1775 | 1765 | return out |
|
1776 | 1766 | |
|
1777 | 1767 | def magic_macro(self,parameter_s = ''): |
|
1778 | 1768 | """Define a set of input lines as a macro for future re-execution. |
|
1779 | 1769 | |
|
1780 | 1770 | Usage:\\ |
|
1781 | 1771 | %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ... |
|
1782 | 1772 | |
|
1783 | 1773 | Options: |
|
1784 | 1774 | |
|
1785 | 1775 | -r: use 'raw' input. By default, the 'processed' history is used, |
|
1786 | 1776 | so that magics are loaded in their transformed version to valid |
|
1787 | 1777 | Python. If this option is given, the raw input as typed as the |
|
1788 | 1778 | command line is used instead. |
|
1789 | 1779 | |
|
1790 | 1780 | This will define a global variable called `name` which is a string |
|
1791 | 1781 | made of joining the slices and lines you specify (n1,n2,... numbers |
|
1792 | 1782 | above) from your input history into a single string. This variable |
|
1793 | 1783 | acts like an automatic function which re-executes those lines as if |
|
1794 | 1784 | you had typed them. You just type 'name' at the prompt and the code |
|
1795 | 1785 | executes. |
|
1796 | 1786 | |
|
1797 | 1787 | The notation for indicating number ranges is: n1-n2 means 'use line |
|
1798 | 1788 | numbers n1,...n2' (the endpoint is included). That is, '5-7' means |
|
1799 | 1789 | using the lines numbered 5,6 and 7. |
|
1800 | 1790 | |
|
1801 | 1791 | Note: as a 'hidden' feature, you can also use traditional python slice |
|
1802 | 1792 | notation, where N:M means numbers N through M-1. |
|
1803 | 1793 | |
|
1804 | 1794 | For example, if your history contains (%hist prints it): |
|
1805 | 1795 | |
|
1806 | 1796 | 44: x=1\\ |
|
1807 | 1797 | 45: y=3\\ |
|
1808 | 1798 | 46: z=x+y\\ |
|
1809 | 1799 | 47: print x\\ |
|
1810 | 1800 | 48: a=5\\ |
|
1811 | 1801 | 49: print 'x',x,'y',y\\ |
|
1812 | 1802 | |
|
1813 | 1803 | you can create a macro with lines 44 through 47 (included) and line 49 |
|
1814 | 1804 | called my_macro with: |
|
1815 | 1805 | |
|
1816 | 1806 | In [51]: %macro my_macro 44-47 49 |
|
1817 | 1807 | |
|
1818 | 1808 | Now, typing `my_macro` (without quotes) will re-execute all this code |
|
1819 | 1809 | in one pass. |
|
1820 | 1810 | |
|
1821 | 1811 | You don't need to give the line-numbers in order, and any given line |
|
1822 | 1812 | number can appear multiple times. You can assemble macros with any |
|
1823 | 1813 | lines from your input history in any order. |
|
1824 | 1814 | |
|
1825 | 1815 | The macro is a simple object which holds its value in an attribute, |
|
1826 | 1816 | but IPython's display system checks for macros and executes them as |
|
1827 | 1817 | code instead of printing them when you type their name. |
|
1828 | 1818 | |
|
1829 | 1819 | You can view a macro's contents by explicitly printing it with: |
|
1830 | 1820 | |
|
1831 | 1821 | 'print macro_name'. |
|
1832 | 1822 | |
|
1833 | 1823 | For one-off cases which DON'T contain magic function calls in them you |
|
1834 | 1824 | can obtain similar results by explicitly executing slices from your |
|
1835 | 1825 | input history with: |
|
1836 | 1826 | |
|
1837 | 1827 | In [60]: exec In[44:48]+In[49]""" |
|
1838 | 1828 | |
|
1839 | 1829 | opts,args = self.parse_options(parameter_s,'r',mode='list') |
|
1840 | 1830 | name,ranges = args[0], args[1:] |
|
1841 | 1831 | #print 'rng',ranges # dbg |
|
1842 | 1832 | lines = self.extract_input_slices(ranges,opts.has_key('r')) |
|
1843 | 1833 | macro = Macro(lines) |
|
1844 | 1834 | self.shell.user_ns.update({name:macro}) |
|
1845 | 1835 | print 'Macro `%s` created. To execute, type its name (without quotes).' % name |
|
1846 | 1836 | print 'Macro contents:' |
|
1847 | 1837 | print macro, |
|
1848 | 1838 | |
|
1849 | 1839 | def magic_save(self,parameter_s = ''): |
|
1850 | 1840 | """Save a set of lines to a given filename. |
|
1851 | 1841 | |
|
1852 | 1842 | Usage:\\ |
|
1853 | 1843 | %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ... |
|
1854 | 1844 | |
|
1855 | 1845 | Options: |
|
1856 | 1846 | |
|
1857 | 1847 | -r: use 'raw' input. By default, the 'processed' history is used, |
|
1858 | 1848 | so that magics are loaded in their transformed version to valid |
|
1859 | 1849 | Python. If this option is given, the raw input as typed as the |
|
1860 | 1850 | command line is used instead. |
|
1861 | 1851 | |
|
1862 | 1852 | This function uses the same syntax as %macro for line extraction, but |
|
1863 | 1853 | instead of creating a macro it saves the resulting string to the |
|
1864 | 1854 | filename you specify. |
|
1865 | 1855 | |
|
1866 | 1856 | It adds a '.py' extension to the file if you don't do so yourself, and |
|
1867 | 1857 | it asks for confirmation before overwriting existing files.""" |
|
1868 | 1858 | |
|
1869 | 1859 | opts,args = self.parse_options(parameter_s,'r',mode='list') |
|
1870 | 1860 | fname,ranges = args[0], args[1:] |
|
1871 | 1861 | if not fname.endswith('.py'): |
|
1872 | 1862 | fname += '.py' |
|
1873 | 1863 | if os.path.isfile(fname): |
|
1874 | 1864 | ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname) |
|
1875 | 1865 | if ans.lower() not in ['y','yes']: |
|
1876 | 1866 | print 'Operation cancelled.' |
|
1877 | 1867 | return |
|
1878 | 1868 | cmds = ''.join(self.extract_input_slices(ranges,opts.has_key('r'))) |
|
1879 | 1869 | f = file(fname,'w') |
|
1880 | 1870 | f.write(cmds) |
|
1881 | 1871 | f.close() |
|
1882 | 1872 | print 'The following commands were written to file `%s`:' % fname |
|
1883 | 1873 | print cmds |
|
1884 | 1874 | |
|
1885 | 1875 | def _edit_macro(self,mname,macro): |
|
1886 | 1876 | """open an editor with the macro data in a file""" |
|
1887 | 1877 | filename = self.shell.mktempfile(macro.value) |
|
1888 | 1878 | self.shell.hooks.editor(filename) |
|
1889 | 1879 | |
|
1890 | 1880 | # and make a new macro object, to replace the old one |
|
1891 | 1881 | mfile = open(filename) |
|
1892 | 1882 | mvalue = mfile.read() |
|
1893 | 1883 | mfile.close() |
|
1894 | 1884 | self.shell.user_ns[mname] = Macro(mvalue) |
|
1895 | 1885 | |
|
1896 | 1886 | def magic_ed(self,parameter_s=''): |
|
1897 | 1887 | """Alias to %edit.""" |
|
1898 | 1888 | return self.magic_edit(parameter_s) |
|
1899 | 1889 | |
|
1900 | 1890 | def magic_edit(self,parameter_s='',last_call=['','']): |
|
1901 | 1891 | """Bring up an editor and execute the resulting code. |
|
1902 | 1892 | |
|
1903 | 1893 | Usage: |
|
1904 | 1894 | %edit [options] [args] |
|
1905 | 1895 | |
|
1906 | 1896 | %edit runs IPython's editor hook. The default version of this hook is |
|
1907 | 1897 | set to call the __IPYTHON__.rc.editor command. This is read from your |
|
1908 | 1898 | environment variable $EDITOR. If this isn't found, it will default to |
|
1909 | 1899 | vi under Linux/Unix and to notepad under Windows. See the end of this |
|
1910 | 1900 | docstring for how to change the editor hook. |
|
1911 | 1901 | |
|
1912 | 1902 | You can also set the value of this editor via the command line option |
|
1913 | 1903 | '-editor' or in your ipythonrc file. This is useful if you wish to use |
|
1914 | 1904 | specifically for IPython an editor different from your typical default |
|
1915 | 1905 | (and for Windows users who typically don't set environment variables). |
|
1916 | 1906 | |
|
1917 | 1907 | This command allows you to conveniently edit multi-line code right in |
|
1918 | 1908 | your IPython session. |
|
1919 | 1909 | |
|
1920 | 1910 | If called without arguments, %edit opens up an empty editor with a |
|
1921 | 1911 | temporary file and will execute the contents of this file when you |
|
1922 | 1912 | close it (don't forget to save it!). |
|
1923 | 1913 | |
|
1924 | 1914 | |
|
1925 | 1915 | Options: |
|
1926 | 1916 | |
|
1927 | 1917 | -n <number>: open the editor at a specified line number. By default, |
|
1928 | 1918 | the IPython editor hook uses the unix syntax 'editor +N filename', but |
|
1929 | 1919 | you can configure this by providing your own modified hook if your |
|
1930 | 1920 | favorite editor supports line-number specifications with a different |
|
1931 | 1921 | syntax. |
|
1932 | 1922 | |
|
1933 | 1923 | -p: this will call the editor with the same data as the previous time |
|
1934 | 1924 | it was used, regardless of how long ago (in your current session) it |
|
1935 | 1925 | was. |
|
1936 | 1926 | |
|
1937 | 1927 | -r: use 'raw' input. This option only applies to input taken from the |
|
1938 | 1928 | user's history. By default, the 'processed' history is used, so that |
|
1939 | 1929 | magics are loaded in their transformed version to valid Python. If |
|
1940 | 1930 | this option is given, the raw input as typed as the command line is |
|
1941 | 1931 | used instead. When you exit the editor, it will be executed by |
|
1942 | 1932 | IPython's own processor. |
|
1943 | 1933 | |
|
1944 | 1934 | -x: do not execute the edited code immediately upon exit. This is |
|
1945 | 1935 | mainly useful if you are editing programs which need to be called with |
|
1946 | 1936 | command line arguments, which you can then do using %run. |
|
1947 | 1937 | |
|
1948 | 1938 | |
|
1949 | 1939 | Arguments: |
|
1950 | 1940 | |
|
1951 | 1941 | If arguments are given, the following possibilites exist: |
|
1952 | 1942 | |
|
1953 | 1943 | - The arguments are numbers or pairs of colon-separated numbers (like |
|
1954 | 1944 | 1 4:8 9). These are interpreted as lines of previous input to be |
|
1955 | 1945 | loaded into the editor. The syntax is the same of the %macro command. |
|
1956 | 1946 | |
|
1957 | 1947 | - If the argument doesn't start with a number, it is evaluated as a |
|
1958 | 1948 | variable and its contents loaded into the editor. You can thus edit |
|
1959 | 1949 | any string which contains python code (including the result of |
|
1960 | 1950 | previous edits). |
|
1961 | 1951 | |
|
1962 | 1952 | - If the argument is the name of an object (other than a string), |
|
1963 | 1953 | IPython will try to locate the file where it was defined and open the |
|
1964 | 1954 | editor at the point where it is defined. You can use `%edit function` |
|
1965 | 1955 | to load an editor exactly at the point where 'function' is defined, |
|
1966 | 1956 | edit it and have the file be executed automatically. |
|
1967 | 1957 | |
|
1968 | 1958 | If the object is a macro (see %macro for details), this opens up your |
|
1969 | 1959 | specified editor with a temporary file containing the macro's data. |
|
1970 | 1960 | Upon exit, the macro is reloaded with the contents of the file. |
|
1971 | 1961 | |
|
1972 | 1962 | Note: opening at an exact line is only supported under Unix, and some |
|
1973 | 1963 | editors (like kedit and gedit up to Gnome 2.8) do not understand the |
|
1974 | 1964 | '+NUMBER' parameter necessary for this feature. Good editors like |
|
1975 | 1965 | (X)Emacs, vi, jed, pico and joe all do. |
|
1976 | 1966 | |
|
1977 | 1967 | - If the argument is not found as a variable, IPython will look for a |
|
1978 | 1968 | file with that name (adding .py if necessary) and load it into the |
|
1979 | 1969 | editor. It will execute its contents with execfile() when you exit, |
|
1980 | 1970 | loading any code in the file into your interactive namespace. |
|
1981 | 1971 | |
|
1982 | 1972 | After executing your code, %edit will return as output the code you |
|
1983 | 1973 | typed in the editor (except when it was an existing file). This way |
|
1984 | 1974 | you can reload the code in further invocations of %edit as a variable, |
|
1985 | 1975 | via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of |
|
1986 | 1976 | the output. |
|
1987 | 1977 | |
|
1988 | 1978 | Note that %edit is also available through the alias %ed. |
|
1989 | 1979 | |
|
1990 | 1980 | This is an example of creating a simple function inside the editor and |
|
1991 | 1981 | then modifying it. First, start up the editor: |
|
1992 | 1982 | |
|
1993 | 1983 | In [1]: ed\\ |
|
1994 | 1984 | Editing... done. Executing edited code...\\ |
|
1995 | 1985 | Out[1]: 'def foo():\\n print "foo() was defined in an editing session"\\n' |
|
1996 | 1986 | |
|
1997 | 1987 | We can then call the function foo(): |
|
1998 | 1988 | |
|
1999 | 1989 | In [2]: foo()\\ |
|
2000 | 1990 | foo() was defined in an editing session |
|
2001 | 1991 | |
|
2002 | 1992 | Now we edit foo. IPython automatically loads the editor with the |
|
2003 | 1993 | (temporary) file where foo() was previously defined: |
|
2004 | 1994 | |
|
2005 | 1995 | In [3]: ed foo\\ |
|
2006 | 1996 | Editing... done. Executing edited code... |
|
2007 | 1997 | |
|
2008 | 1998 | And if we call foo() again we get the modified version: |
|
2009 | 1999 | |
|
2010 | 2000 | In [4]: foo()\\ |
|
2011 | 2001 | foo() has now been changed! |
|
2012 | 2002 | |
|
2013 | 2003 | Here is an example of how to edit a code snippet successive |
|
2014 | 2004 | times. First we call the editor: |
|
2015 | 2005 | |
|
2016 | 2006 | In [8]: ed\\ |
|
2017 | 2007 | Editing... done. Executing edited code...\\ |
|
2018 | 2008 | hello\\ |
|
2019 | 2009 | Out[8]: "print 'hello'\\n" |
|
2020 | 2010 | |
|
2021 | 2011 | Now we call it again with the previous output (stored in _): |
|
2022 | 2012 | |
|
2023 | 2013 | In [9]: ed _\\ |
|
2024 | 2014 | Editing... done. Executing edited code...\\ |
|
2025 | 2015 | hello world\\ |
|
2026 | 2016 | Out[9]: "print 'hello world'\\n" |
|
2027 | 2017 | |
|
2028 | 2018 | Now we call it with the output #8 (stored in _8, also as Out[8]): |
|
2029 | 2019 | |
|
2030 | 2020 | In [10]: ed _8\\ |
|
2031 | 2021 | Editing... done. Executing edited code...\\ |
|
2032 | 2022 | hello again\\ |
|
2033 | 2023 | Out[10]: "print 'hello again'\\n" |
|
2034 | 2024 | |
|
2035 | 2025 | |
|
2036 | 2026 | Changing the default editor hook: |
|
2037 | 2027 | |
|
2038 | 2028 | If you wish to write your own editor hook, you can put it in a |
|
2039 | 2029 | configuration file which you load at startup time. The default hook |
|
2040 | 2030 | is defined in the IPython.hooks module, and you can use that as a |
|
2041 | 2031 | starting example for further modifications. That file also has |
|
2042 | 2032 | general instructions on how to set a new hook for use once you've |
|
2043 | 2033 | defined it.""" |
|
2044 | 2034 | |
|
2045 | 2035 | # FIXME: This function has become a convoluted mess. It needs a |
|
2046 | 2036 | # ground-up rewrite with clean, simple logic. |
|
2047 | 2037 | |
|
2048 | 2038 | def make_filename(arg): |
|
2049 | 2039 | "Make a filename from the given args" |
|
2050 | 2040 | try: |
|
2051 | 2041 | filename = get_py_filename(arg) |
|
2052 | 2042 | except IOError: |
|
2053 | 2043 | if args.endswith('.py'): |
|
2054 | 2044 | filename = arg |
|
2055 | 2045 | else: |
|
2056 | 2046 | filename = None |
|
2057 | 2047 | return filename |
|
2058 | 2048 | |
|
2059 | 2049 | # custom exceptions |
|
2060 | 2050 | class DataIsObject(Exception): pass |
|
2061 | 2051 | |
|
2062 | 2052 | opts,args = self.parse_options(parameter_s,'prxn:') |
|
2063 | 2053 | # Set a few locals from the options for convenience: |
|
2064 | 2054 | opts_p = opts.has_key('p') |
|
2065 | 2055 | opts_r = opts.has_key('r') |
|
2066 | 2056 | |
|
2067 | 2057 | # Default line number value |
|
2068 | 2058 | lineno = opts.get('n',None) |
|
2069 | 2059 | |
|
2070 | 2060 | if opts_p: |
|
2071 | 2061 | args = '_%s' % last_call[0] |
|
2072 | 2062 | if not self.shell.user_ns.has_key(args): |
|
2073 | 2063 | args = last_call[1] |
|
2074 | 2064 | |
|
2075 | 2065 | # use last_call to remember the state of the previous call, but don't |
|
2076 | 2066 | # let it be clobbered by successive '-p' calls. |
|
2077 | 2067 | try: |
|
2078 | 2068 | last_call[0] = self.shell.outputcache.prompt_count |
|
2079 | 2069 | if not opts_p: |
|
2080 | 2070 | last_call[1] = parameter_s |
|
2081 | 2071 | except: |
|
2082 | 2072 | pass |
|
2083 | 2073 | |
|
2084 | 2074 | # by default this is done with temp files, except when the given |
|
2085 | 2075 | # arg is a filename |
|
2086 | 2076 | use_temp = 1 |
|
2087 | 2077 | |
|
2088 | 2078 | if re.match(r'\d',args): |
|
2089 | 2079 | # Mode where user specifies ranges of lines, like in %macro. |
|
2090 | 2080 | # This means that you can't edit files whose names begin with |
|
2091 | 2081 | # numbers this way. Tough. |
|
2092 | 2082 | ranges = args.split() |
|
2093 | 2083 | data = ''.join(self.extract_input_slices(ranges,opts_r)) |
|
2094 | 2084 | elif args.endswith('.py'): |
|
2095 | 2085 | filename = make_filename(args) |
|
2096 | 2086 | data = '' |
|
2097 | 2087 | use_temp = 0 |
|
2098 | 2088 | elif args: |
|
2099 | 2089 | try: |
|
2100 | 2090 | # Load the parameter given as a variable. If not a string, |
|
2101 | 2091 | # process it as an object instead (below) |
|
2102 | 2092 | |
|
2103 | 2093 | #print '*** args',args,'type',type(args) # dbg |
|
2104 | 2094 | data = eval(args,self.shell.user_ns) |
|
2105 | 2095 | if not type(data) in StringTypes: |
|
2106 | 2096 | raise DataIsObject |
|
2107 | 2097 | |
|
2108 | 2098 | except (NameError,SyntaxError): |
|
2109 | 2099 | # given argument is not a variable, try as a filename |
|
2110 | 2100 | filename = make_filename(args) |
|
2111 | 2101 | if filename is None: |
|
2112 | 2102 | warn("Argument given (%s) can't be found as a variable " |
|
2113 | 2103 | "or as a filename." % args) |
|
2114 | 2104 | return |
|
2115 | 2105 | |
|
2116 | 2106 | data = '' |
|
2117 | 2107 | use_temp = 0 |
|
2118 | 2108 | except DataIsObject: |
|
2119 | 2109 | |
|
2120 | 2110 | # macros have a special edit function |
|
2121 | 2111 | if isinstance(data,Macro): |
|
2122 | 2112 | self._edit_macro(args,data) |
|
2123 | 2113 | return |
|
2124 | 2114 | |
|
2125 | 2115 | # For objects, try to edit the file where they are defined |
|
2126 | 2116 | try: |
|
2127 | 2117 | filename = inspect.getabsfile(data) |
|
2128 | 2118 | datafile = 1 |
|
2129 | 2119 | except TypeError: |
|
2130 | 2120 | filename = make_filename(args) |
|
2131 | 2121 | datafile = 1 |
|
2132 | 2122 | warn('Could not find file where `%s` is defined.\n' |
|
2133 | 2123 | 'Opening a file named `%s`' % (args,filename)) |
|
2134 | 2124 | # Now, make sure we can actually read the source (if it was in |
|
2135 | 2125 | # a temp file it's gone by now). |
|
2136 | 2126 | if datafile: |
|
2137 | 2127 | try: |
|
2138 | 2128 | if lineno is None: |
|
2139 | 2129 | lineno = inspect.getsourcelines(data)[1] |
|
2140 | 2130 | except IOError: |
|
2141 | 2131 | filename = make_filename(args) |
|
2142 | 2132 | if filename is None: |
|
2143 | 2133 | warn('The file `%s` where `%s` was defined cannot ' |
|
2144 | 2134 | 'be read.' % (filename,data)) |
|
2145 | 2135 | return |
|
2146 | 2136 | use_temp = 0 |
|
2147 | 2137 | else: |
|
2148 | 2138 | data = '' |
|
2149 | 2139 | |
|
2150 | 2140 | if use_temp: |
|
2151 | 2141 | filename = self.shell.mktempfile(data) |
|
2152 | 2142 | print 'IPython will make a temporary file named:',filename |
|
2153 | 2143 | |
|
2154 | 2144 | # do actual editing here |
|
2155 | 2145 | print 'Editing...', |
|
2156 | 2146 | sys.stdout.flush() |
|
2157 | 2147 | self.shell.hooks.editor(filename,lineno) |
|
2158 | 2148 | if opts.has_key('x'): # -x prevents actual execution |
|
2159 | 2149 | |
|
2160 | 2150 | else: |
|
2161 | 2151 | print 'done. Executing edited code...' |
|
2162 | 2152 | if opts_r: |
|
2163 | 2153 | self.shell.runlines(file_read(filename)) |
|
2164 | 2154 | else: |
|
2165 | 2155 | self.shell.safe_execfile(filename,self.shell.user_ns) |
|
2166 | 2156 | if use_temp: |
|
2167 | 2157 | try: |
|
2168 | 2158 | return open(filename).read() |
|
2169 | 2159 | except IOError,msg: |
|
2170 | 2160 | if msg.filename == filename: |
|
2171 | 2161 | warn('File not found. Did you forget to save?') |
|
2172 | 2162 | return |
|
2173 | 2163 | else: |
|
2174 | 2164 | self.shell.showtraceback() |
|
2175 | 2165 | |
|
2176 | 2166 | def magic_xmode(self,parameter_s = ''): |
|
2177 | 2167 | """Switch modes for the exception handlers. |
|
2178 | 2168 | |
|
2179 | 2169 | Valid modes: Plain, Context and Verbose. |
|
2180 | 2170 | |
|
2181 | 2171 | If called without arguments, acts as a toggle.""" |
|
2182 | 2172 | |
|
2183 | 2173 | def xmode_switch_err(name): |
|
2184 | 2174 | warn('Error changing %s exception modes.\n%s' % |
|
2185 | 2175 | (name,sys.exc_info()[1])) |
|
2186 | 2176 | |
|
2187 | 2177 | shell = self.shell |
|
2188 | 2178 | new_mode = parameter_s.strip().capitalize() |
|
2189 | 2179 | try: |
|
2190 | 2180 | shell.InteractiveTB.set_mode(mode=new_mode) |
|
2191 | 2181 | print 'Exception reporting mode:',shell.InteractiveTB.mode |
|
2192 | 2182 | except: |
|
2193 | 2183 | xmode_switch_err('user') |
|
2194 | 2184 | |
|
2195 | 2185 | # threaded shells use a special handler in sys.excepthook |
|
2196 | 2186 | if shell.isthreaded: |
|
2197 | 2187 | try: |
|
2198 | 2188 | shell.sys_excepthook.set_mode(mode=new_mode) |
|
2199 | 2189 | except: |
|
2200 | 2190 | xmode_switch_err('threaded') |
|
2201 | 2191 | |
|
2202 | 2192 | def magic_colors(self,parameter_s = ''): |
|
2203 | 2193 | """Switch color scheme for prompts, info system and exception handlers. |
|
2204 | 2194 | |
|
2205 | 2195 | Currently implemented schemes: NoColor, Linux, LightBG. |
|
2206 | 2196 | |
|
2207 | 2197 | Color scheme names are not case-sensitive.""" |
|
2208 | 2198 | |
|
2209 | 2199 | def color_switch_err(name): |
|
2210 | 2200 | warn('Error changing %s color schemes.\n%s' % |
|
2211 | 2201 | (name,sys.exc_info()[1])) |
|
2212 | 2202 | |
|
2213 | 2203 | |
|
2214 | 2204 | new_scheme = parameter_s.strip() |
|
2215 | 2205 | if not new_scheme: |
|
2216 | 2206 | print 'You must specify a color scheme.' |
|
2217 | 2207 | return |
|
2218 | 2208 | import IPython.rlineimpl as readline |
|
2219 | 2209 | if not readline.have_readline: |
|
2220 | 2210 | msg = """\ |
|
2221 | 2211 | Proper color support under MS Windows requires the pyreadline library. |
|
2222 | 2212 | You can find it at: |
|
2223 | 2213 | http://ipython.scipy.org/moin/PyReadline/Intro |
|
2224 | 2214 | Gary's readline needs the ctypes module, from: |
|
2225 | 2215 | http://starship.python.net/crew/theller/ctypes |
|
2226 | 2216 | (Note that ctypes is already part of Python versions 2.5 and newer). |
|
2227 | 2217 | |
|
2228 | 2218 | Defaulting color scheme to 'NoColor'""" |
|
2229 | 2219 | new_scheme = 'NoColor' |
|
2230 | 2220 | warn(msg) |
|
2231 | 2221 | # local shortcut |
|
2232 | 2222 | shell = self.shell |
|
2233 | 2223 | |
|
2234 | 2224 | # Set prompt colors |
|
2235 | 2225 | try: |
|
2236 | 2226 | shell.outputcache.set_colors(new_scheme) |
|
2237 | 2227 | except: |
|
2238 | 2228 | color_switch_err('prompt') |
|
2239 | 2229 | else: |
|
2240 | 2230 | shell.rc.colors = \ |
|
2241 | 2231 | shell.outputcache.color_table.active_scheme_name |
|
2242 | 2232 | # Set exception colors |
|
2243 | 2233 | try: |
|
2244 | 2234 | shell.InteractiveTB.set_colors(scheme = new_scheme) |
|
2245 | 2235 | shell.SyntaxTB.set_colors(scheme = new_scheme) |
|
2246 | 2236 | except: |
|
2247 | 2237 | color_switch_err('exception') |
|
2248 | 2238 | |
|
2249 | 2239 | # threaded shells use a verbose traceback in sys.excepthook |
|
2250 | 2240 | if shell.isthreaded: |
|
2251 | 2241 | try: |
|
2252 | 2242 | shell.sys_excepthook.set_colors(scheme=new_scheme) |
|
2253 | 2243 | except: |
|
2254 | 2244 | color_switch_err('system exception handler') |
|
2255 | 2245 | |
|
2256 | 2246 | # Set info (for 'object?') colors |
|
2257 | 2247 | if shell.rc.color_info: |
|
2258 | 2248 | try: |
|
2259 | 2249 | shell.inspector.set_active_scheme(new_scheme) |
|
2260 | 2250 | except: |
|
2261 | 2251 | color_switch_err('object inspector') |
|
2262 | 2252 | else: |
|
2263 | 2253 | shell.inspector.set_active_scheme('NoColor') |
|
2264 | 2254 | |
|
2265 | 2255 | def magic_color_info(self,parameter_s = ''): |
|
2266 | 2256 | """Toggle color_info. |
|
2267 | 2257 | |
|
2268 | 2258 | The color_info configuration parameter controls whether colors are |
|
2269 | 2259 | used for displaying object details (by things like %psource, %pfile or |
|
2270 | 2260 | the '?' system). This function toggles this value with each call. |
|
2271 | 2261 | |
|
2272 | 2262 | Note that unless you have a fairly recent pager (less works better |
|
2273 | 2263 | than more) in your system, using colored object information displays |
|
2274 | 2264 | will not work properly. Test it and see.""" |
|
2275 | 2265 | |
|
2276 | 2266 | self.shell.rc.color_info = 1 - self.shell.rc.color_info |
|
2277 | 2267 | self.magic_colors(self.shell.rc.colors) |
|
2278 | 2268 | print 'Object introspection functions have now coloring:', |
|
2279 | 2269 | print ['OFF','ON'][self.shell.rc.color_info] |
|
2280 | 2270 | |
|
2281 | 2271 | def magic_Pprint(self, parameter_s=''): |
|
2282 | 2272 | """Toggle pretty printing on/off.""" |
|
2283 | 2273 | |
|
2284 | 2274 | self.shell.rc.pprint = 1 - self.shell.rc.pprint |
|
2285 | 2275 | print 'Pretty printing has been turned', \ |
|
2286 | 2276 | ['OFF','ON'][self.shell.rc.pprint] |
|
2287 | 2277 | |
|
2288 | 2278 | def magic_exit(self, parameter_s=''): |
|
2289 | 2279 | """Exit IPython, confirming if configured to do so. |
|
2290 | 2280 | |
|
2291 | 2281 | You can configure whether IPython asks for confirmation upon exit by |
|
2292 | 2282 | setting the confirm_exit flag in the ipythonrc file.""" |
|
2293 | 2283 | |
|
2294 | 2284 | self.shell.exit() |
|
2295 | 2285 | |
|
2296 | 2286 | def magic_quit(self, parameter_s=''): |
|
2297 | 2287 | """Exit IPython, confirming if configured to do so (like %exit)""" |
|
2298 | 2288 | |
|
2299 | 2289 | self.shell.exit() |
|
2300 | 2290 | |
|
2301 | 2291 | def magic_Exit(self, parameter_s=''): |
|
2302 | 2292 | """Exit IPython without confirmation.""" |
|
2303 | 2293 | |
|
2304 | 2294 | self.shell.exit_now = True |
|
2305 | 2295 | |
|
2306 | 2296 | def magic_Quit(self, parameter_s=''): |
|
2307 | 2297 | """Exit IPython without confirmation (like %Exit).""" |
|
2308 | 2298 | |
|
2309 | 2299 | self.shell.exit_now = True |
|
2310 | 2300 | |
|
2311 | 2301 | #...................................................................... |
|
2312 | 2302 | # Functions to implement unix shell-type things |
|
2313 | 2303 | |
|
2314 | 2304 | def magic_alias(self, parameter_s = ''): |
|
2315 | 2305 | """Define an alias for a system command. |
|
2316 | 2306 | |
|
2317 | 2307 | '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd' |
|
2318 | 2308 | |
|
2319 | 2309 | Then, typing 'alias_name params' will execute the system command 'cmd |
|
2320 | 2310 | params' (from your underlying operating system). |
|
2321 | 2311 | |
|
2322 | 2312 | Aliases have lower precedence than magic functions and Python normal |
|
2323 | 2313 | variables, so if 'foo' is both a Python variable and an alias, the |
|
2324 | 2314 | alias can not be executed until 'del foo' removes the Python variable. |
|
2325 | 2315 | |
|
2326 | 2316 | You can use the %l specifier in an alias definition to represent the |
|
2327 | 2317 | whole line when the alias is called. For example: |
|
2328 | 2318 | |
|
2329 | 2319 | In [2]: alias all echo "Input in brackets: <%l>"\\ |
|
2330 | 2320 | In [3]: all hello world\\ |
|
2331 | 2321 | Input in brackets: <hello world> |
|
2332 | 2322 | |
|
2333 | 2323 | You can also define aliases with parameters using %s specifiers (one |
|
2334 | 2324 | per parameter): |
|
2335 | 2325 | |
|
2336 | 2326 | In [1]: alias parts echo first %s second %s\\ |
|
2337 | 2327 | In [2]: %parts A B\\ |
|
2338 | 2328 | first A second B\\ |
|
2339 | 2329 | In [3]: %parts A\\ |
|
2340 | 2330 | Incorrect number of arguments: 2 expected.\\ |
|
2341 | 2331 | parts is an alias to: 'echo first %s second %s' |
|
2342 | 2332 | |
|
2343 | 2333 | Note that %l and %s are mutually exclusive. You can only use one or |
|
2344 | 2334 | the other in your aliases. |
|
2345 | 2335 | |
|
2346 | 2336 | Aliases expand Python variables just like system calls using ! or !! |
|
2347 | 2337 | do: all expressions prefixed with '$' get expanded. For details of |
|
2348 | 2338 | the semantic rules, see PEP-215: |
|
2349 | 2339 | http://www.python.org/peps/pep-0215.html. This is the library used by |
|
2350 | 2340 | IPython for variable expansion. If you want to access a true shell |
|
2351 | 2341 | variable, an extra $ is necessary to prevent its expansion by IPython: |
|
2352 | 2342 | |
|
2353 | 2343 | In [6]: alias show echo\\ |
|
2354 | 2344 | In [7]: PATH='A Python string'\\ |
|
2355 | 2345 | In [8]: show $PATH\\ |
|
2356 | 2346 | A Python string\\ |
|
2357 | 2347 | In [9]: show $$PATH\\ |
|
2358 | 2348 | /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:... |
|
2359 | 2349 | |
|
2360 | 2350 | You can use the alias facility to acess all of $PATH. See the %rehash |
|
2361 | 2351 | and %rehashx functions, which automatically create aliases for the |
|
2362 | 2352 | contents of your $PATH. |
|
2363 | 2353 | |
|
2364 | 2354 | If called with no parameters, %alias prints the current alias table.""" |
|
2365 | 2355 | |
|
2366 | 2356 | par = parameter_s.strip() |
|
2367 | 2357 | if not par: |
|
2368 | 2358 | stored = self.db.get('stored_aliases', {} ) |
|
2369 | 2359 | atab = self.shell.alias_table |
|
2370 | 2360 | aliases = atab.keys() |
|
2371 | 2361 | aliases.sort() |
|
2372 | 2362 | res = [] |
|
2373 | 2363 | showlast = [] |
|
2374 | 2364 | for alias in aliases: |
|
2375 | 2365 | tgt = atab[alias][1] |
|
2376 | 2366 | # 'interesting' aliases |
|
2377 | 2367 | if (alias in stored or |
|
2378 | 2368 | alias != os.path.splitext(tgt)[0] or |
|
2379 | 2369 | ' ' in tgt): |
|
2380 | 2370 | showlast.append((alias, tgt)) |
|
2381 | 2371 | else: |
|
2382 | 2372 | res.append((alias, tgt )) |
|
2383 | 2373 | |
|
2384 | 2374 | # show most interesting aliases last |
|
2385 | 2375 | res.extend(showlast) |
|
2386 | 2376 | print "Total number of aliases:",len(aliases) |
|
2387 | 2377 | return res |
|
2388 | 2378 | try: |
|
2389 | 2379 | alias,cmd = par.split(None,1) |
|
2390 | 2380 | except: |
|
2391 | 2381 | print OInspect.getdoc(self.magic_alias) |
|
2392 | 2382 | else: |
|
2393 | 2383 | nargs = cmd.count('%s') |
|
2394 | 2384 | if nargs>0 and cmd.find('%l')>=0: |
|
2395 | 2385 | error('The %s and %l specifiers are mutually exclusive ' |
|
2396 | 2386 | 'in alias definitions.') |
|
2397 | 2387 | else: # all looks OK |
|
2398 | 2388 | self.shell.alias_table[alias] = (nargs,cmd) |
|
2399 | 2389 | self.shell.alias_table_validate(verbose=0) |
|
2400 | 2390 | # end magic_alias |
|
2401 | 2391 | |
|
2402 | 2392 | def magic_unalias(self, parameter_s = ''): |
|
2403 | 2393 | """Remove an alias""" |
|
2404 | 2394 | |
|
2405 | 2395 | aname = parameter_s.strip() |
|
2406 | 2396 | if aname in self.shell.alias_table: |
|
2407 | 2397 | del self.shell.alias_table[aname] |
|
2408 | 2398 | stored = self.db.get('stored_aliases', {} ) |
|
2409 | 2399 | if aname in stored: |
|
2410 | 2400 | print "Removing %stored alias",aname |
|
2411 | 2401 | del stored[aname] |
|
2412 | 2402 | self.db['stored_aliases'] = stored |
|
2413 | 2403 | |
|
2414 | 2404 | def magic_rehash(self, parameter_s = ''): |
|
2415 | 2405 | """Update the alias table with all entries in $PATH. |
|
2416 | 2406 | |
|
2417 | 2407 | This version does no checks on execute permissions or whether the |
|
2418 | 2408 | contents of $PATH are truly files (instead of directories or something |
|
2419 | 2409 | else). For such a safer (but slower) version, use %rehashx.""" |
|
2420 | 2410 | |
|
2421 | 2411 | # This function (and rehashx) manipulate the alias_table directly |
|
2422 | 2412 | # rather than calling magic_alias, for speed reasons. A rehash on a |
|
2423 | 2413 | # typical Linux box involves several thousand entries, so efficiency |
|
2424 | 2414 | # here is a top concern. |
|
2425 | 2415 | |
|
2426 | 2416 | path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep)) |
|
2427 | 2417 | alias_table = self.shell.alias_table |
|
2428 | 2418 | for pdir in path: |
|
2429 | 2419 | for ff in os.listdir(pdir): |
|
2430 | 2420 | # each entry in the alias table must be (N,name), where |
|
2431 | 2421 | # N is the number of positional arguments of the alias. |
|
2432 | 2422 | alias_table[ff] = (0,ff) |
|
2433 | 2423 | # Make sure the alias table doesn't contain keywords or builtins |
|
2434 | 2424 | self.shell.alias_table_validate() |
|
2435 | 2425 | # Call again init_auto_alias() so we get 'rm -i' and other modified |
|
2436 | 2426 | # aliases since %rehash will probably clobber them |
|
2437 | 2427 | self.shell.init_auto_alias() |
|
2438 | 2428 | |
|
2439 | 2429 | def magic_rehashx(self, parameter_s = ''): |
|
2440 | 2430 | """Update the alias table with all executable files in $PATH. |
|
2441 | 2431 | |
|
2442 | 2432 | This version explicitly checks that every entry in $PATH is a file |
|
2443 | 2433 | with execute access (os.X_OK), so it is much slower than %rehash. |
|
2444 | 2434 | |
|
2445 | 2435 | Under Windows, it checks executability as a match agains a |
|
2446 | 2436 | '|'-separated string of extensions, stored in the IPython config |
|
2447 | 2437 | variable win_exec_ext. This defaults to 'exe|com|bat'. """ |
|
2448 | 2438 | |
|
2449 | 2439 | path = [os.path.abspath(os.path.expanduser(p)) for p in |
|
2450 | 2440 | os.environ['PATH'].split(os.pathsep)] |
|
2451 | 2441 | path = filter(os.path.isdir,path) |
|
2452 | 2442 | |
|
2453 | 2443 | alias_table = self.shell.alias_table |
|
2454 | 2444 | syscmdlist = [] |
|
2455 | 2445 | if os.name == 'posix': |
|
2456 | 2446 | isexec = lambda fname:os.path.isfile(fname) and \ |
|
2457 | 2447 | os.access(fname,os.X_OK) |
|
2458 | 2448 | else: |
|
2459 | 2449 | |
|
2460 | 2450 | try: |
|
2461 | 2451 | winext = os.environ['pathext'].replace(';','|').replace('.','') |
|
2462 | 2452 | except KeyError: |
|
2463 | 2453 | winext = 'exe|com|bat|py' |
|
2464 | 2454 | if 'py' not in winext: |
|
2465 | 2455 | winext += '|py' |
|
2466 | 2456 | execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE) |
|
2467 | 2457 | isexec = lambda fname:os.path.isfile(fname) and execre.match(fname) |
|
2468 | 2458 | savedir = os.getcwd() |
|
2469 | 2459 | try: |
|
2470 | 2460 | # write the whole loop for posix/Windows so we don't have an if in |
|
2471 | 2461 | # the innermost part |
|
2472 | 2462 | if os.name == 'posix': |
|
2473 | 2463 | for pdir in path: |
|
2474 | 2464 | os.chdir(pdir) |
|
2475 | 2465 | for ff in os.listdir(pdir): |
|
2476 | 2466 | if isexec(ff) and ff not in self.shell.no_alias: |
|
2477 | 2467 | # each entry in the alias table must be (N,name), |
|
2478 | 2468 | # where N is the number of positional arguments of the |
|
2479 | 2469 | # alias. |
|
2480 | 2470 | alias_table[ff] = (0,ff) |
|
2481 | 2471 | syscmdlist.append(ff) |
|
2482 | 2472 | else: |
|
2483 | 2473 | for pdir in path: |
|
2484 | 2474 | os.chdir(pdir) |
|
2485 | 2475 | for ff in os.listdir(pdir): |
|
2486 | 2476 | if isexec(ff) and os.path.splitext(ff)[0] not in self.shell.no_alias: |
|
2487 | 2477 | alias_table[execre.sub(r'\1',ff)] = (0,ff) |
|
2488 | 2478 | syscmdlist.append(ff) |
|
2489 | 2479 | # Make sure the alias table doesn't contain keywords or builtins |
|
2490 | 2480 | self.shell.alias_table_validate() |
|
2491 | 2481 | # Call again init_auto_alias() so we get 'rm -i' and other |
|
2492 | 2482 | # modified aliases since %rehashx will probably clobber them |
|
2493 | 2483 | self.shell.init_auto_alias() |
|
2494 | 2484 | db = self.getapi().db |
|
2495 | 2485 | db['syscmdlist'] = syscmdlist |
|
2496 | 2486 | finally: |
|
2497 | 2487 | os.chdir(savedir) |
|
2498 | 2488 | |
|
2499 | 2489 | def magic_pwd(self, parameter_s = ''): |
|
2500 | 2490 | """Return the current working directory path.""" |
|
2501 | 2491 | return os.getcwd() |
|
2502 | 2492 | |
|
2503 | 2493 | def magic_cd(self, parameter_s=''): |
|
2504 | 2494 | """Change the current working directory. |
|
2505 | 2495 | |
|
2506 | 2496 | This command automatically maintains an internal list of directories |
|
2507 | 2497 | you visit during your IPython session, in the variable _dh. The |
|
2508 | 2498 | command %dhist shows this history nicely formatted. |
|
2509 | 2499 | |
|
2510 | 2500 | Usage: |
|
2511 | 2501 | |
|
2512 | 2502 | cd 'dir': changes to directory 'dir'. |
|
2513 | 2503 | |
|
2514 | 2504 | cd -: changes to the last visited directory. |
|
2515 | 2505 | |
|
2516 | 2506 | cd -<n>: changes to the n-th directory in the directory history. |
|
2517 | 2507 | |
|
2518 | 2508 | cd -b <bookmark_name>: jump to a bookmark set by %bookmark |
|
2519 | 2509 | (note: cd <bookmark_name> is enough if there is no |
|
2520 | 2510 | directory <bookmark_name>, but a bookmark with the name exists.) |
|
2521 | 2511 | |
|
2522 | 2512 | Options: |
|
2523 | 2513 | |
|
2524 | 2514 | -q: quiet. Do not print the working directory after the cd command is |
|
2525 | 2515 | executed. By default IPython's cd command does print this directory, |
|
2526 | 2516 | since the default prompts do not display path information. |
|
2527 | 2517 | |
|
2528 | 2518 | Note that !cd doesn't work for this purpose because the shell where |
|
2529 | 2519 | !command runs is immediately discarded after executing 'command'.""" |
|
2530 | 2520 | |
|
2531 | 2521 | parameter_s = parameter_s.strip() |
|
2532 | 2522 | #bkms = self.shell.persist.get("bookmarks",{}) |
|
2533 | 2523 | |
|
2534 | 2524 | numcd = re.match(r'(-)(\d+)$',parameter_s) |
|
2535 | 2525 | # jump in directory history by number |
|
2536 | 2526 | if numcd: |
|
2537 | 2527 | nn = int(numcd.group(2)) |
|
2538 | 2528 | try: |
|
2539 | 2529 | ps = self.shell.user_ns['_dh'][nn] |
|
2540 | 2530 | except IndexError: |
|
2541 | 2531 | print 'The requested directory does not exist in history.' |
|
2542 | 2532 | return |
|
2543 | 2533 | else: |
|
2544 | 2534 | opts = {} |
|
2545 | 2535 | else: |
|
2546 | 2536 | #turn all non-space-escaping backslashes to slashes, |
|
2547 | 2537 | # for c:\windows\directory\names\ |
|
2548 | 2538 | parameter_s = re.sub(r'\\(?! )','/', parameter_s) |
|
2549 | 2539 | opts,ps = self.parse_options(parameter_s,'qb',mode='string') |
|
2550 | 2540 | # jump to previous |
|
2551 | 2541 | if ps == '-': |
|
2552 | 2542 | try: |
|
2553 | 2543 | ps = self.shell.user_ns['_dh'][-2] |
|
2554 | 2544 | except IndexError: |
|
2555 | 2545 | print 'No previous directory to change to.' |
|
2556 | 2546 | return |
|
2557 | 2547 | # jump to bookmark if needed |
|
2558 | 2548 | else: |
|
2559 | 2549 | if not os.path.isdir(ps) or opts.has_key('b'): |
|
2560 | 2550 | bkms = self.db.get('bookmarks', {}) |
|
2561 | 2551 | |
|
2562 | 2552 | if bkms.has_key(ps): |
|
2563 | 2553 | target = bkms[ps] |
|
2564 | 2554 | print '(bookmark:%s) -> %s' % (ps,target) |
|
2565 | 2555 | ps = target |
|
2566 | 2556 | else: |
|
2567 | 2557 | if opts.has_key('b'): |
|
2568 | 2558 | error("Bookmark '%s' not found. " |
|
2569 | 2559 | "Use '%%bookmark -l' to see your bookmarks." % ps) |
|
2570 | 2560 | return |
|
2571 | 2561 | |
|
2572 | 2562 | # at this point ps should point to the target dir |
|
2573 | 2563 | if ps: |
|
2574 | 2564 | try: |
|
2575 | 2565 | os.chdir(os.path.expanduser(ps)) |
|
2576 | 2566 | ttitle = ("IPy:" + ( |
|
2577 | 2567 | os.getcwd() == '/' and '/' or os.path.basename(os.getcwd()))) |
|
2578 | 2568 | platutils.set_term_title(ttitle) |
|
2579 | 2569 | except OSError: |
|
2580 | 2570 | print sys.exc_info()[1] |
|
2581 | 2571 | else: |
|
2582 | 2572 | self.shell.user_ns['_dh'].append(os.getcwd()) |
|
2583 | 2573 | else: |
|
2584 | 2574 | os.chdir(self.shell.home_dir) |
|
2585 | 2575 | platutils.set_term_title("IPy:~") |
|
2586 | 2576 | self.shell.user_ns['_dh'].append(os.getcwd()) |
|
2587 | 2577 | if not 'q' in opts: |
|
2588 | 2578 | print self.shell.user_ns['_dh'][-1] |
|
2589 | 2579 | |
|
2590 | 2580 | def magic_dhist(self, parameter_s=''): |
|
2591 | 2581 | """Print your history of visited directories. |
|
2592 | 2582 | |
|
2593 | 2583 | %dhist -> print full history\\ |
|
2594 | 2584 | %dhist n -> print last n entries only\\ |
|
2595 | 2585 | %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\ |
|
2596 | 2586 | |
|
2597 | 2587 | This history is automatically maintained by the %cd command, and |
|
2598 | 2588 | always available as the global list variable _dh. You can use %cd -<n> |
|
2599 | 2589 | to go to directory number <n>.""" |
|
2600 | 2590 | |
|
2601 | 2591 | dh = self.shell.user_ns['_dh'] |
|
2602 | 2592 | if parameter_s: |
|
2603 | 2593 | try: |
|
2604 | 2594 | args = map(int,parameter_s.split()) |
|
2605 | 2595 | except: |
|
2606 | 2596 | self.arg_err(Magic.magic_dhist) |
|
2607 | 2597 | return |
|
2608 | 2598 | if len(args) == 1: |
|
2609 | 2599 | ini,fin = max(len(dh)-(args[0]),0),len(dh) |
|
2610 | 2600 | elif len(args) == 2: |
|
2611 | 2601 | ini,fin = args |
|
2612 | 2602 | else: |
|
2613 | 2603 | self.arg_err(Magic.magic_dhist) |
|
2614 | 2604 | return |
|
2615 | 2605 | else: |
|
2616 | 2606 | ini,fin = 0,len(dh) |
|
2617 | 2607 | nlprint(dh, |
|
2618 | 2608 | header = 'Directory history (kept in _dh)', |
|
2619 | 2609 | start=ini,stop=fin) |
|
2620 | 2610 | |
|
2621 | 2611 | def magic_env(self, parameter_s=''): |
|
2622 | 2612 | """List environment variables.""" |
|
2623 | 2613 | |
|
2624 | 2614 | return os.environ.data |
|
2625 | 2615 | |
|
2626 | 2616 | def magic_pushd(self, parameter_s=''): |
|
2627 | 2617 | """Place the current dir on stack and change directory. |
|
2628 | 2618 | |
|
2629 | 2619 | Usage:\\ |
|
2630 | 2620 | %pushd ['dirname'] |
|
2631 | 2621 | |
|
2632 | 2622 | %pushd with no arguments does a %pushd to your home directory. |
|
2633 | 2623 | """ |
|
2634 | 2624 | if parameter_s == '': parameter_s = '~' |
|
2635 | 2625 | dir_s = self.shell.dir_stack |
|
2636 | 2626 | if len(dir_s)>0 and os.path.expanduser(parameter_s) != \ |
|
2637 | 2627 | os.path.expanduser(self.shell.dir_stack[0]): |
|
2638 | 2628 | try: |
|
2639 | 2629 | self.magic_cd(parameter_s) |
|
2640 | 2630 | dir_s.insert(0,os.getcwd().replace(self.home_dir,'~')) |
|
2641 | 2631 | self.magic_dirs() |
|
2642 | 2632 | except: |
|
2643 | 2633 | print 'Invalid directory' |
|
2644 | 2634 | else: |
|
2645 | 2635 | print 'You are already there!' |
|
2646 | 2636 | |
|
2647 | 2637 | def magic_popd(self, parameter_s=''): |
|
2648 | 2638 | """Change to directory popped off the top of the stack. |
|
2649 | 2639 | """ |
|
2650 | 2640 | if len (self.shell.dir_stack) > 1: |
|
2651 | 2641 | self.shell.dir_stack.pop(0) |
|
2652 | 2642 | self.magic_cd(self.shell.dir_stack[0]) |
|
2653 | 2643 | print self.shell.dir_stack[0] |
|
2654 | 2644 | else: |
|
2655 | 2645 | print "You can't remove the starting directory from the stack:",\ |
|
2656 | 2646 | self.shell.dir_stack |
|
2657 | 2647 | |
|
2658 | 2648 | def magic_dirs(self, parameter_s=''): |
|
2659 | 2649 | """Return the current directory stack.""" |
|
2660 | 2650 | |
|
2661 | 2651 | return self.shell.dir_stack[:] |
|
2662 | 2652 | |
|
2663 | 2653 | def magic_sc(self, parameter_s=''): |
|
2664 | 2654 | """Shell capture - execute a shell command and capture its output. |
|
2665 | 2655 | |
|
2666 | 2656 | DEPRECATED. Suboptimal, retained for backwards compatibility. |
|
2667 | 2657 | |
|
2668 | 2658 | You should use the form 'var = !command' instead. Example: |
|
2669 | 2659 | |
|
2670 | 2660 | "%sc -l myfiles = ls ~" should now be written as |
|
2671 | 2661 | |
|
2672 | 2662 | "myfiles = !ls ~" |
|
2673 | 2663 | |
|
2674 | 2664 | myfiles.s, myfiles.l and myfiles.n still apply as documented |
|
2675 | 2665 | below. |
|
2676 | 2666 | |
|
2677 | 2667 | -- |
|
2678 | 2668 | %sc [options] varname=command |
|
2679 | 2669 | |
|
2680 | 2670 | IPython will run the given command using commands.getoutput(), and |
|
2681 | 2671 | will then update the user's interactive namespace with a variable |
|
2682 | 2672 | called varname, containing the value of the call. Your command can |
|
2683 | 2673 | contain shell wildcards, pipes, etc. |
|
2684 | 2674 | |
|
2685 | 2675 | The '=' sign in the syntax is mandatory, and the variable name you |
|
2686 | 2676 | supply must follow Python's standard conventions for valid names. |
|
2687 | 2677 | |
|
2688 | 2678 | (A special format without variable name exists for internal use) |
|
2689 | 2679 | |
|
2690 | 2680 | Options: |
|
2691 | 2681 | |
|
2692 | 2682 | -l: list output. Split the output on newlines into a list before |
|
2693 | 2683 | assigning it to the given variable. By default the output is stored |
|
2694 | 2684 | as a single string. |
|
2695 | 2685 | |
|
2696 | 2686 | -v: verbose. Print the contents of the variable. |
|
2697 | 2687 | |
|
2698 | 2688 | In most cases you should not need to split as a list, because the |
|
2699 | 2689 | returned value is a special type of string which can automatically |
|
2700 | 2690 | provide its contents either as a list (split on newlines) or as a |
|
2701 | 2691 | space-separated string. These are convenient, respectively, either |
|
2702 | 2692 | for sequential processing or to be passed to a shell command. |
|
2703 | 2693 | |
|
2704 | 2694 | For example: |
|
2705 | 2695 | |
|
2706 | 2696 | # Capture into variable a |
|
2707 | 2697 | In [9]: sc a=ls *py |
|
2708 | 2698 | |
|
2709 | 2699 | # a is a string with embedded newlines |
|
2710 | 2700 | In [10]: a |
|
2711 | 2701 | Out[10]: 'setup.py\nwin32_manual_post_install.py' |
|
2712 | 2702 | |
|
2713 | 2703 | # which can be seen as a list: |
|
2714 | 2704 | In [11]: a.l |
|
2715 | 2705 | Out[11]: ['setup.py', 'win32_manual_post_install.py'] |
|
2716 | 2706 | |
|
2717 | 2707 | # or as a whitespace-separated string: |
|
2718 | 2708 | In [12]: a.s |
|
2719 | 2709 | Out[12]: 'setup.py win32_manual_post_install.py' |
|
2720 | 2710 | |
|
2721 | 2711 | # a.s is useful to pass as a single command line: |
|
2722 | 2712 | In [13]: !wc -l $a.s |
|
2723 | 2713 | 146 setup.py |
|
2724 | 2714 | 130 win32_manual_post_install.py |
|
2725 | 2715 | 276 total |
|
2726 | 2716 | |
|
2727 | 2717 | # while the list form is useful to loop over: |
|
2728 | 2718 | In [14]: for f in a.l: |
|
2729 | 2719 | ....: !wc -l $f |
|
2730 | 2720 | ....: |
|
2731 | 2721 | 146 setup.py |
|
2732 | 2722 | 130 win32_manual_post_install.py |
|
2733 | 2723 | |
|
2734 | 2724 | Similiarly, the lists returned by the -l option are also special, in |
|
2735 | 2725 | the sense that you can equally invoke the .s attribute on them to |
|
2736 | 2726 | automatically get a whitespace-separated string from their contents: |
|
2737 | 2727 | |
|
2738 | 2728 | In [1]: sc -l b=ls *py |
|
2739 | 2729 | |
|
2740 | 2730 | In [2]: b |
|
2741 | 2731 | Out[2]: ['setup.py', 'win32_manual_post_install.py'] |
|
2742 | 2732 | |
|
2743 | 2733 | In [3]: b.s |
|
2744 | 2734 | Out[3]: 'setup.py win32_manual_post_install.py' |
|
2745 | 2735 | |
|
2746 | 2736 | In summary, both the lists and strings used for ouptut capture have |
|
2747 | 2737 | the following special attributes: |
|
2748 | 2738 | |
|
2749 | 2739 | .l (or .list) : value as list. |
|
2750 | 2740 | .n (or .nlstr): value as newline-separated string. |
|
2751 | 2741 | .s (or .spstr): value as space-separated string. |
|
2752 | 2742 | """ |
|
2753 | 2743 | |
|
2754 | 2744 | opts,args = self.parse_options(parameter_s,'lv') |
|
2755 | 2745 | # Try to get a variable name and command to run |
|
2756 | 2746 | try: |
|
2757 | 2747 | # the variable name must be obtained from the parse_options |
|
2758 | 2748 | # output, which uses shlex.split to strip options out. |
|
2759 | 2749 | var,_ = args.split('=',1) |
|
2760 | 2750 | var = var.strip() |
|
2761 | 2751 | # But the the command has to be extracted from the original input |
|
2762 | 2752 | # parameter_s, not on what parse_options returns, to avoid the |
|
2763 | 2753 | # quote stripping which shlex.split performs on it. |
|
2764 | 2754 | _,cmd = parameter_s.split('=',1) |
|
2765 | 2755 | except ValueError: |
|
2766 | 2756 | var,cmd = '','' |
|
2767 | 2757 | # If all looks ok, proceed |
|
2768 | 2758 | out,err = self.shell.getoutputerror(cmd) |
|
2769 | 2759 | if err: |
|
2770 | 2760 | print >> Term.cerr,err |
|
2771 | 2761 | if opts.has_key('l'): |
|
2772 | 2762 | out = SList(out.split('\n')) |
|
2773 | 2763 | else: |
|
2774 | 2764 | out = LSString(out) |
|
2775 | 2765 | if opts.has_key('v'): |
|
2776 | 2766 | print '%s ==\n%s' % (var,pformat(out)) |
|
2777 | 2767 | if var: |
|
2778 | 2768 | self.shell.user_ns.update({var:out}) |
|
2779 | 2769 | else: |
|
2780 | 2770 | return out |
|
2781 | 2771 | |
|
2782 | 2772 | def magic_sx(self, parameter_s=''): |
|
2783 | 2773 | """Shell execute - run a shell command and capture its output. |
|
2784 | 2774 | |
|
2785 | 2775 | %sx command |
|
2786 | 2776 | |
|
2787 | 2777 | IPython will run the given command using commands.getoutput(), and |
|
2788 | 2778 | return the result formatted as a list (split on '\\n'). Since the |
|
2789 | 2779 | output is _returned_, it will be stored in ipython's regular output |
|
2790 | 2780 | cache Out[N] and in the '_N' automatic variables. |
|
2791 | 2781 | |
|
2792 | 2782 | Notes: |
|
2793 | 2783 | |
|
2794 | 2784 | 1) If an input line begins with '!!', then %sx is automatically |
|
2795 | 2785 | invoked. That is, while: |
|
2796 | 2786 | !ls |
|
2797 | 2787 | causes ipython to simply issue system('ls'), typing |
|
2798 | 2788 | !!ls |
|
2799 | 2789 | is a shorthand equivalent to: |
|
2800 | 2790 | %sx ls |
|
2801 | 2791 | |
|
2802 | 2792 | 2) %sx differs from %sc in that %sx automatically splits into a list, |
|
2803 | 2793 | like '%sc -l'. The reason for this is to make it as easy as possible |
|
2804 | 2794 | to process line-oriented shell output via further python commands. |
|
2805 | 2795 | %sc is meant to provide much finer control, but requires more |
|
2806 | 2796 | typing. |
|
2807 | 2797 | |
|
2808 | 2798 | 3) Just like %sc -l, this is a list with special attributes: |
|
2809 | 2799 | |
|
2810 | 2800 | .l (or .list) : value as list. |
|
2811 | 2801 | .n (or .nlstr): value as newline-separated string. |
|
2812 | 2802 | .s (or .spstr): value as whitespace-separated string. |
|
2813 | 2803 | |
|
2814 | 2804 | This is very useful when trying to use such lists as arguments to |
|
2815 | 2805 | system commands.""" |
|
2816 | 2806 | |
|
2817 | 2807 | if parameter_s: |
|
2818 | 2808 | out,err = self.shell.getoutputerror(parameter_s) |
|
2819 | 2809 | if err: |
|
2820 | 2810 | print >> Term.cerr,err |
|
2821 | 2811 | return SList(out.split('\n')) |
|
2822 | 2812 | |
|
2823 | 2813 | def magic_bg(self, parameter_s=''): |
|
2824 | 2814 | """Run a job in the background, in a separate thread. |
|
2825 | 2815 | |
|
2826 | 2816 | For example, |
|
2827 | 2817 | |
|
2828 | 2818 | %bg myfunc(x,y,z=1) |
|
2829 | 2819 | |
|
2830 | 2820 | will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the |
|
2831 | 2821 | execution starts, a message will be printed indicating the job |
|
2832 | 2822 | number. If your job number is 5, you can use |
|
2833 | 2823 | |
|
2834 | 2824 | myvar = jobs.result(5) or myvar = jobs[5].result |
|
2835 | 2825 | |
|
2836 | 2826 | to assign this result to variable 'myvar'. |
|
2837 | 2827 | |
|
2838 | 2828 | IPython has a job manager, accessible via the 'jobs' object. You can |
|
2839 | 2829 | type jobs? to get more information about it, and use jobs.<TAB> to see |
|
2840 | 2830 | its attributes. All attributes not starting with an underscore are |
|
2841 | 2831 | meant for public use. |
|
2842 | 2832 | |
|
2843 | 2833 | In particular, look at the jobs.new() method, which is used to create |
|
2844 | 2834 | new jobs. This magic %bg function is just a convenience wrapper |
|
2845 | 2835 | around jobs.new(), for expression-based jobs. If you want to create a |
|
2846 | 2836 | new job with an explicit function object and arguments, you must call |
|
2847 | 2837 | jobs.new() directly. |
|
2848 | 2838 | |
|
2849 | 2839 | The jobs.new docstring also describes in detail several important |
|
2850 | 2840 | caveats associated with a thread-based model for background job |
|
2851 | 2841 | execution. Type jobs.new? for details. |
|
2852 | 2842 | |
|
2853 | 2843 | You can check the status of all jobs with jobs.status(). |
|
2854 | 2844 | |
|
2855 | 2845 | The jobs variable is set by IPython into the Python builtin namespace. |
|
2856 | 2846 | If you ever declare a variable named 'jobs', you will shadow this |
|
2857 | 2847 | name. You can either delete your global jobs variable to regain |
|
2858 | 2848 | access to the job manager, or make a new name and assign it manually |
|
2859 | 2849 | to the manager (stored in IPython's namespace). For example, to |
|
2860 | 2850 | assign the job manager to the Jobs name, use: |
|
2861 | 2851 | |
|
2862 | 2852 | Jobs = __builtins__.jobs""" |
|
2863 | 2853 | |
|
2864 | 2854 | self.shell.jobs.new(parameter_s,self.shell.user_ns) |
|
2865 | 2855 | |
|
2866 | 2856 | |
|
2867 | 2857 | def magic_bookmark(self, parameter_s=''): |
|
2868 | 2858 | """Manage IPython's bookmark system. |
|
2869 | 2859 | |
|
2870 | 2860 | %bookmark <name> - set bookmark to current dir |
|
2871 | 2861 | %bookmark <name> <dir> - set bookmark to <dir> |
|
2872 | 2862 | %bookmark -l - list all bookmarks |
|
2873 | 2863 | %bookmark -d <name> - remove bookmark |
|
2874 | 2864 | %bookmark -r - remove all bookmarks |
|
2875 | 2865 | |
|
2876 | 2866 | You can later on access a bookmarked folder with: |
|
2877 | 2867 | %cd -b <name> |
|
2878 | 2868 | or simply '%cd <name>' if there is no directory called <name> AND |
|
2879 | 2869 | there is such a bookmark defined. |
|
2880 | 2870 | |
|
2881 | 2871 | Your bookmarks persist through IPython sessions, but they are |
|
2882 | 2872 | associated with each profile.""" |
|
2883 | 2873 | |
|
2884 | 2874 | opts,args = self.parse_options(parameter_s,'drl',mode='list') |
|
2885 | 2875 | if len(args) > 2: |
|
2886 | 2876 | error('You can only give at most two arguments') |
|
2887 | 2877 | return |
|
2888 | 2878 | |
|
2889 | 2879 | bkms = self.db.get('bookmarks',{}) |
|
2890 | 2880 | |
|
2891 | 2881 | if opts.has_key('d'): |
|
2892 | 2882 | try: |
|
2893 | 2883 | todel = args[0] |
|
2894 | 2884 | except IndexError: |
|
2895 | 2885 | error('You must provide a bookmark to delete') |
|
2896 | 2886 | else: |
|
2897 | 2887 | try: |
|
2898 | 2888 | del bkms[todel] |
|
2899 | 2889 | except: |
|
2900 | 2890 | error("Can't delete bookmark '%s'" % todel) |
|
2901 | 2891 | elif opts.has_key('r'): |
|
2902 | 2892 | bkms = {} |
|
2903 | 2893 | elif opts.has_key('l'): |
|
2904 | 2894 | bks = bkms.keys() |
|
2905 | 2895 | bks.sort() |
|
2906 | 2896 | if bks: |
|
2907 | 2897 | size = max(map(len,bks)) |
|
2908 | 2898 | else: |
|
2909 | 2899 | size = 0 |
|
2910 | 2900 | fmt = '%-'+str(size)+'s -> %s' |
|
2911 | 2901 | print 'Current bookmarks:' |
|
2912 | 2902 | for bk in bks: |
|
2913 | 2903 | print fmt % (bk,bkms[bk]) |
|
2914 | 2904 | else: |
|
2915 | 2905 | if not args: |
|
2916 | 2906 | error("You must specify the bookmark name") |
|
2917 | 2907 | elif len(args)==1: |
|
2918 | 2908 | bkms[args[0]] = os.getcwd() |
|
2919 | 2909 | elif len(args)==2: |
|
2920 | 2910 | bkms[args[0]] = args[1] |
|
2921 | 2911 | self.db['bookmarks'] = bkms |
|
2922 | 2912 | |
|
2923 | 2913 | def magic_pycat(self, parameter_s=''): |
|
2924 | 2914 | """Show a syntax-highlighted file through a pager. |
|
2925 | 2915 | |
|
2926 | 2916 | This magic is similar to the cat utility, but it will assume the file |
|
2927 | 2917 | to be Python source and will show it with syntax highlighting. """ |
|
2928 | 2918 | |
|
2929 | 2919 | try: |
|
2930 | 2920 | filename = get_py_filename(parameter_s) |
|
2931 | 2921 | cont = file_read(filename) |
|
2932 | 2922 | except IOError: |
|
2933 | 2923 | try: |
|
2934 | 2924 | cont = eval(parameter_s,self.user_ns) |
|
2935 | 2925 | except NameError: |
|
2936 | 2926 | cont = None |
|
2937 | 2927 | if cont is None: |
|
2938 | 2928 | print "Error: no such file or variable" |
|
2939 | 2929 | return |
|
2940 | 2930 | |
|
2941 | 2931 | page(self.shell.pycolorize(cont), |
|
2942 | 2932 | screen_lines=self.shell.rc.screen_length) |
|
2943 | 2933 | |
|
2944 | 2934 | def magic_cpaste(self, parameter_s=''): |
|
2945 | 2935 | """Allows you to paste & execute a pre-formatted code block from clipboard |
|
2946 | 2936 | |
|
2947 | 2937 | You must terminate the block with '--' (two minus-signs) alone on the |
|
2948 | 2938 | line. You can also provide your own sentinel with '%paste -s %%' ('%%' |
|
2949 | 2939 | is the new sentinel for this operation) |
|
2950 | 2940 | |
|
2951 | 2941 | The block is dedented prior to execution to enable execution of |
|
2952 | 2942 | method definitions. '>' characters at the beginning of a line is |
|
2953 | 2943 | ignored, to allow pasting directly from e-mails. The executed block |
|
2954 | 2944 | is also assigned to variable named 'pasted_block' for later editing |
|
2955 | 2945 | with '%edit pasted_block'. |
|
2956 | 2946 | |
|
2957 | 2947 | You can also pass a variable name as an argument, e.g. '%cpaste foo'. |
|
2958 | 2948 | This assigns the pasted block to variable 'foo' as string, without |
|
2959 | 2949 | dedenting or executing it. |
|
2960 | 2950 | |
|
2961 | 2951 | Do not be alarmed by garbled output on Windows (it's a readline bug). |
|
2962 | 2952 | Just press enter and type -- (and press enter again) and the block |
|
2963 | 2953 | will be what was just pasted. |
|
2964 | 2954 | |
|
2965 | 2955 | IPython statements (magics, shell escapes) are not supported (yet). |
|
2966 | 2956 | """ |
|
2967 | 2957 | opts,args = self.parse_options(parameter_s,'s:',mode='string') |
|
2968 | 2958 | par = args.strip() |
|
2969 | 2959 | sentinel = opts.get('s','--') |
|
2970 | 2960 | |
|
2971 | 2961 | from IPython import iplib |
|
2972 | 2962 | lines = [] |
|
2973 | 2963 | print "Pasting code; enter '%s' alone on the line to stop." % sentinel |
|
2974 | 2964 | while 1: |
|
2975 | 2965 | l = iplib.raw_input_original(':') |
|
2976 | 2966 | if l ==sentinel: |
|
2977 | 2967 | break |
|
2978 | 2968 | lines.append(l.lstrip('>')) |
|
2979 | 2969 | block = "\n".join(lines) + '\n' |
|
2980 | 2970 | #print "block:\n",block |
|
2981 | 2971 | if not par: |
|
2982 | 2972 | b = textwrap.dedent(block) |
|
2983 | 2973 | exec b in self.user_ns |
|
2984 | 2974 | self.user_ns['pasted_block'] = b |
|
2985 | 2975 | else: |
|
2986 | 2976 | self.user_ns[par] = block |
|
2987 | 2977 | print "Block assigned to '%s'" % par |
|
2988 | 2978 | |
|
2989 | 2979 | def magic_quickref(self,arg): |
|
2990 | 2980 | """ Show a quick reference sheet """ |
|
2991 | 2981 | import IPython.usage |
|
2992 | 2982 | qr = IPython.usage.quick_reference + self.magic_magic('-brief') |
|
2993 | 2983 | |
|
2994 | 2984 | page(qr) |
|
2995 | 2985 | |
|
2996 | 2986 | def magic_upgrade(self,arg): |
|
2997 | 2987 | """ Upgrade your IPython installation |
|
2998 | 2988 | |
|
2999 | 2989 | This will copy the config files that don't yet exist in your |
|
3000 | 2990 | ipython dir from the system config dir. Use this after upgrading |
|
3001 | 2991 | IPython if you don't wish to delete your .ipython dir. |
|
3002 | 2992 | |
|
3003 | 2993 | Call with -nolegacy to get rid of ipythonrc* files (recommended for |
|
3004 | 2994 | new users) |
|
3005 | 2995 | |
|
3006 | 2996 | """ |
|
3007 | 2997 | ip = self.getapi() |
|
3008 | 2998 | ipinstallation = path(IPython.__file__).dirname() |
|
3009 | 2999 | upgrade_script = '%s "%s"' % (sys.executable,ipinstallation / 'upgrade_dir.py') |
|
3010 | 3000 | src_config = ipinstallation / 'UserConfig' |
|
3011 | 3001 | userdir = path(ip.options.ipythondir) |
|
3012 | 3002 | cmd = '%s "%s" "%s"' % (upgrade_script, src_config, userdir) |
|
3013 | 3003 | print ">",cmd |
|
3014 | 3004 | shell(cmd) |
|
3015 | 3005 | if arg == '-nolegacy': |
|
3016 | 3006 | legacy = userdir.files('ipythonrc*') |
|
3017 | 3007 | print "Nuking legacy files:",legacy |
|
3018 | 3008 | |
|
3019 | 3009 | [p.remove() for p in legacy] |
|
3020 | 3010 | suffix = (sys.platform == 'win32' and '.ini' or '') |
|
3021 | 3011 | (userdir / ('ipythonrc' + suffix)).write_text('# Empty, see ipy_user_conf.py\n') |
|
3022 | 3012 | |
|
3023 | 3013 | |
|
3024 | 3014 | # end Magic |
@@ -1,1707 +1,1719 b'' | |||
|
1 | 1 | # -*- coding: utf-8 -*- |
|
2 | 2 | """ |
|
3 | 3 | General purpose utilities. |
|
4 | 4 | |
|
5 | 5 | This is a grab-bag of stuff I find useful in most programs I write. Some of |
|
6 | 6 | these things are also convenient when working at the command line. |
|
7 | 7 | |
|
8 |
$Id: genutils.py 1 |
|
|
8 | $Id: genutils.py 1845 2006-10-27 20:35:47Z fptest $""" | |
|
9 | 9 | |
|
10 | 10 | #***************************************************************************** |
|
11 | 11 | # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu> |
|
12 | 12 | # |
|
13 | 13 | # Distributed under the terms of the BSD License. The full license is in |
|
14 | 14 | # the file COPYING, distributed as part of this software. |
|
15 | 15 | #***************************************************************************** |
|
16 | 16 | |
|
17 | 17 | from IPython import Release |
|
18 | 18 | __author__ = '%s <%s>' % Release.authors['Fernando'] |
|
19 | 19 | __license__ = Release.license |
|
20 | 20 | |
|
21 | 21 | #**************************************************************************** |
|
22 | 22 | # required modules from the Python standard library |
|
23 | 23 | import __main__ |
|
24 | 24 | import commands |
|
25 | 25 | import os |
|
26 | 26 | import re |
|
27 | import shlex | |
|
27 | 28 | import shutil |
|
28 | 29 | import sys |
|
29 | 30 | import tempfile |
|
30 | 31 | import time |
|
31 | 32 | import types |
|
32 | 33 | |
|
33 | 34 | # Other IPython utilities |
|
34 | 35 | from IPython.Itpl import Itpl,itpl,printpl |
|
35 | 36 | from IPython import DPyGetOpt |
|
36 | 37 | from path import path |
|
37 | 38 | if os.name == "nt": |
|
38 | 39 | from IPython.winconsole import get_console_size |
|
39 | 40 | |
|
40 | 41 | #**************************************************************************** |
|
41 | 42 | # Exceptions |
|
42 | 43 | class Error(Exception): |
|
43 | 44 | """Base class for exceptions in this module.""" |
|
44 | 45 | pass |
|
45 | 46 | |
|
46 | 47 | #---------------------------------------------------------------------------- |
|
47 | 48 | class IOStream: |
|
48 | 49 | def __init__(self,stream,fallback): |
|
49 | 50 | if not hasattr(stream,'write') or not hasattr(stream,'flush'): |
|
50 | 51 | stream = fallback |
|
51 | 52 | self.stream = stream |
|
52 | 53 | self._swrite = stream.write |
|
53 | 54 | self.flush = stream.flush |
|
54 | 55 | |
|
55 | 56 | def write(self,data): |
|
56 | 57 | try: |
|
57 | 58 | self._swrite(data) |
|
58 | 59 | except: |
|
59 | 60 | try: |
|
60 | 61 | # print handles some unicode issues which may trip a plain |
|
61 | 62 | # write() call. Attempt to emulate write() by using a |
|
62 | 63 | # trailing comma |
|
63 | 64 | print >> self.stream, data, |
|
64 | 65 | except: |
|
65 | 66 | # if we get here, something is seriously broken. |
|
66 | 67 | print >> sys.stderr, \ |
|
67 | 68 | 'ERROR - failed to write data to stream:', self.stream |
|
68 | 69 | |
|
69 | 70 | class IOTerm: |
|
70 | 71 | """ Term holds the file or file-like objects for handling I/O operations. |
|
71 | 72 | |
|
72 | 73 | These are normally just sys.stdin, sys.stdout and sys.stderr but for |
|
73 | 74 | Windows they can can replaced to allow editing the strings before they are |
|
74 | 75 | displayed.""" |
|
75 | 76 | |
|
76 | 77 | # In the future, having IPython channel all its I/O operations through |
|
77 | 78 | # this class will make it easier to embed it into other environments which |
|
78 | 79 | # are not a normal terminal (such as a GUI-based shell) |
|
79 | 80 | def __init__(self,cin=None,cout=None,cerr=None): |
|
80 | 81 | self.cin = IOStream(cin,sys.stdin) |
|
81 | 82 | self.cout = IOStream(cout,sys.stdout) |
|
82 | 83 | self.cerr = IOStream(cerr,sys.stderr) |
|
83 | 84 | |
|
84 | 85 | # Global variable to be used for all I/O |
|
85 | 86 | Term = IOTerm() |
|
86 | 87 | |
|
87 | 88 | import IPython.rlineimpl as readline |
|
88 | 89 | # Remake Term to use the readline i/o facilities |
|
89 | 90 | if sys.platform == 'win32' and readline.have_readline: |
|
90 | 91 | |
|
91 | 92 | Term = IOTerm(cout=readline._outputfile,cerr=readline._outputfile) |
|
92 | 93 | |
|
93 | 94 | |
|
94 | 95 | #**************************************************************************** |
|
95 | 96 | # Generic warning/error printer, used by everything else |
|
96 | 97 | def warn(msg,level=2,exit_val=1): |
|
97 | 98 | """Standard warning printer. Gives formatting consistency. |
|
98 | 99 | |
|
99 | 100 | Output is sent to Term.cerr (sys.stderr by default). |
|
100 | 101 | |
|
101 | 102 | Options: |
|
102 | 103 | |
|
103 | 104 | -level(2): allows finer control: |
|
104 | 105 | 0 -> Do nothing, dummy function. |
|
105 | 106 | 1 -> Print message. |
|
106 | 107 | 2 -> Print 'WARNING:' + message. (Default level). |
|
107 | 108 | 3 -> Print 'ERROR:' + message. |
|
108 | 109 | 4 -> Print 'FATAL ERROR:' + message and trigger a sys.exit(exit_val). |
|
109 | 110 | |
|
110 | 111 | -exit_val (1): exit value returned by sys.exit() for a level 4 |
|
111 | 112 | warning. Ignored for all other levels.""" |
|
112 | 113 | |
|
113 | 114 | if level>0: |
|
114 | 115 | header = ['','','WARNING: ','ERROR: ','FATAL ERROR: '] |
|
115 | 116 | print >> Term.cerr, '%s%s' % (header[level],msg) |
|
116 | 117 | if level == 4: |
|
117 | 118 | print >> Term.cerr,'Exiting.\n' |
|
118 | 119 | sys.exit(exit_val) |
|
119 | 120 | |
|
120 | 121 | def info(msg): |
|
121 | 122 | """Equivalent to warn(msg,level=1).""" |
|
122 | 123 | |
|
123 | 124 | warn(msg,level=1) |
|
124 | 125 | |
|
125 | 126 | def error(msg): |
|
126 | 127 | """Equivalent to warn(msg,level=3).""" |
|
127 | 128 | |
|
128 | 129 | warn(msg,level=3) |
|
129 | 130 | |
|
130 | 131 | def fatal(msg,exit_val=1): |
|
131 | 132 | """Equivalent to warn(msg,exit_val=exit_val,level=4).""" |
|
132 | 133 | |
|
133 | 134 | warn(msg,exit_val=exit_val,level=4) |
|
134 | 135 | |
|
135 | 136 | #--------------------------------------------------------------------------- |
|
136 | 137 | # Debugging routines |
|
137 | 138 | # |
|
138 | 139 | def debugx(expr,pre_msg=''): |
|
139 | 140 | """Print the value of an expression from the caller's frame. |
|
140 | 141 | |
|
141 | 142 | Takes an expression, evaluates it in the caller's frame and prints both |
|
142 | 143 | the given expression and the resulting value (as well as a debug mark |
|
143 | 144 | indicating the name of the calling function. The input must be of a form |
|
144 | 145 | suitable for eval(). |
|
145 | 146 | |
|
146 | 147 | An optional message can be passed, which will be prepended to the printed |
|
147 | 148 | expr->value pair.""" |
|
148 | 149 | |
|
149 | 150 | cf = sys._getframe(1) |
|
150 | 151 | print '[DBG:%s] %s%s -> %r' % (cf.f_code.co_name,pre_msg,expr, |
|
151 | 152 | eval(expr,cf.f_globals,cf.f_locals)) |
|
152 | 153 | |
|
153 | 154 | # deactivate it by uncommenting the following line, which makes it a no-op |
|
154 | 155 | #def debugx(expr,pre_msg=''): pass |
|
155 | 156 | |
|
156 | 157 | #---------------------------------------------------------------------------- |
|
157 | 158 | StringTypes = types.StringTypes |
|
158 | 159 | |
|
159 | 160 | # Basic timing functionality |
|
160 | 161 | |
|
161 | 162 | # If possible (Unix), use the resource module instead of time.clock() |
|
162 | 163 | try: |
|
163 | 164 | import resource |
|
164 | 165 | def clock(): |
|
165 | 166 | """clock() -> floating point number |
|
166 | 167 | |
|
167 | 168 | Return the CPU time in seconds (user time only, system time is |
|
168 | 169 | ignored) since the start of the process. This is done via a call to |
|
169 | 170 | resource.getrusage, so it avoids the wraparound problems in |
|
170 | 171 | time.clock().""" |
|
171 | 172 | |
|
172 | 173 | return resource.getrusage(resource.RUSAGE_SELF)[0] |
|
173 | 174 | |
|
174 | 175 | def clock2(): |
|
175 | 176 | """clock2() -> (t_user,t_system) |
|
176 | 177 | |
|
177 | 178 | Similar to clock(), but return a tuple of user/system times.""" |
|
178 | 179 | return resource.getrusage(resource.RUSAGE_SELF)[:2] |
|
179 | 180 | |
|
180 | 181 | except ImportError: |
|
181 | 182 | clock = time.clock |
|
182 | 183 | def clock2(): |
|
183 | 184 | """Under windows, system CPU time can't be measured. |
|
184 | 185 | |
|
185 | 186 | This just returns clock() and zero.""" |
|
186 | 187 | return time.clock(),0.0 |
|
187 | 188 | |
|
188 | 189 | def timings_out(reps,func,*args,**kw): |
|
189 | 190 | """timings_out(reps,func,*args,**kw) -> (t_total,t_per_call,output) |
|
190 | 191 | |
|
191 | 192 | Execute a function reps times, return a tuple with the elapsed total |
|
192 | 193 | CPU time in seconds, the time per call and the function's output. |
|
193 | 194 | |
|
194 | 195 | Under Unix, the return value is the sum of user+system time consumed by |
|
195 | 196 | the process, computed via the resource module. This prevents problems |
|
196 | 197 | related to the wraparound effect which the time.clock() function has. |
|
197 | 198 | |
|
198 | 199 | Under Windows the return value is in wall clock seconds. See the |
|
199 | 200 | documentation for the time module for more details.""" |
|
200 | 201 | |
|
201 | 202 | reps = int(reps) |
|
202 | 203 | assert reps >=1, 'reps must be >= 1' |
|
203 | 204 | if reps==1: |
|
204 | 205 | start = clock() |
|
205 | 206 | out = func(*args,**kw) |
|
206 | 207 | tot_time = clock()-start |
|
207 | 208 | else: |
|
208 | 209 | rng = xrange(reps-1) # the last time is executed separately to store output |
|
209 | 210 | start = clock() |
|
210 | 211 | for dummy in rng: func(*args,**kw) |
|
211 | 212 | out = func(*args,**kw) # one last time |
|
212 | 213 | tot_time = clock()-start |
|
213 | 214 | av_time = tot_time / reps |
|
214 | 215 | return tot_time,av_time,out |
|
215 | 216 | |
|
216 | 217 | def timings(reps,func,*args,**kw): |
|
217 | 218 | """timings(reps,func,*args,**kw) -> (t_total,t_per_call) |
|
218 | 219 | |
|
219 | 220 | Execute a function reps times, return a tuple with the elapsed total CPU |
|
220 | 221 | time in seconds and the time per call. These are just the first two values |
|
221 | 222 | in timings_out().""" |
|
222 | 223 | |
|
223 | 224 | return timings_out(reps,func,*args,**kw)[0:2] |
|
224 | 225 | |
|
225 | 226 | def timing(func,*args,**kw): |
|
226 | 227 | """timing(func,*args,**kw) -> t_total |
|
227 | 228 | |
|
228 | 229 | Execute a function once, return the elapsed total CPU time in |
|
229 | 230 | seconds. This is just the first value in timings_out().""" |
|
230 | 231 | |
|
231 | 232 | return timings_out(1,func,*args,**kw)[0] |
|
232 | 233 | |
|
233 | 234 | #**************************************************************************** |
|
234 | 235 | # file and system |
|
235 | 236 | |
|
237 | def arg_split(s,posix=False): | |
|
238 | """Split a command line's arguments in a shell-like manner. | |
|
239 | ||
|
240 | This is a modified version of the standard library's shlex.split() | |
|
241 | function, but with a default of posix=False for splitting, so that quotes | |
|
242 | in inputs are respected.""" | |
|
243 | ||
|
244 | lex = shlex.shlex(s, posix=posix) | |
|
245 | lex.whitespace_split = True | |
|
246 | return list(lex) | |
|
247 | ||
|
236 | 248 | def system(cmd,verbose=0,debug=0,header=''): |
|
237 | 249 | """Execute a system command, return its exit status. |
|
238 | 250 | |
|
239 | 251 | Options: |
|
240 | 252 | |
|
241 | 253 | - verbose (0): print the command to be executed. |
|
242 | 254 | |
|
243 | 255 | - debug (0): only print, do not actually execute. |
|
244 | 256 | |
|
245 | 257 | - header (''): Header to print on screen prior to the executed command (it |
|
246 | 258 | is only prepended to the command, no newlines are added). |
|
247 | 259 | |
|
248 | 260 | Note: a stateful version of this function is available through the |
|
249 | 261 | SystemExec class.""" |
|
250 | 262 | |
|
251 | 263 | stat = 0 |
|
252 | 264 | if verbose or debug: print header+cmd |
|
253 | 265 | sys.stdout.flush() |
|
254 | 266 | if not debug: stat = os.system(cmd) |
|
255 | 267 | return stat |
|
256 | 268 | |
|
257 | 269 | # This function is used by ipython in a lot of places to make system calls. |
|
258 | 270 | # We need it to be slightly different under win32, due to the vagaries of |
|
259 | 271 | # 'network shares'. A win32 override is below. |
|
260 | 272 | |
|
261 | 273 | def shell(cmd,verbose=0,debug=0,header=''): |
|
262 | 274 | """Execute a command in the system shell, always return None. |
|
263 | 275 | |
|
264 | 276 | Options: |
|
265 | 277 | |
|
266 | 278 | - verbose (0): print the command to be executed. |
|
267 | 279 | |
|
268 | 280 | - debug (0): only print, do not actually execute. |
|
269 | 281 | |
|
270 | 282 | - header (''): Header to print on screen prior to the executed command (it |
|
271 | 283 | is only prepended to the command, no newlines are added). |
|
272 | 284 | |
|
273 | 285 | Note: this is similar to genutils.system(), but it returns None so it can |
|
274 | 286 | be conveniently used in interactive loops without getting the return value |
|
275 | 287 | (typically 0) printed many times.""" |
|
276 | 288 | |
|
277 | 289 | stat = 0 |
|
278 | 290 | if verbose or debug: print header+cmd |
|
279 | 291 | # flush stdout so we don't mangle python's buffering |
|
280 | 292 | sys.stdout.flush() |
|
281 | 293 | if not debug: |
|
282 | 294 | os.system(cmd) |
|
283 | 295 | |
|
284 | 296 | # override shell() for win32 to deal with network shares |
|
285 | 297 | if os.name in ('nt','dos'): |
|
286 | 298 | |
|
287 | 299 | shell_ori = shell |
|
288 | 300 | |
|
289 | 301 | def shell(cmd,verbose=0,debug=0,header=''): |
|
290 | 302 | if os.getcwd().startswith(r"\\"): |
|
291 | 303 | path = os.getcwd() |
|
292 | 304 | # change to c drive (cannot be on UNC-share when issuing os.system, |
|
293 | 305 | # as cmd.exe cannot handle UNC addresses) |
|
294 | 306 | os.chdir("c:") |
|
295 | 307 | # issue pushd to the UNC-share and then run the command |
|
296 | 308 | try: |
|
297 | 309 | shell_ori('"pushd %s&&"'%path+cmd,verbose,debug,header) |
|
298 | 310 | finally: |
|
299 | 311 | os.chdir(path) |
|
300 | 312 | else: |
|
301 | 313 | shell_ori(cmd,verbose,debug,header) |
|
302 | 314 | |
|
303 | 315 | shell.__doc__ = shell_ori.__doc__ |
|
304 | 316 | |
|
305 | 317 | def getoutput(cmd,verbose=0,debug=0,header='',split=0): |
|
306 | 318 | """Dummy substitute for perl's backquotes. |
|
307 | 319 | |
|
308 | 320 | Executes a command and returns the output. |
|
309 | 321 | |
|
310 | 322 | Accepts the same arguments as system(), plus: |
|
311 | 323 | |
|
312 | 324 | - split(0): if true, the output is returned as a list split on newlines. |
|
313 | 325 | |
|
314 | 326 | Note: a stateful version of this function is available through the |
|
315 | 327 | SystemExec class. |
|
316 | 328 | |
|
317 | 329 | This is pretty much deprecated and rarely used, |
|
318 | 330 | genutils.getoutputerror may be what you need. |
|
319 | 331 | |
|
320 | 332 | """ |
|
321 | 333 | |
|
322 | 334 | if verbose or debug: print header+cmd |
|
323 | 335 | if not debug: |
|
324 | 336 | output = os.popen(cmd).read() |
|
325 | 337 | # stipping last \n is here for backwards compat. |
|
326 | 338 | if output.endswith('\n'): |
|
327 | 339 | output = output[:-1] |
|
328 | 340 | if split: |
|
329 | 341 | return output.split('\n') |
|
330 | 342 | else: |
|
331 | 343 | return output |
|
332 | 344 | |
|
333 | 345 | def getoutputerror(cmd,verbose=0,debug=0,header='',split=0): |
|
334 | 346 | """Return (standard output,standard error) of executing cmd in a shell. |
|
335 | 347 | |
|
336 | 348 | Accepts the same arguments as system(), plus: |
|
337 | 349 | |
|
338 | 350 | - split(0): if true, each of stdout/err is returned as a list split on |
|
339 | 351 | newlines. |
|
340 | 352 | |
|
341 | 353 | Note: a stateful version of this function is available through the |
|
342 | 354 | SystemExec class.""" |
|
343 | 355 | |
|
344 | 356 | if verbose or debug: print header+cmd |
|
345 | 357 | if not cmd: |
|
346 | 358 | if split: |
|
347 | 359 | return [],[] |
|
348 | 360 | else: |
|
349 | 361 | return '','' |
|
350 | 362 | if not debug: |
|
351 | 363 | pin,pout,perr = os.popen3(cmd) |
|
352 | 364 | tout = pout.read().rstrip() |
|
353 | 365 | terr = perr.read().rstrip() |
|
354 | 366 | pin.close() |
|
355 | 367 | pout.close() |
|
356 | 368 | perr.close() |
|
357 | 369 | if split: |
|
358 | 370 | return tout.split('\n'),terr.split('\n') |
|
359 | 371 | else: |
|
360 | 372 | return tout,terr |
|
361 | 373 | |
|
362 | 374 | # for compatibility with older naming conventions |
|
363 | 375 | xsys = system |
|
364 | 376 | bq = getoutput |
|
365 | 377 | |
|
366 | 378 | class SystemExec: |
|
367 | 379 | """Access the system and getoutput functions through a stateful interface. |
|
368 | 380 | |
|
369 | 381 | Note: here we refer to the system and getoutput functions from this |
|
370 | 382 | library, not the ones from the standard python library. |
|
371 | 383 | |
|
372 | 384 | This class offers the system and getoutput functions as methods, but the |
|
373 | 385 | verbose, debug and header parameters can be set for the instance (at |
|
374 | 386 | creation time or later) so that they don't need to be specified on each |
|
375 | 387 | call. |
|
376 | 388 | |
|
377 | 389 | For efficiency reasons, there's no way to override the parameters on a |
|
378 | 390 | per-call basis other than by setting instance attributes. If you need |
|
379 | 391 | local overrides, it's best to directly call system() or getoutput(). |
|
380 | 392 | |
|
381 | 393 | The following names are provided as alternate options: |
|
382 | 394 | - xsys: alias to system |
|
383 | 395 | - bq: alias to getoutput |
|
384 | 396 | |
|
385 | 397 | An instance can then be created as: |
|
386 | 398 | >>> sysexec = SystemExec(verbose=1,debug=0,header='Calling: ') |
|
387 | 399 | |
|
388 | 400 | And used as: |
|
389 | 401 | >>> sysexec.xsys('pwd') |
|
390 | 402 | >>> dirlist = sysexec.bq('ls -l') |
|
391 | 403 | """ |
|
392 | 404 | |
|
393 | 405 | def __init__(self,verbose=0,debug=0,header='',split=0): |
|
394 | 406 | """Specify the instance's values for verbose, debug and header.""" |
|
395 | 407 | setattr_list(self,'verbose debug header split') |
|
396 | 408 | |
|
397 | 409 | def system(self,cmd): |
|
398 | 410 | """Stateful interface to system(), with the same keyword parameters.""" |
|
399 | 411 | |
|
400 | 412 | system(cmd,self.verbose,self.debug,self.header) |
|
401 | 413 | |
|
402 | 414 | def shell(self,cmd): |
|
403 | 415 | """Stateful interface to shell(), with the same keyword parameters.""" |
|
404 | 416 | |
|
405 | 417 | shell(cmd,self.verbose,self.debug,self.header) |
|
406 | 418 | |
|
407 | 419 | xsys = system # alias |
|
408 | 420 | |
|
409 | 421 | def getoutput(self,cmd): |
|
410 | 422 | """Stateful interface to getoutput().""" |
|
411 | 423 | |
|
412 | 424 | return getoutput(cmd,self.verbose,self.debug,self.header,self.split) |
|
413 | 425 | |
|
414 | 426 | def getoutputerror(self,cmd): |
|
415 | 427 | """Stateful interface to getoutputerror().""" |
|
416 | 428 | |
|
417 | 429 | return getoutputerror(cmd,self.verbose,self.debug,self.header,self.split) |
|
418 | 430 | |
|
419 | 431 | bq = getoutput # alias |
|
420 | 432 | |
|
421 | 433 | #----------------------------------------------------------------------------- |
|
422 | 434 | def mutex_opts(dict,ex_op): |
|
423 | 435 | """Check for presence of mutually exclusive keys in a dict. |
|
424 | 436 | |
|
425 | 437 | Call: mutex_opts(dict,[[op1a,op1b],[op2a,op2b]...]""" |
|
426 | 438 | for op1,op2 in ex_op: |
|
427 | 439 | if op1 in dict and op2 in dict: |
|
428 | 440 | raise ValueError,'\n*** ERROR in Arguments *** '\ |
|
429 | 441 | 'Options '+op1+' and '+op2+' are mutually exclusive.' |
|
430 | 442 | |
|
431 | 443 | #----------------------------------------------------------------------------- |
|
432 | 444 | def get_py_filename(name): |
|
433 | 445 | """Return a valid python filename in the current directory. |
|
434 | 446 | |
|
435 | 447 | If the given name is not a file, it adds '.py' and searches again. |
|
436 | 448 | Raises IOError with an informative message if the file isn't found.""" |
|
437 | 449 | |
|
438 | 450 | name = os.path.expanduser(name) |
|
439 | 451 | if not os.path.isfile(name) and not name.endswith('.py'): |
|
440 | 452 | name += '.py' |
|
441 | 453 | if os.path.isfile(name): |
|
442 | 454 | return name |
|
443 | 455 | else: |
|
444 | 456 | raise IOError,'File `%s` not found.' % name |
|
445 | 457 | |
|
446 | 458 | #----------------------------------------------------------------------------- |
|
447 | 459 | def filefind(fname,alt_dirs = None): |
|
448 | 460 | """Return the given filename either in the current directory, if it |
|
449 | 461 | exists, or in a specified list of directories. |
|
450 | 462 | |
|
451 | 463 | ~ expansion is done on all file and directory names. |
|
452 | 464 | |
|
453 | 465 | Upon an unsuccessful search, raise an IOError exception.""" |
|
454 | 466 | |
|
455 | 467 | if alt_dirs is None: |
|
456 | 468 | try: |
|
457 | 469 | alt_dirs = get_home_dir() |
|
458 | 470 | except HomeDirError: |
|
459 | 471 | alt_dirs = os.getcwd() |
|
460 | 472 | search = [fname] + list_strings(alt_dirs) |
|
461 | 473 | search = map(os.path.expanduser,search) |
|
462 | 474 | #print 'search list for',fname,'list:',search # dbg |
|
463 | 475 | fname = search[0] |
|
464 | 476 | if os.path.isfile(fname): |
|
465 | 477 | return fname |
|
466 | 478 | for direc in search[1:]: |
|
467 | 479 | testname = os.path.join(direc,fname) |
|
468 | 480 | #print 'testname',testname # dbg |
|
469 | 481 | if os.path.isfile(testname): |
|
470 | 482 | return testname |
|
471 | 483 | raise IOError,'File' + `fname` + \ |
|
472 | 484 | ' not found in current or supplied directories:' + `alt_dirs` |
|
473 | 485 | |
|
474 | 486 | #---------------------------------------------------------------------------- |
|
475 | 487 | def file_read(filename): |
|
476 | 488 | """Read a file and close it. Returns the file source.""" |
|
477 | 489 | fobj = open(filename,'r'); |
|
478 | 490 | source = fobj.read(); |
|
479 | 491 | fobj.close() |
|
480 | 492 | return source |
|
481 | 493 | |
|
482 | 494 | def file_readlines(filename): |
|
483 | 495 | """Read a file and close it. Returns the file source using readlines().""" |
|
484 | 496 | fobj = open(filename,'r'); |
|
485 | 497 | lines = fobj.readlines(); |
|
486 | 498 | fobj.close() |
|
487 | 499 | return lines |
|
488 | 500 | |
|
489 | 501 | #---------------------------------------------------------------------------- |
|
490 | 502 | def target_outdated(target,deps): |
|
491 | 503 | """Determine whether a target is out of date. |
|
492 | 504 | |
|
493 | 505 | target_outdated(target,deps) -> 1/0 |
|
494 | 506 | |
|
495 | 507 | deps: list of filenames which MUST exist. |
|
496 | 508 | target: single filename which may or may not exist. |
|
497 | 509 | |
|
498 | 510 | If target doesn't exist or is older than any file listed in deps, return |
|
499 | 511 | true, otherwise return false. |
|
500 | 512 | """ |
|
501 | 513 | try: |
|
502 | 514 | target_time = os.path.getmtime(target) |
|
503 | 515 | except os.error: |
|
504 | 516 | return 1 |
|
505 | 517 | for dep in deps: |
|
506 | 518 | dep_time = os.path.getmtime(dep) |
|
507 | 519 | if dep_time > target_time: |
|
508 | 520 | #print "For target",target,"Dep failed:",dep # dbg |
|
509 | 521 | #print "times (dep,tar):",dep_time,target_time # dbg |
|
510 | 522 | return 1 |
|
511 | 523 | return 0 |
|
512 | 524 | |
|
513 | 525 | #----------------------------------------------------------------------------- |
|
514 | 526 | def target_update(target,deps,cmd): |
|
515 | 527 | """Update a target with a given command given a list of dependencies. |
|
516 | 528 | |
|
517 | 529 | target_update(target,deps,cmd) -> runs cmd if target is outdated. |
|
518 | 530 | |
|
519 | 531 | This is just a wrapper around target_outdated() which calls the given |
|
520 | 532 | command if target is outdated.""" |
|
521 | 533 | |
|
522 | 534 | if target_outdated(target,deps): |
|
523 | 535 | xsys(cmd) |
|
524 | 536 | |
|
525 | 537 | #---------------------------------------------------------------------------- |
|
526 | 538 | def unquote_ends(istr): |
|
527 | 539 | """Remove a single pair of quotes from the endpoints of a string.""" |
|
528 | 540 | |
|
529 | 541 | if not istr: |
|
530 | 542 | return istr |
|
531 | 543 | if (istr[0]=="'" and istr[-1]=="'") or \ |
|
532 | 544 | (istr[0]=='"' and istr[-1]=='"'): |
|
533 | 545 | return istr[1:-1] |
|
534 | 546 | else: |
|
535 | 547 | return istr |
|
536 | 548 | |
|
537 | 549 | #---------------------------------------------------------------------------- |
|
538 | 550 | def process_cmdline(argv,names=[],defaults={},usage=''): |
|
539 | 551 | """ Process command-line options and arguments. |
|
540 | 552 | |
|
541 | 553 | Arguments: |
|
542 | 554 | |
|
543 | 555 | - argv: list of arguments, typically sys.argv. |
|
544 | 556 | |
|
545 | 557 | - names: list of option names. See DPyGetOpt docs for details on options |
|
546 | 558 | syntax. |
|
547 | 559 | |
|
548 | 560 | - defaults: dict of default values. |
|
549 | 561 | |
|
550 | 562 | - usage: optional usage notice to print if a wrong argument is passed. |
|
551 | 563 | |
|
552 | 564 | Return a dict of options and a list of free arguments.""" |
|
553 | 565 | |
|
554 | 566 | getopt = DPyGetOpt.DPyGetOpt() |
|
555 | 567 | getopt.setIgnoreCase(0) |
|
556 | 568 | getopt.parseConfiguration(names) |
|
557 | 569 | |
|
558 | 570 | try: |
|
559 | 571 | getopt.processArguments(argv) |
|
560 | 572 | except: |
|
561 | 573 | print usage |
|
562 | 574 | warn(`sys.exc_value`,level=4) |
|
563 | 575 | |
|
564 | 576 | defaults.update(getopt.optionValues) |
|
565 | 577 | args = getopt.freeValues |
|
566 | 578 | |
|
567 | 579 | return defaults,args |
|
568 | 580 | |
|
569 | 581 | #---------------------------------------------------------------------------- |
|
570 | 582 | def optstr2types(ostr): |
|
571 | 583 | """Convert a string of option names to a dict of type mappings. |
|
572 | 584 | |
|
573 | 585 | optstr2types(str) -> {None:'string_opts',int:'int_opts',float:'float_opts'} |
|
574 | 586 | |
|
575 | 587 | This is used to get the types of all the options in a string formatted |
|
576 | 588 | with the conventions of DPyGetOpt. The 'type' None is used for options |
|
577 | 589 | which are strings (they need no further conversion). This function's main |
|
578 | 590 | use is to get a typemap for use with read_dict(). |
|
579 | 591 | """ |
|
580 | 592 | |
|
581 | 593 | typeconv = {None:'',int:'',float:''} |
|
582 | 594 | typemap = {'s':None,'i':int,'f':float} |
|
583 | 595 | opt_re = re.compile(r'([\w]*)([^:=]*:?=?)([sif]?)') |
|
584 | 596 | |
|
585 | 597 | for w in ostr.split(): |
|
586 | 598 | oname,alias,otype = opt_re.match(w).groups() |
|
587 | 599 | if otype == '' or alias == '!': # simple switches are integers too |
|
588 | 600 | otype = 'i' |
|
589 | 601 | typeconv[typemap[otype]] += oname + ' ' |
|
590 | 602 | return typeconv |
|
591 | 603 | |
|
592 | 604 | #---------------------------------------------------------------------------- |
|
593 | 605 | def read_dict(filename,type_conv=None,**opt): |
|
594 | 606 | |
|
595 | 607 | """Read a dictionary of key=value pairs from an input file, optionally |
|
596 | 608 | performing conversions on the resulting values. |
|
597 | 609 | |
|
598 | 610 | read_dict(filename,type_conv,**opt) -> dict |
|
599 | 611 | |
|
600 | 612 | Only one value per line is accepted, the format should be |
|
601 | 613 | # optional comments are ignored |
|
602 | 614 | key value\n |
|
603 | 615 | |
|
604 | 616 | Args: |
|
605 | 617 | |
|
606 | 618 | - type_conv: A dictionary specifying which keys need to be converted to |
|
607 | 619 | which types. By default all keys are read as strings. This dictionary |
|
608 | 620 | should have as its keys valid conversion functions for strings |
|
609 | 621 | (int,long,float,complex, or your own). The value for each key |
|
610 | 622 | (converter) should be a whitespace separated string containing the names |
|
611 | 623 | of all the entries in the file to be converted using that function. For |
|
612 | 624 | keys to be left alone, use None as the conversion function (only needed |
|
613 | 625 | with purge=1, see below). |
|
614 | 626 | |
|
615 | 627 | - opt: dictionary with extra options as below (default in parens) |
|
616 | 628 | |
|
617 | 629 | purge(0): if set to 1, all keys *not* listed in type_conv are purged out |
|
618 | 630 | of the dictionary to be returned. If purge is going to be used, the |
|
619 | 631 | set of keys to be left as strings also has to be explicitly specified |
|
620 | 632 | using the (non-existent) conversion function None. |
|
621 | 633 | |
|
622 | 634 | fs(None): field separator. This is the key/value separator to be used |
|
623 | 635 | when parsing the file. The None default means any whitespace [behavior |
|
624 | 636 | of string.split()]. |
|
625 | 637 | |
|
626 | 638 | strip(0): if 1, strip string values of leading/trailinig whitespace. |
|
627 | 639 | |
|
628 | 640 | warn(1): warning level if requested keys are not found in file. |
|
629 | 641 | - 0: silently ignore. |
|
630 | 642 | - 1: inform but proceed. |
|
631 | 643 | - 2: raise KeyError exception. |
|
632 | 644 | |
|
633 | 645 | no_empty(0): if 1, remove keys with whitespace strings as a value. |
|
634 | 646 | |
|
635 | 647 | unique([]): list of keys (or space separated string) which can't be |
|
636 | 648 | repeated. If one such key is found in the file, each new instance |
|
637 | 649 | overwrites the previous one. For keys not listed here, the behavior is |
|
638 | 650 | to make a list of all appearances. |
|
639 | 651 | |
|
640 | 652 | Example: |
|
641 | 653 | If the input file test.ini has: |
|
642 | 654 | i 3 |
|
643 | 655 | x 4.5 |
|
644 | 656 | y 5.5 |
|
645 | 657 | s hi ho |
|
646 | 658 | Then: |
|
647 | 659 | |
|
648 | 660 | >>> type_conv={int:'i',float:'x',None:'s'} |
|
649 | 661 | >>> read_dict('test.ini') |
|
650 | 662 | {'i': '3', 's': 'hi ho', 'x': '4.5', 'y': '5.5'} |
|
651 | 663 | >>> read_dict('test.ini',type_conv) |
|
652 | 664 | {'i': 3, 's': 'hi ho', 'x': 4.5, 'y': '5.5'} |
|
653 | 665 | >>> read_dict('test.ini',type_conv,purge=1) |
|
654 | 666 | {'i': 3, 's': 'hi ho', 'x': 4.5} |
|
655 | 667 | """ |
|
656 | 668 | |
|
657 | 669 | # starting config |
|
658 | 670 | opt.setdefault('purge',0) |
|
659 | 671 | opt.setdefault('fs',None) # field sep defaults to any whitespace |
|
660 | 672 | opt.setdefault('strip',0) |
|
661 | 673 | opt.setdefault('warn',1) |
|
662 | 674 | opt.setdefault('no_empty',0) |
|
663 | 675 | opt.setdefault('unique','') |
|
664 | 676 | if type(opt['unique']) in StringTypes: |
|
665 | 677 | unique_keys = qw(opt['unique']) |
|
666 | 678 | elif type(opt['unique']) in (types.TupleType,types.ListType): |
|
667 | 679 | unique_keys = opt['unique'] |
|
668 | 680 | else: |
|
669 | 681 | raise ValueError, 'Unique keys must be given as a string, List or Tuple' |
|
670 | 682 | |
|
671 | 683 | dict = {} |
|
672 | 684 | # first read in table of values as strings |
|
673 | 685 | file = open(filename,'r') |
|
674 | 686 | for line in file.readlines(): |
|
675 | 687 | line = line.strip() |
|
676 | 688 | if len(line) and line[0]=='#': continue |
|
677 | 689 | if len(line)>0: |
|
678 | 690 | lsplit = line.split(opt['fs'],1) |
|
679 | 691 | try: |
|
680 | 692 | key,val = lsplit |
|
681 | 693 | except ValueError: |
|
682 | 694 | key,val = lsplit[0],'' |
|
683 | 695 | key = key.strip() |
|
684 | 696 | if opt['strip']: val = val.strip() |
|
685 | 697 | if val == "''" or val == '""': val = '' |
|
686 | 698 | if opt['no_empty'] and (val=='' or val.isspace()): |
|
687 | 699 | continue |
|
688 | 700 | # if a key is found more than once in the file, build a list |
|
689 | 701 | # unless it's in the 'unique' list. In that case, last found in file |
|
690 | 702 | # takes precedence. User beware. |
|
691 | 703 | try: |
|
692 | 704 | if dict[key] and key in unique_keys: |
|
693 | 705 | dict[key] = val |
|
694 | 706 | elif type(dict[key]) is types.ListType: |
|
695 | 707 | dict[key].append(val) |
|
696 | 708 | else: |
|
697 | 709 | dict[key] = [dict[key],val] |
|
698 | 710 | except KeyError: |
|
699 | 711 | dict[key] = val |
|
700 | 712 | # purge if requested |
|
701 | 713 | if opt['purge']: |
|
702 | 714 | accepted_keys = qwflat(type_conv.values()) |
|
703 | 715 | for key in dict.keys(): |
|
704 | 716 | if key in accepted_keys: continue |
|
705 | 717 | del(dict[key]) |
|
706 | 718 | # now convert if requested |
|
707 | 719 | if type_conv==None: return dict |
|
708 | 720 | conversions = type_conv.keys() |
|
709 | 721 | try: conversions.remove(None) |
|
710 | 722 | except: pass |
|
711 | 723 | for convert in conversions: |
|
712 | 724 | for val in qw(type_conv[convert]): |
|
713 | 725 | try: |
|
714 | 726 | dict[val] = convert(dict[val]) |
|
715 | 727 | except KeyError,e: |
|
716 | 728 | if opt['warn'] == 0: |
|
717 | 729 | pass |
|
718 | 730 | elif opt['warn'] == 1: |
|
719 | 731 | print >>sys.stderr, 'Warning: key',val,\ |
|
720 | 732 | 'not found in file',filename |
|
721 | 733 | elif opt['warn'] == 2: |
|
722 | 734 | raise KeyError,e |
|
723 | 735 | else: |
|
724 | 736 | raise ValueError,'Warning level must be 0,1 or 2' |
|
725 | 737 | |
|
726 | 738 | return dict |
|
727 | 739 | |
|
728 | 740 | #---------------------------------------------------------------------------- |
|
729 | 741 | def flag_calls(func): |
|
730 | 742 | """Wrap a function to detect and flag when it gets called. |
|
731 | 743 | |
|
732 | 744 | This is a decorator which takes a function and wraps it in a function with |
|
733 | 745 | a 'called' attribute. wrapper.called is initialized to False. |
|
734 | 746 | |
|
735 | 747 | The wrapper.called attribute is set to False right before each call to the |
|
736 | 748 | wrapped function, so if the call fails it remains False. After the call |
|
737 | 749 | completes, wrapper.called is set to True and the output is returned. |
|
738 | 750 | |
|
739 | 751 | Testing for truth in wrapper.called allows you to determine if a call to |
|
740 | 752 | func() was attempted and succeeded.""" |
|
741 | 753 | |
|
742 | 754 | def wrapper(*args,**kw): |
|
743 | 755 | wrapper.called = False |
|
744 | 756 | out = func(*args,**kw) |
|
745 | 757 | wrapper.called = True |
|
746 | 758 | return out |
|
747 | 759 | |
|
748 | 760 | wrapper.called = False |
|
749 | 761 | wrapper.__doc__ = func.__doc__ |
|
750 | 762 | return wrapper |
|
751 | 763 | |
|
752 | 764 | #---------------------------------------------------------------------------- |
|
753 | 765 | class HomeDirError(Error): |
|
754 | 766 | pass |
|
755 | 767 | |
|
756 | 768 | def get_home_dir(): |
|
757 | 769 | """Return the closest possible equivalent to a 'home' directory. |
|
758 | 770 | |
|
759 | 771 | We first try $HOME. Absent that, on NT it's $HOMEDRIVE\$HOMEPATH. |
|
760 | 772 | |
|
761 | 773 | Currently only Posix and NT are implemented, a HomeDirError exception is |
|
762 | 774 | raised for all other OSes. """ |
|
763 | 775 | |
|
764 | 776 | isdir = os.path.isdir |
|
765 | 777 | env = os.environ |
|
766 | 778 | try: |
|
767 | 779 | homedir = env['HOME'] |
|
768 | 780 | if not isdir(homedir): |
|
769 | 781 | # in case a user stuck some string which does NOT resolve to a |
|
770 | 782 | # valid path, it's as good as if we hadn't foud it |
|
771 | 783 | raise KeyError |
|
772 | 784 | return homedir |
|
773 | 785 | except KeyError: |
|
774 | 786 | if os.name == 'posix': |
|
775 | 787 | raise HomeDirError,'undefined $HOME, IPython can not proceed.' |
|
776 | 788 | elif os.name == 'nt': |
|
777 | 789 | # For some strange reason, win9x returns 'nt' for os.name. |
|
778 | 790 | try: |
|
779 | 791 | homedir = os.path.join(env['HOMEDRIVE'],env['HOMEPATH']) |
|
780 | 792 | if not isdir(homedir): |
|
781 | 793 | homedir = os.path.join(env['USERPROFILE']) |
|
782 | 794 | if not isdir(homedir): |
|
783 | 795 | raise HomeDirError |
|
784 | 796 | return homedir |
|
785 | 797 | except: |
|
786 | 798 | try: |
|
787 | 799 | # Use the registry to get the 'My Documents' folder. |
|
788 | 800 | import _winreg as wreg |
|
789 | 801 | key = wreg.OpenKey(wreg.HKEY_CURRENT_USER, |
|
790 | 802 | "Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders") |
|
791 | 803 | homedir = wreg.QueryValueEx(key,'Personal')[0] |
|
792 | 804 | key.Close() |
|
793 | 805 | if not isdir(homedir): |
|
794 | 806 | e = ('Invalid "Personal" folder registry key ' |
|
795 | 807 | 'typically "My Documents".\n' |
|
796 | 808 | 'Value: %s\n' |
|
797 | 809 | 'This is not a valid directory on your system.' % |
|
798 | 810 | homedir) |
|
799 | 811 | raise HomeDirError(e) |
|
800 | 812 | return homedir |
|
801 | 813 | except HomeDirError: |
|
802 | 814 | raise |
|
803 | 815 | except: |
|
804 | 816 | return 'C:\\' |
|
805 | 817 | elif os.name == 'dos': |
|
806 | 818 | # Desperate, may do absurd things in classic MacOS. May work under DOS. |
|
807 | 819 | return 'C:\\' |
|
808 | 820 | else: |
|
809 | 821 | raise HomeDirError,'support for your operating system not implemented.' |
|
810 | 822 | |
|
811 | 823 | #**************************************************************************** |
|
812 | 824 | # strings and text |
|
813 | 825 | |
|
814 | 826 | class LSString(str): |
|
815 | 827 | """String derivative with a special access attributes. |
|
816 | 828 | |
|
817 | 829 | These are normal strings, but with the special attributes: |
|
818 | 830 | |
|
819 | 831 | .l (or .list) : value as list (split on newlines). |
|
820 | 832 | .n (or .nlstr): original value (the string itself). |
|
821 | 833 | .s (or .spstr): value as whitespace-separated string. |
|
822 | 834 | |
|
823 | 835 | Any values which require transformations are computed only once and |
|
824 | 836 | cached. |
|
825 | 837 | |
|
826 | 838 | Such strings are very useful to efficiently interact with the shell, which |
|
827 | 839 | typically only understands whitespace-separated options for commands.""" |
|
828 | 840 | |
|
829 | 841 | def get_list(self): |
|
830 | 842 | try: |
|
831 | 843 | return self.__list |
|
832 | 844 | except AttributeError: |
|
833 | 845 | self.__list = self.split('\n') |
|
834 | 846 | return self.__list |
|
835 | 847 | |
|
836 | 848 | l = list = property(get_list) |
|
837 | 849 | |
|
838 | 850 | def get_spstr(self): |
|
839 | 851 | try: |
|
840 | 852 | return self.__spstr |
|
841 | 853 | except AttributeError: |
|
842 | 854 | self.__spstr = self.replace('\n',' ') |
|
843 | 855 | return self.__spstr |
|
844 | 856 | |
|
845 | 857 | s = spstr = property(get_spstr) |
|
846 | 858 | |
|
847 | 859 | def get_nlstr(self): |
|
848 | 860 | return self |
|
849 | 861 | |
|
850 | 862 | n = nlstr = property(get_nlstr) |
|
851 | 863 | |
|
852 | 864 | def get_paths(self): |
|
853 | 865 | try: |
|
854 | 866 | return self.__paths |
|
855 | 867 | except AttributeError: |
|
856 | 868 | self.__paths = [path(p) for p in self.split('\n') if os.path.exists(p)] |
|
857 | 869 | return self.__paths |
|
858 | 870 | |
|
859 | 871 | p = paths = property(get_paths) |
|
860 | 872 | |
|
861 | 873 | |
|
862 | 874 | #---------------------------------------------------------------------------- |
|
863 | 875 | class SList(list): |
|
864 | 876 | """List derivative with a special access attributes. |
|
865 | 877 | |
|
866 | 878 | These are normal lists, but with the special attributes: |
|
867 | 879 | |
|
868 | 880 | .l (or .list) : value as list (the list itself). |
|
869 | 881 | .n (or .nlstr): value as a string, joined on newlines. |
|
870 | 882 | .s (or .spstr): value as a string, joined on spaces. |
|
871 | 883 | |
|
872 | 884 | Any values which require transformations are computed only once and |
|
873 | 885 | cached.""" |
|
874 | 886 | |
|
875 | 887 | def get_list(self): |
|
876 | 888 | return self |
|
877 | 889 | |
|
878 | 890 | l = list = property(get_list) |
|
879 | 891 | |
|
880 | 892 | def get_spstr(self): |
|
881 | 893 | try: |
|
882 | 894 | return self.__spstr |
|
883 | 895 | except AttributeError: |
|
884 | 896 | self.__spstr = ' '.join(self) |
|
885 | 897 | return self.__spstr |
|
886 | 898 | |
|
887 | 899 | s = spstr = property(get_spstr) |
|
888 | 900 | |
|
889 | 901 | def get_nlstr(self): |
|
890 | 902 | try: |
|
891 | 903 | return self.__nlstr |
|
892 | 904 | except AttributeError: |
|
893 | 905 | self.__nlstr = '\n'.join(self) |
|
894 | 906 | return self.__nlstr |
|
895 | 907 | |
|
896 | 908 | n = nlstr = property(get_nlstr) |
|
897 | 909 | |
|
898 | 910 | def get_paths(self): |
|
899 | 911 | try: |
|
900 | 912 | return self.__paths |
|
901 | 913 | except AttributeError: |
|
902 | 914 | self.__paths = [path(p) for p in self if os.path.exists(p)] |
|
903 | 915 | return self.__paths |
|
904 | 916 | |
|
905 | 917 | p = paths = property(get_paths) |
|
906 | 918 | |
|
907 | 919 | #---------------------------------------------------------------------------- |
|
908 | 920 | def esc_quotes(strng): |
|
909 | 921 | """Return the input string with single and double quotes escaped out""" |
|
910 | 922 | |
|
911 | 923 | return strng.replace('"','\\"').replace("'","\\'") |
|
912 | 924 | |
|
913 | 925 | #---------------------------------------------------------------------------- |
|
914 | 926 | def make_quoted_expr(s): |
|
915 | 927 | """Return string s in appropriate quotes, using raw string if possible. |
|
916 | 928 | |
|
917 | 929 | Effectively this turns string: cd \ao\ao\ |
|
918 | 930 | to: r"cd \ao\ao\_"[:-1] |
|
919 | 931 | |
|
920 | 932 | Note the use of raw string and padding at the end to allow trailing backslash. |
|
921 | 933 | |
|
922 | 934 | """ |
|
923 | 935 | |
|
924 | 936 | tail = '' |
|
925 | 937 | tailpadding = '' |
|
926 | 938 | raw = '' |
|
927 | 939 | if "\\" in s: |
|
928 | 940 | raw = 'r' |
|
929 | 941 | if s.endswith('\\'): |
|
930 | 942 | tail = '[:-1]' |
|
931 | 943 | tailpadding = '_' |
|
932 | 944 | if '"' not in s: |
|
933 | 945 | quote = '"' |
|
934 | 946 | elif "'" not in s: |
|
935 | 947 | quote = "'" |
|
936 | 948 | elif '"""' not in s and not s.endswith('"'): |
|
937 | 949 | quote = '"""' |
|
938 | 950 | elif "'''" not in s and not s.endswith("'"): |
|
939 | 951 | quote = "'''" |
|
940 | 952 | else: |
|
941 | 953 | # give up, backslash-escaped string will do |
|
942 | 954 | return '"%s"' % esc_quotes(s) |
|
943 | 955 | res = itpl("$raw$quote$s$tailpadding$quote$tail") |
|
944 | 956 | return res |
|
945 | 957 | |
|
946 | 958 | |
|
947 | 959 | #---------------------------------------------------------------------------- |
|
948 | 960 | def raw_input_multi(header='', ps1='==> ', ps2='..> ',terminate_str = '.'): |
|
949 | 961 | """Take multiple lines of input. |
|
950 | 962 | |
|
951 | 963 | A list with each line of input as a separate element is returned when a |
|
952 | 964 | termination string is entered (defaults to a single '.'). Input can also |
|
953 | 965 | terminate via EOF (^D in Unix, ^Z-RET in Windows). |
|
954 | 966 | |
|
955 | 967 | Lines of input which end in \\ are joined into single entries (and a |
|
956 | 968 | secondary continuation prompt is issued as long as the user terminates |
|
957 | 969 | lines with \\). This allows entering very long strings which are still |
|
958 | 970 | meant to be treated as single entities. |
|
959 | 971 | """ |
|
960 | 972 | |
|
961 | 973 | try: |
|
962 | 974 | if header: |
|
963 | 975 | header += '\n' |
|
964 | 976 | lines = [raw_input(header + ps1)] |
|
965 | 977 | except EOFError: |
|
966 | 978 | return [] |
|
967 | 979 | terminate = [terminate_str] |
|
968 | 980 | try: |
|
969 | 981 | while lines[-1:] != terminate: |
|
970 | 982 | new_line = raw_input(ps1) |
|
971 | 983 | while new_line.endswith('\\'): |
|
972 | 984 | new_line = new_line[:-1] + raw_input(ps2) |
|
973 | 985 | lines.append(new_line) |
|
974 | 986 | |
|
975 | 987 | return lines[:-1] # don't return the termination command |
|
976 | 988 | except EOFError: |
|
977 | 989 | |
|
978 | 990 | return lines |
|
979 | 991 | |
|
980 | 992 | #---------------------------------------------------------------------------- |
|
981 | 993 | def raw_input_ext(prompt='', ps2='... '): |
|
982 | 994 | """Similar to raw_input(), but accepts extended lines if input ends with \\.""" |
|
983 | 995 | |
|
984 | 996 | line = raw_input(prompt) |
|
985 | 997 | while line.endswith('\\'): |
|
986 | 998 | line = line[:-1] + raw_input(ps2) |
|
987 | 999 | return line |
|
988 | 1000 | |
|
989 | 1001 | #---------------------------------------------------------------------------- |
|
990 | 1002 | def ask_yes_no(prompt,default=None): |
|
991 | 1003 | """Asks a question and returns an integer 1/0 (y/n) answer. |
|
992 | 1004 | |
|
993 | 1005 | If default is given (one of 'y','n'), it is used if the user input is |
|
994 | 1006 | empty. Otherwise the question is repeated until an answer is given. |
|
995 | 1007 | |
|
996 | 1008 | An EOF is treated as the default answer. If there is no default, an |
|
997 | 1009 | exception is raised to prevent infinite loops. |
|
998 | 1010 | |
|
999 | 1011 | Valid answers are: y/yes/n/no (match is not case sensitive).""" |
|
1000 | 1012 | |
|
1001 | 1013 | answers = {'y':True,'n':False,'yes':True,'no':False} |
|
1002 | 1014 | ans = None |
|
1003 | 1015 | while ans not in answers.keys(): |
|
1004 | 1016 | try: |
|
1005 | 1017 | ans = raw_input(prompt+' ').lower() |
|
1006 | 1018 | if not ans: # response was an empty string |
|
1007 | 1019 | ans = default |
|
1008 | 1020 | except KeyboardInterrupt: |
|
1009 | 1021 | pass |
|
1010 | 1022 | except EOFError: |
|
1011 | 1023 | if default in answers.keys(): |
|
1012 | 1024 | ans = default |
|
1013 | 1025 | |
|
1014 | 1026 | else: |
|
1015 | 1027 | raise |
|
1016 | 1028 | |
|
1017 | 1029 | return answers[ans] |
|
1018 | 1030 | |
|
1019 | 1031 | #---------------------------------------------------------------------------- |
|
1020 | 1032 | def marquee(txt='',width=78,mark='*'): |
|
1021 | 1033 | """Return the input string centered in a 'marquee'.""" |
|
1022 | 1034 | if not txt: |
|
1023 | 1035 | return (mark*width)[:width] |
|
1024 | 1036 | nmark = (width-len(txt)-2)/len(mark)/2 |
|
1025 | 1037 | if nmark < 0: nmark =0 |
|
1026 | 1038 | marks = mark*nmark |
|
1027 | 1039 | return '%s %s %s' % (marks,txt,marks) |
|
1028 | 1040 | |
|
1029 | 1041 | #---------------------------------------------------------------------------- |
|
1030 | 1042 | class EvalDict: |
|
1031 | 1043 | """ |
|
1032 | 1044 | Emulate a dict which evaluates its contents in the caller's frame. |
|
1033 | 1045 | |
|
1034 | 1046 | Usage: |
|
1035 | 1047 | >>>number = 19 |
|
1036 | 1048 | >>>text = "python" |
|
1037 | 1049 | >>>print "%(text.capitalize())s %(number/9.0).1f rules!" % EvalDict() |
|
1038 | 1050 | """ |
|
1039 | 1051 | |
|
1040 | 1052 | # This version is due to sismex01@hebmex.com on c.l.py, and is basically a |
|
1041 | 1053 | # modified (shorter) version of: |
|
1042 | 1054 | # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66018 by |
|
1043 | 1055 | # Skip Montanaro (skip@pobox.com). |
|
1044 | 1056 | |
|
1045 | 1057 | def __getitem__(self, name): |
|
1046 | 1058 | frame = sys._getframe(1) |
|
1047 | 1059 | return eval(name, frame.f_globals, frame.f_locals) |
|
1048 | 1060 | |
|
1049 | 1061 | EvalString = EvalDict # for backwards compatibility |
|
1050 | 1062 | #---------------------------------------------------------------------------- |
|
1051 | 1063 | def qw(words,flat=0,sep=None,maxsplit=-1): |
|
1052 | 1064 | """Similar to Perl's qw() operator, but with some more options. |
|
1053 | 1065 | |
|
1054 | 1066 | qw(words,flat=0,sep=' ',maxsplit=-1) -> words.split(sep,maxsplit) |
|
1055 | 1067 | |
|
1056 | 1068 | words can also be a list itself, and with flat=1, the output will be |
|
1057 | 1069 | recursively flattened. Examples: |
|
1058 | 1070 | |
|
1059 | 1071 | >>> qw('1 2') |
|
1060 | 1072 | ['1', '2'] |
|
1061 | 1073 | >>> qw(['a b','1 2',['m n','p q']]) |
|
1062 | 1074 | [['a', 'b'], ['1', '2'], [['m', 'n'], ['p', 'q']]] |
|
1063 | 1075 | >>> qw(['a b','1 2',['m n','p q']],flat=1) |
|
1064 | 1076 | ['a', 'b', '1', '2', 'm', 'n', 'p', 'q'] """ |
|
1065 | 1077 | |
|
1066 | 1078 | if type(words) in StringTypes: |
|
1067 | 1079 | return [word.strip() for word in words.split(sep,maxsplit) |
|
1068 | 1080 | if word and not word.isspace() ] |
|
1069 | 1081 | if flat: |
|
1070 | 1082 | return flatten(map(qw,words,[1]*len(words))) |
|
1071 | 1083 | return map(qw,words) |
|
1072 | 1084 | |
|
1073 | 1085 | #---------------------------------------------------------------------------- |
|
1074 | 1086 | def qwflat(words,sep=None,maxsplit=-1): |
|
1075 | 1087 | """Calls qw(words) in flat mode. It's just a convenient shorthand.""" |
|
1076 | 1088 | return qw(words,1,sep,maxsplit) |
|
1077 | 1089 | |
|
1078 | 1090 | #---------------------------------------------------------------------------- |
|
1079 | 1091 | def qw_lol(indata): |
|
1080 | 1092 | """qw_lol('a b') -> [['a','b']], |
|
1081 | 1093 | otherwise it's just a call to qw(). |
|
1082 | 1094 | |
|
1083 | 1095 | We need this to make sure the modules_some keys *always* end up as a |
|
1084 | 1096 | list of lists.""" |
|
1085 | 1097 | |
|
1086 | 1098 | if type(indata) in StringTypes: |
|
1087 | 1099 | return [qw(indata)] |
|
1088 | 1100 | else: |
|
1089 | 1101 | return qw(indata) |
|
1090 | 1102 | |
|
1091 | 1103 | #----------------------------------------------------------------------------- |
|
1092 | 1104 | def list_strings(arg): |
|
1093 | 1105 | """Always return a list of strings, given a string or list of strings |
|
1094 | 1106 | as input.""" |
|
1095 | 1107 | |
|
1096 | 1108 | if type(arg) in StringTypes: return [arg] |
|
1097 | 1109 | else: return arg |
|
1098 | 1110 | |
|
1099 | 1111 | #---------------------------------------------------------------------------- |
|
1100 | 1112 | def grep(pat,list,case=1): |
|
1101 | 1113 | """Simple minded grep-like function. |
|
1102 | 1114 | grep(pat,list) returns occurrences of pat in list, None on failure. |
|
1103 | 1115 | |
|
1104 | 1116 | It only does simple string matching, with no support for regexps. Use the |
|
1105 | 1117 | option case=0 for case-insensitive matching.""" |
|
1106 | 1118 | |
|
1107 | 1119 | # This is pretty crude. At least it should implement copying only references |
|
1108 | 1120 | # to the original data in case it's big. Now it copies the data for output. |
|
1109 | 1121 | out=[] |
|
1110 | 1122 | if case: |
|
1111 | 1123 | for term in list: |
|
1112 | 1124 | if term.find(pat)>-1: out.append(term) |
|
1113 | 1125 | else: |
|
1114 | 1126 | lpat=pat.lower() |
|
1115 | 1127 | for term in list: |
|
1116 | 1128 | if term.lower().find(lpat)>-1: out.append(term) |
|
1117 | 1129 | |
|
1118 | 1130 | if len(out): return out |
|
1119 | 1131 | else: return None |
|
1120 | 1132 | |
|
1121 | 1133 | #---------------------------------------------------------------------------- |
|
1122 | 1134 | def dgrep(pat,*opts): |
|
1123 | 1135 | """Return grep() on dir()+dir(__builtins__). |
|
1124 | 1136 | |
|
1125 | 1137 | A very common use of grep() when working interactively.""" |
|
1126 | 1138 | |
|
1127 | 1139 | return grep(pat,dir(__main__)+dir(__main__.__builtins__),*opts) |
|
1128 | 1140 | |
|
1129 | 1141 | #---------------------------------------------------------------------------- |
|
1130 | 1142 | def idgrep(pat): |
|
1131 | 1143 | """Case-insensitive dgrep()""" |
|
1132 | 1144 | |
|
1133 | 1145 | return dgrep(pat,0) |
|
1134 | 1146 | |
|
1135 | 1147 | #---------------------------------------------------------------------------- |
|
1136 | 1148 | def igrep(pat,list): |
|
1137 | 1149 | """Synonym for case-insensitive grep.""" |
|
1138 | 1150 | |
|
1139 | 1151 | return grep(pat,list,case=0) |
|
1140 | 1152 | |
|
1141 | 1153 | #---------------------------------------------------------------------------- |
|
1142 | 1154 | def indent(str,nspaces=4,ntabs=0): |
|
1143 | 1155 | """Indent a string a given number of spaces or tabstops. |
|
1144 | 1156 | |
|
1145 | 1157 | indent(str,nspaces=4,ntabs=0) -> indent str by ntabs+nspaces. |
|
1146 | 1158 | """ |
|
1147 | 1159 | if str is None: |
|
1148 | 1160 | return |
|
1149 | 1161 | ind = '\t'*ntabs+' '*nspaces |
|
1150 | 1162 | outstr = '%s%s' % (ind,str.replace(os.linesep,os.linesep+ind)) |
|
1151 | 1163 | if outstr.endswith(os.linesep+ind): |
|
1152 | 1164 | return outstr[:-len(ind)] |
|
1153 | 1165 | else: |
|
1154 | 1166 | return outstr |
|
1155 | 1167 | |
|
1156 | 1168 | #----------------------------------------------------------------------------- |
|
1157 | 1169 | def native_line_ends(filename,backup=1): |
|
1158 | 1170 | """Convert (in-place) a file to line-ends native to the current OS. |
|
1159 | 1171 | |
|
1160 | 1172 | If the optional backup argument is given as false, no backup of the |
|
1161 | 1173 | original file is left. """ |
|
1162 | 1174 | |
|
1163 | 1175 | backup_suffixes = {'posix':'~','dos':'.bak','nt':'.bak','mac':'.bak'} |
|
1164 | 1176 | |
|
1165 | 1177 | bak_filename = filename + backup_suffixes[os.name] |
|
1166 | 1178 | |
|
1167 | 1179 | original = open(filename).read() |
|
1168 | 1180 | shutil.copy2(filename,bak_filename) |
|
1169 | 1181 | try: |
|
1170 | 1182 | new = open(filename,'wb') |
|
1171 | 1183 | new.write(os.linesep.join(original.splitlines())) |
|
1172 | 1184 | new.write(os.linesep) # ALWAYS put an eol at the end of the file |
|
1173 | 1185 | new.close() |
|
1174 | 1186 | except: |
|
1175 | 1187 | os.rename(bak_filename,filename) |
|
1176 | 1188 | if not backup: |
|
1177 | 1189 | try: |
|
1178 | 1190 | os.remove(bak_filename) |
|
1179 | 1191 | except: |
|
1180 | 1192 | pass |
|
1181 | 1193 | |
|
1182 | 1194 | #---------------------------------------------------------------------------- |
|
1183 | 1195 | def get_pager_cmd(pager_cmd = None): |
|
1184 | 1196 | """Return a pager command. |
|
1185 | 1197 | |
|
1186 | 1198 | Makes some attempts at finding an OS-correct one.""" |
|
1187 | 1199 | |
|
1188 | 1200 | if os.name == 'posix': |
|
1189 | 1201 | default_pager_cmd = 'less -r' # -r for color control sequences |
|
1190 | 1202 | elif os.name in ['nt','dos']: |
|
1191 | 1203 | default_pager_cmd = 'type' |
|
1192 | 1204 | |
|
1193 | 1205 | if pager_cmd is None: |
|
1194 | 1206 | try: |
|
1195 | 1207 | pager_cmd = os.environ['PAGER'] |
|
1196 | 1208 | except: |
|
1197 | 1209 | pager_cmd = default_pager_cmd |
|
1198 | 1210 | return pager_cmd |
|
1199 | 1211 | |
|
1200 | 1212 | #----------------------------------------------------------------------------- |
|
1201 | 1213 | def get_pager_start(pager,start): |
|
1202 | 1214 | """Return the string for paging files with an offset. |
|
1203 | 1215 | |
|
1204 | 1216 | This is the '+N' argument which less and more (under Unix) accept. |
|
1205 | 1217 | """ |
|
1206 | 1218 | |
|
1207 | 1219 | if pager in ['less','more']: |
|
1208 | 1220 | if start: |
|
1209 | 1221 | start_string = '+' + str(start) |
|
1210 | 1222 | else: |
|
1211 | 1223 | start_string = '' |
|
1212 | 1224 | else: |
|
1213 | 1225 | start_string = '' |
|
1214 | 1226 | return start_string |
|
1215 | 1227 | |
|
1216 | 1228 | #---------------------------------------------------------------------------- |
|
1217 | 1229 | if os.name == "nt": |
|
1218 | 1230 | import msvcrt |
|
1219 | 1231 | def page_more(): |
|
1220 | 1232 | """ Smart pausing between pages |
|
1221 | 1233 | |
|
1222 | 1234 | @return: True if need print more lines, False if quit |
|
1223 | 1235 | """ |
|
1224 | 1236 | Term.cout.write('---Return to continue, q to quit--- ') |
|
1225 | 1237 | ans = msvcrt.getch() |
|
1226 | 1238 | if ans in ("q", "Q"): |
|
1227 | 1239 | result = False |
|
1228 | 1240 | else: |
|
1229 | 1241 | result = True |
|
1230 | 1242 | Term.cout.write("\b"*37 + " "*37 + "\b"*37) |
|
1231 | 1243 | return result |
|
1232 | 1244 | else: |
|
1233 | 1245 | def page_more(): |
|
1234 | 1246 | ans = raw_input('---Return to continue, q to quit--- ') |
|
1235 | 1247 | if ans.lower().startswith('q'): |
|
1236 | 1248 | return False |
|
1237 | 1249 | else: |
|
1238 | 1250 | return True |
|
1239 | 1251 | |
|
1240 | 1252 | esc_re = re.compile(r"(\x1b[^m]+m)") |
|
1241 | 1253 | |
|
1242 | 1254 | def page_dumb(strng,start=0,screen_lines=25): |
|
1243 | 1255 | """Very dumb 'pager' in Python, for when nothing else works. |
|
1244 | 1256 | |
|
1245 | 1257 | Only moves forward, same interface as page(), except for pager_cmd and |
|
1246 | 1258 | mode.""" |
|
1247 | 1259 | |
|
1248 | 1260 | out_ln = strng.splitlines()[start:] |
|
1249 | 1261 | screens = chop(out_ln,screen_lines-1) |
|
1250 | 1262 | if len(screens) == 1: |
|
1251 | 1263 | print >>Term.cout, os.linesep.join(screens[0]) |
|
1252 | 1264 | else: |
|
1253 | 1265 | last_escape = "" |
|
1254 | 1266 | for scr in screens[0:-1]: |
|
1255 | 1267 | hunk = os.linesep.join(scr) |
|
1256 | 1268 | print >>Term.cout, last_escape + hunk |
|
1257 | 1269 | if not page_more(): |
|
1258 | 1270 | return |
|
1259 | 1271 | esc_list = esc_re.findall(hunk) |
|
1260 | 1272 | if len(esc_list) > 0: |
|
1261 | 1273 | last_escape = esc_list[-1] |
|
1262 | 1274 | print >>Term.cout, last_escape + os.linesep.join(screens[-1]) |
|
1263 | 1275 | |
|
1264 | 1276 | #---------------------------------------------------------------------------- |
|
1265 | 1277 | def page(strng,start=0,screen_lines=0,pager_cmd = None): |
|
1266 | 1278 | """Print a string, piping through a pager after a certain length. |
|
1267 | 1279 | |
|
1268 | 1280 | The screen_lines parameter specifies the number of *usable* lines of your |
|
1269 | 1281 | terminal screen (total lines minus lines you need to reserve to show other |
|
1270 | 1282 | information). |
|
1271 | 1283 | |
|
1272 | 1284 | If you set screen_lines to a number <=0, page() will try to auto-determine |
|
1273 | 1285 | your screen size and will only use up to (screen_size+screen_lines) for |
|
1274 | 1286 | printing, paging after that. That is, if you want auto-detection but need |
|
1275 | 1287 | to reserve the bottom 3 lines of the screen, use screen_lines = -3, and for |
|
1276 | 1288 | auto-detection without any lines reserved simply use screen_lines = 0. |
|
1277 | 1289 | |
|
1278 | 1290 | If a string won't fit in the allowed lines, it is sent through the |
|
1279 | 1291 | specified pager command. If none given, look for PAGER in the environment, |
|
1280 | 1292 | and ultimately default to less. |
|
1281 | 1293 | |
|
1282 | 1294 | If no system pager works, the string is sent through a 'dumb pager' |
|
1283 | 1295 | written in python, very simplistic. |
|
1284 | 1296 | """ |
|
1285 | 1297 | |
|
1286 | 1298 | # Ugly kludge, but calling curses.initscr() flat out crashes in emacs |
|
1287 | 1299 | TERM = os.environ.get('TERM','dumb') |
|
1288 | 1300 | if TERM in ['dumb','emacs'] and os.name != 'nt': |
|
1289 | 1301 | print strng |
|
1290 | 1302 | return |
|
1291 | 1303 | # chop off the topmost part of the string we don't want to see |
|
1292 | 1304 | str_lines = strng.split(os.linesep)[start:] |
|
1293 | 1305 | str_toprint = os.linesep.join(str_lines) |
|
1294 | 1306 | num_newlines = len(str_lines) |
|
1295 | 1307 | len_str = len(str_toprint) |
|
1296 | 1308 | |
|
1297 | 1309 | # Dumb heuristics to guesstimate number of on-screen lines the string |
|
1298 | 1310 | # takes. Very basic, but good enough for docstrings in reasonable |
|
1299 | 1311 | # terminals. If someone later feels like refining it, it's not hard. |
|
1300 | 1312 | numlines = max(num_newlines,int(len_str/80)+1) |
|
1301 | 1313 | |
|
1302 | 1314 | if os.name == "nt": |
|
1303 | 1315 | screen_lines_def = get_console_size(defaulty=25)[1] |
|
1304 | 1316 | else: |
|
1305 | 1317 | screen_lines_def = 25 # default value if we can't auto-determine |
|
1306 | 1318 | |
|
1307 | 1319 | # auto-determine screen size |
|
1308 | 1320 | if screen_lines <= 0: |
|
1309 | 1321 | if TERM=='xterm': |
|
1310 | 1322 | try: |
|
1311 | 1323 | import curses |
|
1312 | 1324 | if hasattr(curses,'initscr'): |
|
1313 | 1325 | use_curses = 1 |
|
1314 | 1326 | else: |
|
1315 | 1327 | use_curses = 0 |
|
1316 | 1328 | except ImportError: |
|
1317 | 1329 | use_curses = 0 |
|
1318 | 1330 | else: |
|
1319 | 1331 | # curses causes problems on many terminals other than xterm. |
|
1320 | 1332 | use_curses = 0 |
|
1321 | 1333 | if use_curses: |
|
1322 | 1334 | scr = curses.initscr() |
|
1323 | 1335 | screen_lines_real,screen_cols = scr.getmaxyx() |
|
1324 | 1336 | curses.endwin() |
|
1325 | 1337 | screen_lines += screen_lines_real |
|
1326 | 1338 | #print '***Screen size:',screen_lines_real,'lines x',\ |
|
1327 | 1339 | #screen_cols,'columns.' # dbg |
|
1328 | 1340 | else: |
|
1329 | 1341 | screen_lines += screen_lines_def |
|
1330 | 1342 | |
|
1331 | 1343 | #print 'numlines',numlines,'screenlines',screen_lines # dbg |
|
1332 | 1344 | if numlines <= screen_lines : |
|
1333 | 1345 | #print '*** normal print' # dbg |
|
1334 | 1346 | print >>Term.cout, str_toprint |
|
1335 | 1347 | else: |
|
1336 | 1348 | # Try to open pager and default to internal one if that fails. |
|
1337 | 1349 | # All failure modes are tagged as 'retval=1', to match the return |
|
1338 | 1350 | # value of a failed system command. If any intermediate attempt |
|
1339 | 1351 | # sets retval to 1, at the end we resort to our own page_dumb() pager. |
|
1340 | 1352 | pager_cmd = get_pager_cmd(pager_cmd) |
|
1341 | 1353 | pager_cmd += ' ' + get_pager_start(pager_cmd,start) |
|
1342 | 1354 | if os.name == 'nt': |
|
1343 | 1355 | if pager_cmd.startswith('type'): |
|
1344 | 1356 | # The default WinXP 'type' command is failing on complex strings. |
|
1345 | 1357 | retval = 1 |
|
1346 | 1358 | else: |
|
1347 | 1359 | tmpname = tempfile.mktemp('.txt') |
|
1348 | 1360 | tmpfile = file(tmpname,'wt') |
|
1349 | 1361 | tmpfile.write(strng) |
|
1350 | 1362 | tmpfile.close() |
|
1351 | 1363 | cmd = "%s < %s" % (pager_cmd,tmpname) |
|
1352 | 1364 | if os.system(cmd): |
|
1353 | 1365 | retval = 1 |
|
1354 | 1366 | else: |
|
1355 | 1367 | retval = None |
|
1356 | 1368 | os.remove(tmpname) |
|
1357 | 1369 | else: |
|
1358 | 1370 | try: |
|
1359 | 1371 | retval = None |
|
1360 | 1372 | # if I use popen4, things hang. No idea why. |
|
1361 | 1373 | #pager,shell_out = os.popen4(pager_cmd) |
|
1362 | 1374 | pager = os.popen(pager_cmd,'w') |
|
1363 | 1375 | pager.write(strng) |
|
1364 | 1376 | pager.close() |
|
1365 | 1377 | retval = pager.close() # success returns None |
|
1366 | 1378 | except IOError,msg: # broken pipe when user quits |
|
1367 | 1379 | if msg.args == (32,'Broken pipe'): |
|
1368 | 1380 | retval = None |
|
1369 | 1381 | else: |
|
1370 | 1382 | retval = 1 |
|
1371 | 1383 | except OSError: |
|
1372 | 1384 | # Other strange problems, sometimes seen in Win2k/cygwin |
|
1373 | 1385 | retval = 1 |
|
1374 | 1386 | if retval is not None: |
|
1375 | 1387 | page_dumb(strng,screen_lines=screen_lines) |
|
1376 | 1388 | |
|
1377 | 1389 | #---------------------------------------------------------------------------- |
|
1378 | 1390 | def page_file(fname,start = 0, pager_cmd = None): |
|
1379 | 1391 | """Page a file, using an optional pager command and starting line. |
|
1380 | 1392 | """ |
|
1381 | 1393 | |
|
1382 | 1394 | pager_cmd = get_pager_cmd(pager_cmd) |
|
1383 | 1395 | pager_cmd += ' ' + get_pager_start(pager_cmd,start) |
|
1384 | 1396 | |
|
1385 | 1397 | try: |
|
1386 | 1398 | if os.environ['TERM'] in ['emacs','dumb']: |
|
1387 | 1399 | raise EnvironmentError |
|
1388 | 1400 | xsys(pager_cmd + ' ' + fname) |
|
1389 | 1401 | except: |
|
1390 | 1402 | try: |
|
1391 | 1403 | if start > 0: |
|
1392 | 1404 | start -= 1 |
|
1393 | 1405 | page(open(fname).read(),start) |
|
1394 | 1406 | except: |
|
1395 | 1407 | print 'Unable to show file',`fname` |
|
1396 | 1408 | |
|
1397 | 1409 | #---------------------------------------------------------------------------- |
|
1398 | 1410 | def snip_print(str,width = 75,print_full = 0,header = ''): |
|
1399 | 1411 | """Print a string snipping the midsection to fit in width. |
|
1400 | 1412 | |
|
1401 | 1413 | print_full: mode control: |
|
1402 | 1414 | - 0: only snip long strings |
|
1403 | 1415 | - 1: send to page() directly. |
|
1404 | 1416 | - 2: snip long strings and ask for full length viewing with page() |
|
1405 | 1417 | Return 1 if snipping was necessary, 0 otherwise.""" |
|
1406 | 1418 | |
|
1407 | 1419 | if print_full == 1: |
|
1408 | 1420 | page(header+str) |
|
1409 | 1421 | return 0 |
|
1410 | 1422 | |
|
1411 | 1423 | print header, |
|
1412 | 1424 | if len(str) < width: |
|
1413 | 1425 | print str |
|
1414 | 1426 | snip = 0 |
|
1415 | 1427 | else: |
|
1416 | 1428 | whalf = int((width -5)/2) |
|
1417 | 1429 | print str[:whalf] + ' <...> ' + str[-whalf:] |
|
1418 | 1430 | snip = 1 |
|
1419 | 1431 | if snip and print_full == 2: |
|
1420 | 1432 | if raw_input(header+' Snipped. View (y/n)? [N]').lower() == 'y': |
|
1421 | 1433 | page(str) |
|
1422 | 1434 | return snip |
|
1423 | 1435 | |
|
1424 | 1436 | #**************************************************************************** |
|
1425 | 1437 | # lists, dicts and structures |
|
1426 | 1438 | |
|
1427 | 1439 | def belong(candidates,checklist): |
|
1428 | 1440 | """Check whether a list of items appear in a given list of options. |
|
1429 | 1441 | |
|
1430 | 1442 | Returns a list of 1 and 0, one for each candidate given.""" |
|
1431 | 1443 | |
|
1432 | 1444 | return [x in checklist for x in candidates] |
|
1433 | 1445 | |
|
1434 | 1446 | #---------------------------------------------------------------------------- |
|
1435 | 1447 | def uniq_stable(elems): |
|
1436 | 1448 | """uniq_stable(elems) -> list |
|
1437 | 1449 | |
|
1438 | 1450 | Return from an iterable, a list of all the unique elements in the input, |
|
1439 | 1451 | but maintaining the order in which they first appear. |
|
1440 | 1452 | |
|
1441 | 1453 | A naive solution to this problem which just makes a dictionary with the |
|
1442 | 1454 | elements as keys fails to respect the stability condition, since |
|
1443 | 1455 | dictionaries are unsorted by nature. |
|
1444 | 1456 | |
|
1445 | 1457 | Note: All elements in the input must be valid dictionary keys for this |
|
1446 | 1458 | routine to work, as it internally uses a dictionary for efficiency |
|
1447 | 1459 | reasons.""" |
|
1448 | 1460 | |
|
1449 | 1461 | unique = [] |
|
1450 | 1462 | unique_dict = {} |
|
1451 | 1463 | for nn in elems: |
|
1452 | 1464 | if nn not in unique_dict: |
|
1453 | 1465 | unique.append(nn) |
|
1454 | 1466 | unique_dict[nn] = None |
|
1455 | 1467 | return unique |
|
1456 | 1468 | |
|
1457 | 1469 | #---------------------------------------------------------------------------- |
|
1458 | 1470 | class NLprinter: |
|
1459 | 1471 | """Print an arbitrarily nested list, indicating index numbers. |
|
1460 | 1472 | |
|
1461 | 1473 | An instance of this class called nlprint is available and callable as a |
|
1462 | 1474 | function. |
|
1463 | 1475 | |
|
1464 | 1476 | nlprint(list,indent=' ',sep=': ') -> prints indenting each level by 'indent' |
|
1465 | 1477 | and using 'sep' to separate the index from the value. """ |
|
1466 | 1478 | |
|
1467 | 1479 | def __init__(self): |
|
1468 | 1480 | self.depth = 0 |
|
1469 | 1481 | |
|
1470 | 1482 | def __call__(self,lst,pos='',**kw): |
|
1471 | 1483 | """Prints the nested list numbering levels.""" |
|
1472 | 1484 | kw.setdefault('indent',' ') |
|
1473 | 1485 | kw.setdefault('sep',': ') |
|
1474 | 1486 | kw.setdefault('start',0) |
|
1475 | 1487 | kw.setdefault('stop',len(lst)) |
|
1476 | 1488 | # we need to remove start and stop from kw so they don't propagate |
|
1477 | 1489 | # into a recursive call for a nested list. |
|
1478 | 1490 | start = kw['start']; del kw['start'] |
|
1479 | 1491 | stop = kw['stop']; del kw['stop'] |
|
1480 | 1492 | if self.depth == 0 and 'header' in kw.keys(): |
|
1481 | 1493 | print kw['header'] |
|
1482 | 1494 | |
|
1483 | 1495 | for idx in range(start,stop): |
|
1484 | 1496 | elem = lst[idx] |
|
1485 | 1497 | if type(elem)==type([]): |
|
1486 | 1498 | self.depth += 1 |
|
1487 | 1499 | self.__call__(elem,itpl('$pos$idx,'),**kw) |
|
1488 | 1500 | self.depth -= 1 |
|
1489 | 1501 | else: |
|
1490 | 1502 | printpl(kw['indent']*self.depth+'$pos$idx$kw["sep"]$elem') |
|
1491 | 1503 | |
|
1492 | 1504 | nlprint = NLprinter() |
|
1493 | 1505 | #---------------------------------------------------------------------------- |
|
1494 | 1506 | def all_belong(candidates,checklist): |
|
1495 | 1507 | """Check whether a list of items ALL appear in a given list of options. |
|
1496 | 1508 | |
|
1497 | 1509 | Returns a single 1 or 0 value.""" |
|
1498 | 1510 | |
|
1499 | 1511 | return 1-(0 in [x in checklist for x in candidates]) |
|
1500 | 1512 | |
|
1501 | 1513 | #---------------------------------------------------------------------------- |
|
1502 | 1514 | def sort_compare(lst1,lst2,inplace = 1): |
|
1503 | 1515 | """Sort and compare two lists. |
|
1504 | 1516 | |
|
1505 | 1517 | By default it does it in place, thus modifying the lists. Use inplace = 0 |
|
1506 | 1518 | to avoid that (at the cost of temporary copy creation).""" |
|
1507 | 1519 | if not inplace: |
|
1508 | 1520 | lst1 = lst1[:] |
|
1509 | 1521 | lst2 = lst2[:] |
|
1510 | 1522 | lst1.sort(); lst2.sort() |
|
1511 | 1523 | return lst1 == lst2 |
|
1512 | 1524 | |
|
1513 | 1525 | #---------------------------------------------------------------------------- |
|
1514 | 1526 | def mkdict(**kwargs): |
|
1515 | 1527 | """Return a dict from a keyword list. |
|
1516 | 1528 | |
|
1517 | 1529 | It's just syntactic sugar for making ditcionary creation more convenient: |
|
1518 | 1530 | # the standard way |
|
1519 | 1531 | >>>data = { 'red' : 1, 'green' : 2, 'blue' : 3 } |
|
1520 | 1532 | # a cleaner way |
|
1521 | 1533 | >>>data = dict(red=1, green=2, blue=3) |
|
1522 | 1534 | |
|
1523 | 1535 | If you need more than this, look at the Struct() class.""" |
|
1524 | 1536 | |
|
1525 | 1537 | return kwargs |
|
1526 | 1538 | |
|
1527 | 1539 | #---------------------------------------------------------------------------- |
|
1528 | 1540 | def list2dict(lst): |
|
1529 | 1541 | """Takes a list of (key,value) pairs and turns it into a dict.""" |
|
1530 | 1542 | |
|
1531 | 1543 | dic = {} |
|
1532 | 1544 | for k,v in lst: dic[k] = v |
|
1533 | 1545 | return dic |
|
1534 | 1546 | |
|
1535 | 1547 | #---------------------------------------------------------------------------- |
|
1536 | 1548 | def list2dict2(lst,default=''): |
|
1537 | 1549 | """Takes a list and turns it into a dict. |
|
1538 | 1550 | Much slower than list2dict, but more versatile. This version can take |
|
1539 | 1551 | lists with sublists of arbitrary length (including sclars).""" |
|
1540 | 1552 | |
|
1541 | 1553 | dic = {} |
|
1542 | 1554 | for elem in lst: |
|
1543 | 1555 | if type(elem) in (types.ListType,types.TupleType): |
|
1544 | 1556 | size = len(elem) |
|
1545 | 1557 | if size == 0: |
|
1546 | 1558 | pass |
|
1547 | 1559 | elif size == 1: |
|
1548 | 1560 | dic[elem] = default |
|
1549 | 1561 | else: |
|
1550 | 1562 | k,v = elem[0], elem[1:] |
|
1551 | 1563 | if len(v) == 1: v = v[0] |
|
1552 | 1564 | dic[k] = v |
|
1553 | 1565 | else: |
|
1554 | 1566 | dic[elem] = default |
|
1555 | 1567 | return dic |
|
1556 | 1568 | |
|
1557 | 1569 | #---------------------------------------------------------------------------- |
|
1558 | 1570 | def flatten(seq): |
|
1559 | 1571 | """Flatten a list of lists (NOT recursive, only works for 2d lists).""" |
|
1560 | 1572 | |
|
1561 | 1573 | return [x for subseq in seq for x in subseq] |
|
1562 | 1574 | |
|
1563 | 1575 | #---------------------------------------------------------------------------- |
|
1564 | 1576 | def get_slice(seq,start=0,stop=None,step=1): |
|
1565 | 1577 | """Get a slice of a sequence with variable step. Specify start,stop,step.""" |
|
1566 | 1578 | if stop == None: |
|
1567 | 1579 | stop = len(seq) |
|
1568 | 1580 | item = lambda i: seq[i] |
|
1569 | 1581 | return map(item,xrange(start,stop,step)) |
|
1570 | 1582 | |
|
1571 | 1583 | #---------------------------------------------------------------------------- |
|
1572 | 1584 | def chop(seq,size): |
|
1573 | 1585 | """Chop a sequence into chunks of the given size.""" |
|
1574 | 1586 | chunk = lambda i: seq[i:i+size] |
|
1575 | 1587 | return map(chunk,xrange(0,len(seq),size)) |
|
1576 | 1588 | |
|
1577 | 1589 | #---------------------------------------------------------------------------- |
|
1578 | 1590 | # with is a keyword as of python 2.5, so this function is renamed to withobj |
|
1579 | 1591 | # from its old 'with' name. |
|
1580 | 1592 | def with_obj(object, **args): |
|
1581 | 1593 | """Set multiple attributes for an object, similar to Pascal's with. |
|
1582 | 1594 | |
|
1583 | 1595 | Example: |
|
1584 | 1596 | with_obj(jim, |
|
1585 | 1597 | born = 1960, |
|
1586 | 1598 | haircolour = 'Brown', |
|
1587 | 1599 | eyecolour = 'Green') |
|
1588 | 1600 | |
|
1589 | 1601 | Credit: Greg Ewing, in |
|
1590 | 1602 | http://mail.python.org/pipermail/python-list/2001-May/040703.html. |
|
1591 | 1603 | |
|
1592 | 1604 | NOTE: up until IPython 0.7.2, this was called simply 'with', but 'with' |
|
1593 | 1605 | has become a keyword for Python 2.5, so we had to rename it.""" |
|
1594 | 1606 | |
|
1595 | 1607 | object.__dict__.update(args) |
|
1596 | 1608 | |
|
1597 | 1609 | #---------------------------------------------------------------------------- |
|
1598 | 1610 | def setattr_list(obj,alist,nspace = None): |
|
1599 | 1611 | """Set a list of attributes for an object taken from a namespace. |
|
1600 | 1612 | |
|
1601 | 1613 | setattr_list(obj,alist,nspace) -> sets in obj all the attributes listed in |
|
1602 | 1614 | alist with their values taken from nspace, which must be a dict (something |
|
1603 | 1615 | like locals() will often do) If nspace isn't given, locals() of the |
|
1604 | 1616 | *caller* is used, so in most cases you can omit it. |
|
1605 | 1617 | |
|
1606 | 1618 | Note that alist can be given as a string, which will be automatically |
|
1607 | 1619 | split into a list on whitespace. If given as a list, it must be a list of |
|
1608 | 1620 | *strings* (the variable names themselves), not of variables.""" |
|
1609 | 1621 | |
|
1610 | 1622 | # this grabs the local variables from the *previous* call frame -- that is |
|
1611 | 1623 | # the locals from the function that called setattr_list(). |
|
1612 | 1624 | # - snipped from weave.inline() |
|
1613 | 1625 | if nspace is None: |
|
1614 | 1626 | call_frame = sys._getframe().f_back |
|
1615 | 1627 | nspace = call_frame.f_locals |
|
1616 | 1628 | |
|
1617 | 1629 | if type(alist) in StringTypes: |
|
1618 | 1630 | alist = alist.split() |
|
1619 | 1631 | for attr in alist: |
|
1620 | 1632 | val = eval(attr,nspace) |
|
1621 | 1633 | setattr(obj,attr,val) |
|
1622 | 1634 | |
|
1623 | 1635 | #---------------------------------------------------------------------------- |
|
1624 | 1636 | def getattr_list(obj,alist,*args): |
|
1625 | 1637 | """getattr_list(obj,alist[, default]) -> attribute list. |
|
1626 | 1638 | |
|
1627 | 1639 | Get a list of named attributes for an object. When a default argument is |
|
1628 | 1640 | given, it is returned when the attribute doesn't exist; without it, an |
|
1629 | 1641 | exception is raised in that case. |
|
1630 | 1642 | |
|
1631 | 1643 | Note that alist can be given as a string, which will be automatically |
|
1632 | 1644 | split into a list on whitespace. If given as a list, it must be a list of |
|
1633 | 1645 | *strings* (the variable names themselves), not of variables.""" |
|
1634 | 1646 | |
|
1635 | 1647 | if type(alist) in StringTypes: |
|
1636 | 1648 | alist = alist.split() |
|
1637 | 1649 | if args: |
|
1638 | 1650 | if len(args)==1: |
|
1639 | 1651 | default = args[0] |
|
1640 | 1652 | return map(lambda attr: getattr(obj,attr,default),alist) |
|
1641 | 1653 | else: |
|
1642 | 1654 | raise ValueError,'getattr_list() takes only one optional argument' |
|
1643 | 1655 | else: |
|
1644 | 1656 | return map(lambda attr: getattr(obj,attr),alist) |
|
1645 | 1657 | |
|
1646 | 1658 | #---------------------------------------------------------------------------- |
|
1647 | 1659 | def map_method(method,object_list,*argseq,**kw): |
|
1648 | 1660 | """map_method(method,object_list,*args,**kw) -> list |
|
1649 | 1661 | |
|
1650 | 1662 | Return a list of the results of applying the methods to the items of the |
|
1651 | 1663 | argument sequence(s). If more than one sequence is given, the method is |
|
1652 | 1664 | called with an argument list consisting of the corresponding item of each |
|
1653 | 1665 | sequence. All sequences must be of the same length. |
|
1654 | 1666 | |
|
1655 | 1667 | Keyword arguments are passed verbatim to all objects called. |
|
1656 | 1668 | |
|
1657 | 1669 | This is Python code, so it's not nearly as fast as the builtin map().""" |
|
1658 | 1670 | |
|
1659 | 1671 | out_list = [] |
|
1660 | 1672 | idx = 0 |
|
1661 | 1673 | for object in object_list: |
|
1662 | 1674 | try: |
|
1663 | 1675 | handler = getattr(object, method) |
|
1664 | 1676 | except AttributeError: |
|
1665 | 1677 | out_list.append(None) |
|
1666 | 1678 | else: |
|
1667 | 1679 | if argseq: |
|
1668 | 1680 | args = map(lambda lst:lst[idx],argseq) |
|
1669 | 1681 | #print 'ob',object,'hand',handler,'ar',args # dbg |
|
1670 | 1682 | out_list.append(handler(args,**kw)) |
|
1671 | 1683 | else: |
|
1672 | 1684 | out_list.append(handler(**kw)) |
|
1673 | 1685 | idx += 1 |
|
1674 | 1686 | return out_list |
|
1675 | 1687 | |
|
1676 | 1688 | #---------------------------------------------------------------------------- |
|
1677 | 1689 | def import_fail_info(mod_name,fns=None): |
|
1678 | 1690 | """Inform load failure for a module.""" |
|
1679 | 1691 | |
|
1680 | 1692 | if fns == None: |
|
1681 | 1693 | warn("Loading of %s failed.\n" % (mod_name,)) |
|
1682 | 1694 | else: |
|
1683 | 1695 | warn("Loading of %s from %s failed.\n" % (fns,mod_name)) |
|
1684 | 1696 | |
|
1685 | 1697 | #---------------------------------------------------------------------------- |
|
1686 | 1698 | # Proposed popitem() extension, written as a method |
|
1687 | 1699 | |
|
1688 | 1700 | class NotGiven: pass |
|
1689 | 1701 | |
|
1690 | 1702 | def popkey(dct,key,default=NotGiven): |
|
1691 | 1703 | """Return dct[key] and delete dct[key]. |
|
1692 | 1704 | |
|
1693 | 1705 | If default is given, return it if dct[key] doesn't exist, otherwise raise |
|
1694 | 1706 | KeyError. """ |
|
1695 | 1707 | |
|
1696 | 1708 | try: |
|
1697 | 1709 | val = dct[key] |
|
1698 | 1710 | except KeyError: |
|
1699 | 1711 | if default is NotGiven: |
|
1700 | 1712 | raise |
|
1701 | 1713 | else: |
|
1702 | 1714 | return default |
|
1703 | 1715 | else: |
|
1704 | 1716 | del dct[key] |
|
1705 | 1717 | return val |
|
1706 | 1718 | #*************************** end of file <genutils.py> ********************** |
|
1707 | 1719 |
General Comments 0
You need to be logged in to leave comments.
Login now