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