##// END OF EJS Templates
Merge pull request #2882 from takluyver/utils-cleanup...
Bussonnier Matthias -
r9486:a3c4e796 merge
parent child Browse files
Show More
@@ -27,7 +27,6 b' from IPython.core.oinspect import find_file, find_source_lines'
27 27 from IPython.testing.skipdoctest import skip_doctest
28 28 from IPython.utils import py3compat
29 29 from IPython.utils.contexts import preserve_keys
30 from IPython.utils.io import file_read
31 30 from IPython.utils.path import get_py_filename, unquote_filename
32 31 from IPython.utils.warn import warn
33 32
@@ -531,7 +530,8 b' class CodeMagics(Magics):'
531 530 # XXX TODO: should this be generalized for all string vars?
532 531 # For now, this is special-cased to blocks created by cpaste
533 532 if args.strip() == 'pasted_block':
534 self.shell.user_ns['pasted_block'] = file_read(filename)
533 with open(filename, 'r') as f:
534 self.shell.user_ns['pasted_block'] = f.read()
535 535
536 536 if 'x' in opts: # -x prevents actual execution
537 537 print
@@ -541,8 +541,9 b' class CodeMagics(Magics):'
541 541 if not is_temp:
542 542 self.shell.user_ns['__file__'] = filename
543 543 if 'r' in opts: # Untranslated IPython code
544 self.shell.run_cell(file_read(filename),
545 store_history=False)
544 with open(filename, 'r') as f:
545 source = f.read()
546 self.shell.run_cell(source, store_history=False)
546 547 else:
547 548 self.shell.safe_execfile(filename, self.shell.user_ns,
548 549 self.shell.user_ns)
@@ -31,7 +31,6 b' from IPython.core.magic import ('
31 31 Magics, compress_dhist, magics_class, line_magic, cell_magic, line_cell_magic
32 32 )
33 33 from IPython.testing.skipdoctest import skip_doctest
34 from IPython.utils.io import nlprint
35 34 from IPython.utils.openpy import source_to_unicode
36 35 from IPython.utils.path import unquote_filename
37 36 from IPython.utils.process import abbrev_cwd
@@ -403,7 +402,7 b' class OSMagics(Magics):'
403 402
404 403 %dhist -> print full history\\
405 404 %dhist n -> print last n entries only\\
406 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
405 %dhist n1 n2 -> print entries between n1 and n2 (n2 not included)\\
407 406
408 407 This history is automatically maintained by the %cd command, and
409 408 always available as the global list variable _dh. You can use %cd -<n>
@@ -425,14 +424,15 b' class OSMagics(Magics):'
425 424 ini,fin = max(len(dh)-(args[0]),0),len(dh)
426 425 elif len(args) == 2:
427 426 ini,fin = args
427 fin = min(fin, len(dh))
428 428 else:
429 429 self.arg_err(self.dhist)
430 430 return
431 431 else:
432 432 ini,fin = 0,len(dh)
433 nlprint(dh,
434 header = 'Directory history (kept in _dh)',
435 start=ini,stop=fin)
433 print 'Directory history (kept in _dh)'
434 for i in range(ini, fin):
435 print "%d: %s" % (i, dh[i])
436 436
437 437 @skip_doctest
438 438 @line_magic
@@ -104,9 +104,9 b' from IPython.core.display_trap import DisplayTrap'
104 104 from IPython.core.excolors import exception_colors
105 105 from IPython.utils import PyColorize
106 106 from IPython.utils import io
107 from IPython.utils import openpy
107 108 from IPython.utils import path as util_path
108 109 from IPython.utils import py3compat
109 from IPython.utils import pyfile
110 110 from IPython.utils import ulinecache
111 111 from IPython.utils.data import uniq_stable
112 112 from IPython.utils.warn import info, error
@@ -837,7 +837,7 b' class VerboseTB(TBTools):'
837 837 continue
838 838 elif file.endswith(('.pyc','.pyo')):
839 839 # Look up the corresponding source file.
840 file = pyfile.source_from_cache(file)
840 file = openpy.source_from_cache(file)
841 841
842 842 def linereader(file=file, lnum=[lnum], getline=ulinecache.getline):
843 843 line = getline(file, lnum[0])
@@ -119,7 +119,7 b' try:'
119 119 except NameError:
120 120 from imp import reload
121 121
122 from IPython.utils import pyfile
122 from IPython.utils import openpy
123 123 from IPython.utils.py3compat import PY3
124 124
125 125 #------------------------------------------------------------------------------
@@ -207,12 +207,12 b' class ModuleReloader(object):'
207 207 path, ext = os.path.splitext(filename)
208 208
209 209 if ext.lower() == '.py':
210 pyc_filename = pyfile.cache_from_source(filename)
210 pyc_filename = openpy.cache_from_source(filename)
211 211 py_filename = filename
212 212 else:
213 213 pyc_filename = filename
214 214 try:
215 py_filename = pyfile.source_from_cache(filename)
215 py_filename = openpy.source_from_cache(filename)
216 216 except ValueError:
217 217 continue
218 218
@@ -184,7 +184,6 b' import shlex'
184 184 import sys
185 185
186 186 from IPython.utils import io
187 from IPython.utils.io import file_read
188 187 from IPython.utils.text import marquee
189 188 from IPython.utils import openpy
190 189 __all__ = ['Demo','IPythonDemo','LineDemo','IPythonLineDemo','DemoError']
@@ -380,7 +379,8 b' class Demo(object):'
380 379
381 380 filename = self.shell.mktempfile(self.src_blocks[index])
382 381 self.shell.hooks.editor(filename,1)
383 new_block = file_read(filename)
382 with open(filename, 'r') as f:
383 new_block = f.read()
384 384 # update the source and colored block
385 385 self.src_blocks[index] = new_block
386 386 self.src_blocks_colored[index] = self.ip_colorize(new_block)
@@ -22,7 +22,6 b' import sys'
22 22 from IPython.external import pexpect
23 23
24 24 # Our own
25 from .autoattr import auto_attr
26 25 from ._process_common import getoutput, arg_split
27 26 from IPython.utils import py3compat
28 27 from IPython.utils.encoding import DEFAULT_ENCODING
@@ -55,14 +54,16 b' class ProcessHandler(object):'
55 54 logfile = None
56 55
57 56 # Shell to call for subprocesses to execute
58 sh = None
57 _sh = None
59 58
60 @auto_attr
59 @property
61 60 def sh(self):
62 sh = pexpect.which('sh')
63 if sh is None:
61 if self._sh is None:
62 self._sh = pexpect.which('sh')
63 if self._sh is None:
64 64 raise OSError('"sh" shell not found')
65 return sh
65
66 return self._sh
66 67
67 68 def __init__(self, logfile=None, read_timeout=None, terminate_timeout=None):
68 69 """Arguments are used for pexpect calls."""
@@ -9,16 +9,6 b''
9 9 # the file COPYING, distributed as part of this software.
10 10 #-----------------------------------------------------------------------------
11 11
12 #-----------------------------------------------------------------------------
13 # Imports
14 #-----------------------------------------------------------------------------
15
16 import types
17
18 #-----------------------------------------------------------------------------
19 # Code
20 #-----------------------------------------------------------------------------
21
22 12 def uniq_stable(elems):
23 13 """uniq_stable(elems) -> list
24 14
@@ -32,65 +22,14 b' def uniq_stable(elems):'
32 22 return [x for x in elems if x not in seen and not seen.add(x)]
33 23
34 24
35 def sort_compare(lst1, lst2, inplace=1):
36 """Sort and compare two lists.
37
38 By default it does it in place, thus modifying the lists. Use inplace = 0
39 to avoid that (at the cost of temporary copy creation)."""
40 if not inplace:
41 lst1 = lst1[:]
42 lst2 = lst2[:]
43 lst1.sort(); lst2.sort()
44 return lst1 == lst2
45
46
47 def list2dict(lst):
48 """Takes a list of (key,value) pairs and turns it into a dict."""
49
50 dic = {}
51 for k,v in lst: dic[k] = v
52 return dic
53
54
55 def list2dict2(lst, default=''):
56 """Takes a list and turns it into a dict.
57 Much slower than list2dict, but more versatile. This version can take
58 lists with sublists of arbitrary length (including sclars)."""
59
60 dic = {}
61 for elem in lst:
62 if type(elem) in (types.ListType,types.TupleType):
63 size = len(elem)
64 if size == 0:
65 pass
66 elif size == 1:
67 dic[elem] = default
68 else:
69 k,v = elem[0], elem[1:]
70 if len(v) == 1: v = v[0]
71 dic[k] = v
72 else:
73 dic[elem] = default
74 return dic
75
76
77 25 def flatten(seq):
78 26 """Flatten a list of lists (NOT recursive, only works for 2d lists)."""
79 27
80 28 return [x for subseq in seq for x in subseq]
81 29
82 30
83 def get_slice(seq, start=0, stop=None, step=1):
84 """Get a slice of a sequence with variable step. Specify start,stop,step."""
85 if stop == None:
86 stop = len(seq)
87 item = lambda i: seq[i]
88 return map(item,xrange(start,stop,step))
89
90
91 31 def chop(seq, size):
92 32 """Chop a sequence into chunks of the given size."""
93 chunk = lambda i: seq[i:i+size]
94 return map(chunk,xrange(0,len(seq),size))
33 return [seq[i:i+size] for i in xrange(0,len(seq),size)]
95 34
96 35
@@ -154,64 +154,6 b' class Tee(object):'
154 154 self.close()
155 155
156 156
157 def file_read(filename):
158 """Read a file and close it. Returns the file source."""
159 fobj = open(filename,'r');
160 source = fobj.read();
161 fobj.close()
162 return source
163
164
165 def file_readlines(filename):
166 """Read a file and close it. Returns the file source using readlines()."""
167 fobj = open(filename,'r');
168 lines = fobj.readlines();
169 fobj.close()
170 return lines
171
172
173 def raw_input_multi(header='', ps1='==> ', ps2='..> ',terminate_str = '.'):
174 """Take multiple lines of input.
175
176 A list with each line of input as a separate element is returned when a
177 termination string is entered (defaults to a single '.'). Input can also
178 terminate via EOF (^D in Unix, ^Z-RET in Windows).
179
180 Lines of input which end in \\ are joined into single entries (and a
181 secondary continuation prompt is issued as long as the user terminates
182 lines with \\). This allows entering very long strings which are still
183 meant to be treated as single entities.
184 """
185
186 try:
187 if header:
188 header += '\n'
189 lines = [raw_input(header + ps1)]
190 except EOFError:
191 return []
192 terminate = [terminate_str]
193 try:
194 while lines[-1:] != terminate:
195 new_line = raw_input(ps1)
196 while new_line.endswith('\\'):
197 new_line = new_line[:-1] + raw_input(ps2)
198 lines.append(new_line)
199
200 return lines[:-1] # don't return the termination command
201 except EOFError:
202 print()
203 return lines
204
205
206 def raw_input_ext(prompt='', ps2='... '):
207 """Similar to raw_input(), but accepts extended lines if input ends with \\."""
208
209 line = raw_input(prompt)
210 while line.endswith('\\'):
211 line = line[:-1] + raw_input(ps2)
212 return line
213
214
215 157 def ask_yes_no(prompt,default=None):
216 158 """Asks a question and returns a boolean (y/n) answer.
217 159
@@ -242,44 +184,6 b' def ask_yes_no(prompt,default=None):'
242 184 return answers[ans]
243 185
244 186
245 class NLprinter:
246 """Print an arbitrarily nested list, indicating index numbers.
247
248 An instance of this class called nlprint is available and callable as a
249 function.
250
251 nlprint(list,indent=' ',sep=': ') -> prints indenting each level by 'indent'
252 and using 'sep' to separate the index from the value. """
253
254 def __init__(self):
255 self.depth = 0
256
257 def __call__(self,lst,pos='',**kw):
258 """Prints the nested list numbering levels."""
259 kw.setdefault('indent',' ')
260 kw.setdefault('sep',': ')
261 kw.setdefault('start',0)
262 kw.setdefault('stop',len(lst))
263 # we need to remove start and stop from kw so they don't propagate
264 # into a recursive call for a nested list.
265 start = kw['start']; del kw['start']
266 stop = kw['stop']; del kw['stop']
267 if self.depth == 0 and 'header' in kw.keys():
268 print(kw['header'])
269
270 for idx in range(start,stop):
271 elem = lst[idx]
272 newpos = pos + str(idx)
273 if type(elem)==type([]):
274 self.depth += 1
275 self.__call__(elem, newpos+",", **kw)
276 self.depth -= 1
277 else:
278 print(kw['indent']*self.depth + newpos + kw["sep"] + repr(elem))
279
280 nlprint = NLprinter()
281
282
283 187 def temp_pyfile(src, ext='.py'):
284 188 """Make a temporary python file, return filename and filehandle.
285 189
@@ -18,8 +18,6 b' Authors:'
18 18 # Imports
19 19 #-----------------------------------------------------------------------------
20 20
21 from IPython.utils.data import list2dict2
22
23 21 __all__ = ['Struct']
24 22
25 23 #-----------------------------------------------------------------------------
@@ -370,7 +368,7 b' class Struct(dict):'
370 368 add_s = lambda old,new: old + ' ' + new
371 369
372 370 # default policy is to keep current keys when there's a conflict
373 conflict_solve = list2dict2(self.keys(), default = preserve)
371 conflict_solve = dict.fromkeys(self, preserve)
374 372
375 373 # the conflict_solve dictionary is given by the user 'inverted': we
376 374 # need a name-function mapping, it comes as a function -> names
@@ -8,6 +8,7 b' from __future__ import absolute_import'
8 8
9 9 import io
10 10 from io import TextIOWrapper, BytesIO
11 import os.path
11 12 import re
12 13
13 14 cookie_re = re.compile(ur"coding[:=]\s*([-\w.]+)", re.UNICODE)
@@ -217,3 +218,22 b' def _list_readline(x):'
217 218 def readline():
218 219 return next(x)
219 220 return readline
221
222 # Code for going between .py files and cached .pyc files ----------------------
223
224 try: # Python 3.2, see PEP 3147
225 from imp import source_from_cache, cache_from_source
226 except ImportError:
227 # Python <= 3.1: .pyc files go next to .py
228 def source_from_cache(path):
229 basename, ext = os.path.splitext(path)
230 if ext not in ('.pyc', '.pyo'):
231 raise ValueError('Not a cached Python file extension', ext)
232 # Should we look for .pyw files?
233 return basename + '.py'
234
235 def cache_from_source(path, debug_override=None):
236 if debug_override is None:
237 debug_override = __debug__
238 basename, ext = os.path.splitext(path)
239 return basename + '.pyc' if debug_override else '.pyo'
@@ -30,25 +30,12 b' from string import Formatter'
30 30 from IPython.external.path import path
31 31 from IPython.testing.skipdoctest import skip_doctest_py3, skip_doctest
32 32 from IPython.utils import py3compat
33 from IPython.utils.io import nlprint
34 33 from IPython.utils.data import flatten
35 34
36 35 #-----------------------------------------------------------------------------
37 36 # Code
38 37 #-----------------------------------------------------------------------------
39 38
40 def unquote_ends(istr):
41 """Remove a single pair of quotes from the endpoints of a string."""
42
43 if not istr:
44 return istr
45 if (istr[0]=="'" and istr[-1]=="'") or \
46 (istr[0]=='"' and istr[-1]=='"'):
47 return istr[1:-1]
48 else:
49 return istr
50
51
52 39 class LSString(str):
53 40 """String derivative with a special access attributes.
54 41
@@ -265,105 +252,11 b' class SList(list):'
265 252 # arg.hideonce = False
266 253 # return
267 254 #
268 # nlprint(arg)
255 # nlprint(arg) # This was a nested list printer, now removed.
269 256 #
270 257 # print_slist = result_display.when_type(SList)(print_slist)
271 258
272 259
273 def esc_quotes(strng):
274 """Return the input string with single and double quotes escaped out"""
275
276 return strng.replace('"','\\"').replace("'","\\'")
277
278
279 def qw(words,flat=0,sep=None,maxsplit=-1):
280 """Similar to Perl's qw() operator, but with some more options.
281
282 qw(words,flat=0,sep=' ',maxsplit=-1) -> words.split(sep,maxsplit)
283
284 words can also be a list itself, and with flat=1, the output will be
285 recursively flattened.
286
287 Examples:
288
289 >>> qw('1 2')
290 ['1', '2']
291
292 >>> qw(['a b','1 2',['m n','p q']])
293 [['a', 'b'], ['1', '2'], [['m', 'n'], ['p', 'q']]]
294
295 >>> qw(['a b','1 2',['m n','p q']],flat=1)
296 ['a', 'b', '1', '2', 'm', 'n', 'p', 'q']
297 """
298
299 if isinstance(words, basestring):
300 return [word.strip() for word in words.split(sep,maxsplit)
301 if word and not word.isspace() ]
302 if flat:
303 return flatten(map(qw,words,[1]*len(words)))
304 return map(qw,words)
305
306
307 def qwflat(words,sep=None,maxsplit=-1):
308 """Calls qw(words) in flat mode. It's just a convenient shorthand."""
309 return qw(words,1,sep,maxsplit)
310
311
312 def qw_lol(indata):
313 """qw_lol('a b') -> [['a','b']],
314 otherwise it's just a call to qw().
315
316 We need this to make sure the modules_some keys *always* end up as a
317 list of lists."""
318
319 if isinstance(indata, basestring):
320 return [qw(indata)]
321 else:
322 return qw(indata)
323
324
325 def grep(pat,list,case=1):
326 """Simple minded grep-like function.
327 grep(pat,list) returns occurrences of pat in list, None on failure.
328
329 It only does simple string matching, with no support for regexps. Use the
330 option case=0 for case-insensitive matching."""
331
332 # This is pretty crude. At least it should implement copying only references
333 # to the original data in case it's big. Now it copies the data for output.
334 out=[]
335 if case:
336 for term in list:
337 if term.find(pat)>-1: out.append(term)
338 else:
339 lpat=pat.lower()
340 for term in list:
341 if term.lower().find(lpat)>-1: out.append(term)
342
343 if len(out): return out
344 else: return None
345
346
347 def dgrep(pat,*opts):
348 """Return grep() on dir()+dir(__builtins__).
349
350 A very common use of grep() when working interactively."""
351
352 return grep(pat,dir(__main__)+dir(__main__.__builtins__),*opts)
353
354
355 def idgrep(pat):
356 """Case-insensitive dgrep()"""
357
358 return dgrep(pat,0)
359
360
361 def igrep(pat,list):
362 """Synonym for case-insensitive grep."""
363
364 return grep(pat,list,case=0)
365
366
367 260 def indent(instr,nspaces=4, ntabs=0, flatten=False):
368 261 """Indent a string a given number of spaces or tabstops.
369 262
1 NO CONTENT: file was removed
1 NO CONTENT: file was removed
1 NO CONTENT: file was removed
1 NO CONTENT: file was removed
1 NO CONTENT: file was removed
1 NO CONTENT: file was removed
1 NO CONTENT: file was removed
General Comments 0
You need to be logged in to leave comments. Login now