##// 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 from IPython.testing.skipdoctest import skip_doctest
27 from IPython.testing.skipdoctest import skip_doctest
28 from IPython.utils import py3compat
28 from IPython.utils import py3compat
29 from IPython.utils.contexts import preserve_keys
29 from IPython.utils.contexts import preserve_keys
30 from IPython.utils.io import file_read
31 from IPython.utils.path import get_py_filename, unquote_filename
30 from IPython.utils.path import get_py_filename, unquote_filename
32 from IPython.utils.warn import warn
31 from IPython.utils.warn import warn
33
32
@@ -531,7 +530,8 b' class CodeMagics(Magics):'
531 # XXX TODO: should this be generalized for all string vars?
530 # XXX TODO: should this be generalized for all string vars?
532 # For now, this is special-cased to blocks created by cpaste
531 # For now, this is special-cased to blocks created by cpaste
533 if args.strip() == 'pasted_block':
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 if 'x' in opts: # -x prevents actual execution
536 if 'x' in opts: # -x prevents actual execution
537 print
537 print
@@ -541,8 +541,9 b' class CodeMagics(Magics):'
541 if not is_temp:
541 if not is_temp:
542 self.shell.user_ns['__file__'] = filename
542 self.shell.user_ns['__file__'] = filename
543 if 'r' in opts: # Untranslated IPython code
543 if 'r' in opts: # Untranslated IPython code
544 self.shell.run_cell(file_read(filename),
544 with open(filename, 'r') as f:
545 store_history=False)
545 source = f.read()
546 self.shell.run_cell(source, store_history=False)
546 else:
547 else:
547 self.shell.safe_execfile(filename, self.shell.user_ns,
548 self.shell.safe_execfile(filename, self.shell.user_ns,
548 self.shell.user_ns)
549 self.shell.user_ns)
@@ -31,7 +31,6 b' from IPython.core.magic import ('
31 Magics, compress_dhist, magics_class, line_magic, cell_magic, line_cell_magic
31 Magics, compress_dhist, magics_class, line_magic, cell_magic, line_cell_magic
32 )
32 )
33 from IPython.testing.skipdoctest import skip_doctest
33 from IPython.testing.skipdoctest import skip_doctest
34 from IPython.utils.io import nlprint
35 from IPython.utils.openpy import source_to_unicode
34 from IPython.utils.openpy import source_to_unicode
36 from IPython.utils.path import unquote_filename
35 from IPython.utils.path import unquote_filename
37 from IPython.utils.process import abbrev_cwd
36 from IPython.utils.process import abbrev_cwd
@@ -403,7 +402,7 b' class OSMagics(Magics):'
403
402
404 %dhist -> print full history\\
403 %dhist -> print full history\\
405 %dhist n -> print last n entries only\\
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 This history is automatically maintained by the %cd command, and
407 This history is automatically maintained by the %cd command, and
409 always available as the global list variable _dh. You can use %cd -<n>
408 always available as the global list variable _dh. You can use %cd -<n>
@@ -425,14 +424,15 b' class OSMagics(Magics):'
425 ini,fin = max(len(dh)-(args[0]),0),len(dh)
424 ini,fin = max(len(dh)-(args[0]),0),len(dh)
426 elif len(args) == 2:
425 elif len(args) == 2:
427 ini,fin = args
426 ini,fin = args
427 fin = min(fin, len(dh))
428 else:
428 else:
429 self.arg_err(self.dhist)
429 self.arg_err(self.dhist)
430 return
430 return
431 else:
431 else:
432 ini,fin = 0,len(dh)
432 ini,fin = 0,len(dh)
433 nlprint(dh,
433 print 'Directory history (kept in _dh)'
434 header = 'Directory history (kept in _dh)',
434 for i in range(ini, fin):
435 start=ini,stop=fin)
435 print "%d: %s" % (i, dh[i])
436
436
437 @skip_doctest
437 @skip_doctest
438 @line_magic
438 @line_magic
@@ -104,9 +104,9 b' from IPython.core.display_trap import DisplayTrap'
104 from IPython.core.excolors import exception_colors
104 from IPython.core.excolors import exception_colors
105 from IPython.utils import PyColorize
105 from IPython.utils import PyColorize
106 from IPython.utils import io
106 from IPython.utils import io
107 from IPython.utils import openpy
107 from IPython.utils import path as util_path
108 from IPython.utils import path as util_path
108 from IPython.utils import py3compat
109 from IPython.utils import py3compat
109 from IPython.utils import pyfile
110 from IPython.utils import ulinecache
110 from IPython.utils import ulinecache
111 from IPython.utils.data import uniq_stable
111 from IPython.utils.data import uniq_stable
112 from IPython.utils.warn import info, error
112 from IPython.utils.warn import info, error
@@ -837,7 +837,7 b' class VerboseTB(TBTools):'
837 continue
837 continue
838 elif file.endswith(('.pyc','.pyo')):
838 elif file.endswith(('.pyc','.pyo')):
839 # Look up the corresponding source file.
839 # Look up the corresponding source file.
840 file = pyfile.source_from_cache(file)
840 file = openpy.source_from_cache(file)
841
841
842 def linereader(file=file, lnum=[lnum], getline=ulinecache.getline):
842 def linereader(file=file, lnum=[lnum], getline=ulinecache.getline):
843 line = getline(file, lnum[0])
843 line = getline(file, lnum[0])
@@ -119,7 +119,7 b' try:'
119 except NameError:
119 except NameError:
120 from imp import reload
120 from imp import reload
121
121
122 from IPython.utils import pyfile
122 from IPython.utils import openpy
123 from IPython.utils.py3compat import PY3
123 from IPython.utils.py3compat import PY3
124
124
125 #------------------------------------------------------------------------------
125 #------------------------------------------------------------------------------
@@ -207,12 +207,12 b' class ModuleReloader(object):'
207 path, ext = os.path.splitext(filename)
207 path, ext = os.path.splitext(filename)
208
208
209 if ext.lower() == '.py':
209 if ext.lower() == '.py':
210 pyc_filename = pyfile.cache_from_source(filename)
210 pyc_filename = openpy.cache_from_source(filename)
211 py_filename = filename
211 py_filename = filename
212 else:
212 else:
213 pyc_filename = filename
213 pyc_filename = filename
214 try:
214 try:
215 py_filename = pyfile.source_from_cache(filename)
215 py_filename = openpy.source_from_cache(filename)
216 except ValueError:
216 except ValueError:
217 continue
217 continue
218
218
@@ -184,7 +184,6 b' import shlex'
184 import sys
184 import sys
185
185
186 from IPython.utils import io
186 from IPython.utils import io
187 from IPython.utils.io import file_read
188 from IPython.utils.text import marquee
187 from IPython.utils.text import marquee
189 from IPython.utils import openpy
188 from IPython.utils import openpy
190 __all__ = ['Demo','IPythonDemo','LineDemo','IPythonLineDemo','DemoError']
189 __all__ = ['Demo','IPythonDemo','LineDemo','IPythonLineDemo','DemoError']
@@ -380,7 +379,8 b' class Demo(object):'
380
379
381 filename = self.shell.mktempfile(self.src_blocks[index])
380 filename = self.shell.mktempfile(self.src_blocks[index])
382 self.shell.hooks.editor(filename,1)
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 # update the source and colored block
384 # update the source and colored block
385 self.src_blocks[index] = new_block
385 self.src_blocks[index] = new_block
386 self.src_blocks_colored[index] = self.ip_colorize(new_block)
386 self.src_blocks_colored[index] = self.ip_colorize(new_block)
@@ -22,7 +22,6 b' import sys'
22 from IPython.external import pexpect
22 from IPython.external import pexpect
23
23
24 # Our own
24 # Our own
25 from .autoattr import auto_attr
26 from ._process_common import getoutput, arg_split
25 from ._process_common import getoutput, arg_split
27 from IPython.utils import py3compat
26 from IPython.utils import py3compat
28 from IPython.utils.encoding import DEFAULT_ENCODING
27 from IPython.utils.encoding import DEFAULT_ENCODING
@@ -55,14 +54,16 b' class ProcessHandler(object):'
55 logfile = None
54 logfile = None
56
55
57 # Shell to call for subprocesses to execute
56 # Shell to call for subprocesses to execute
58 sh = None
57 _sh = None
59
58
60 @auto_attr
59 @property
61 def sh(self):
60 def sh(self):
62 sh = pexpect.which('sh')
61 if self._sh is None:
63 if sh is None:
62 self._sh = pexpect.which('sh')
64 raise OSError('"sh" shell not found')
63 if self._sh is None:
65 return sh
64 raise OSError('"sh" shell not found')
65
66 return self._sh
66
67
67 def __init__(self, logfile=None, read_timeout=None, terminate_timeout=None):
68 def __init__(self, logfile=None, read_timeout=None, terminate_timeout=None):
68 """Arguments are used for pexpect calls."""
69 """Arguments are used for pexpect calls."""
@@ -9,16 +9,6 b''
9 # the file COPYING, distributed as part of this software.
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 def uniq_stable(elems):
12 def uniq_stable(elems):
23 """uniq_stable(elems) -> list
13 """uniq_stable(elems) -> list
24
14
@@ -32,65 +22,14 b' def uniq_stable(elems):'
32 return [x for x in elems if x not in seen and not seen.add(x)]
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 def flatten(seq):
25 def flatten(seq):
78 """Flatten a list of lists (NOT recursive, only works for 2d lists)."""
26 """Flatten a list of lists (NOT recursive, only works for 2d lists)."""
79
27
80 return [x for subseq in seq for x in subseq]
28 return [x for subseq in seq for x in subseq]
81
29
82
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
30
91 def chop(seq, size):
31 def chop(seq, size):
92 """Chop a sequence into chunks of the given size."""
32 """Chop a sequence into chunks of the given size."""
93 chunk = lambda i: seq[i:i+size]
33 return [seq[i:i+size] for i in xrange(0,len(seq),size)]
94 return map(chunk,xrange(0,len(seq),size))
95
34
96
35
@@ -154,64 +154,6 b' class Tee(object):'
154 self.close()
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 def ask_yes_no(prompt,default=None):
157 def ask_yes_no(prompt,default=None):
216 """Asks a question and returns a boolean (y/n) answer.
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 return answers[ans]
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 def temp_pyfile(src, ext='.py'):
187 def temp_pyfile(src, ext='.py'):
284 """Make a temporary python file, return filename and filehandle.
188 """Make a temporary python file, return filename and filehandle.
285
189
@@ -18,8 +18,6 b' Authors:'
18 # Imports
18 # Imports
19 #-----------------------------------------------------------------------------
19 #-----------------------------------------------------------------------------
20
20
21 from IPython.utils.data import list2dict2
22
23 __all__ = ['Struct']
21 __all__ = ['Struct']
24
22
25 #-----------------------------------------------------------------------------
23 #-----------------------------------------------------------------------------
@@ -370,7 +368,7 b' class Struct(dict):'
370 add_s = lambda old,new: old + ' ' + new
368 add_s = lambda old,new: old + ' ' + new
371
369
372 # default policy is to keep current keys when there's a conflict
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 # the conflict_solve dictionary is given by the user 'inverted': we
373 # the conflict_solve dictionary is given by the user 'inverted': we
376 # need a name-function mapping, it comes as a function -> names
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 import io
9 import io
10 from io import TextIOWrapper, BytesIO
10 from io import TextIOWrapper, BytesIO
11 import os.path
11 import re
12 import re
12
13
13 cookie_re = re.compile(ur"coding[:=]\s*([-\w.]+)", re.UNICODE)
14 cookie_re = re.compile(ur"coding[:=]\s*([-\w.]+)", re.UNICODE)
@@ -217,3 +218,22 b' def _list_readline(x):'
217 def readline():
218 def readline():
218 return next(x)
219 return next(x)
219 return readline
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 from IPython.external.path import path
30 from IPython.external.path import path
31 from IPython.testing.skipdoctest import skip_doctest_py3, skip_doctest
31 from IPython.testing.skipdoctest import skip_doctest_py3, skip_doctest
32 from IPython.utils import py3compat
32 from IPython.utils import py3compat
33 from IPython.utils.io import nlprint
34 from IPython.utils.data import flatten
33 from IPython.utils.data import flatten
35
34
36 #-----------------------------------------------------------------------------
35 #-----------------------------------------------------------------------------
37 # Code
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 class LSString(str):
39 class LSString(str):
53 """String derivative with a special access attributes.
40 """String derivative with a special access attributes.
54
41
@@ -265,105 +252,11 b' class SList(list):'
265 # arg.hideonce = False
252 # arg.hideonce = False
266 # return
253 # return
267 #
254 #
268 # nlprint(arg)
255 # nlprint(arg) # This was a nested list printer, now removed.
269 #
256 #
270 # print_slist = result_display.when_type(SList)(print_slist)
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 def indent(instr,nspaces=4, ntabs=0, flatten=False):
260 def indent(instr,nspaces=4, ntabs=0, flatten=False):
368 """Indent a string a given number of spaces or tabstops.
261 """Indent a string a given number of spaces or tabstops.
369
262
1 NO CONTENT: file was removed
NO CONTENT: file was removed
1 NO CONTENT: file was removed
NO CONTENT: file was removed
1 NO CONTENT: file was removed
NO CONTENT: file was removed
1 NO CONTENT: file was removed
NO CONTENT: file was removed
1 NO CONTENT: file was removed
NO CONTENT: file was removed
1 NO CONTENT: file was removed
NO CONTENT: file was removed
1 NO CONTENT: file was removed
NO CONTENT: file was removed
General Comments 0
You need to be logged in to leave comments. Login now