##// END OF EJS Templates
Fixes to testing....
Fernando Perez -
Show More
@@ -61,9 +61,11 b' class Style(object):'
61 61 ``bg`` as the background color and ``attrs`` as the attributes.
62 62
63 63 Examples:
64 >>> Style(COLOR_RED, COLOR_BLACK)
65 <Style fg=red bg=black attrs=0>
64 66
65 >>> Style(COLOR_RED, COLOR_BLACK)
66 >>> Style(COLOR_YELLOW, COLOR_BLUE, A_BOLD|A_UNDERLINE)
67 >>> Style(COLOR_YELLOW, COLOR_BLUE, A_BOLD|A_UNDERLINE)
68 <Style fg=yellow bg=blue attrs=bold|underline>
67 69 """
68 70 self.fg = fg
69 71 self.bg = bg
@@ -8,7 +8,7 b' objects imported this way starts with ``i`` to minimize collisions.'
8 8 ``ipipe`` supports "pipeline expressions", which is something resembling Unix
9 9 pipes. An example is::
10 10
11 >>> ienv | isort("key.lower()")
11 py> ienv | isort("key.lower()")
12 12
13 13 This gives a listing of all environment variables sorted by name.
14 14
@@ -49,31 +49,31 b' three extensions points (all of them optional):'
49 49 makes it possible to use dictionaries and modules in pipeline expressions,
50 50 for example::
51 51
52 >>> import sys
53 >>> sys | ifilter("isinstance(value, int)") | idump
52 py> import sys
53 py> sys | ifilter("isinstance(value, int)") | idump
54 54 key |value
55 55 api_version| 1012
56 56 dllhandle | 503316480
57 57 hexversion | 33817328
58 58 maxint |2147483647
59 59 maxunicode | 65535
60 >>> sys.modules | ifilter("_.value is not None") | isort("_.key.lower()")
60 py> sys.modules | ifilter("_.value is not None") | isort("_.key.lower()")
61 61 ...
62 62
63 63 Note: The expression strings passed to ``ifilter()`` and ``isort()`` can
64 64 refer to the object to be filtered or sorted via the variable ``_`` and to any
65 65 of the attributes of the object, i.e.::
66 66
67 >>> sys.modules | ifilter("_.value is not None") | isort("_.key.lower()")
67 py> sys.modules | ifilter("_.value is not None") | isort("_.key.lower()")
68 68
69 69 does the same as::
70 70
71 >>> sys.modules | ifilter("value is not None") | isort("key.lower()")
71 py> sys.modules | ifilter("value is not None") | isort("key.lower()")
72 72
73 73 In addition to expression strings, it's possible to pass callables (taking
74 74 the object as an argument) to ``ifilter()``, ``isort()`` and ``ieval()``::
75 75
76 >>> sys | ifilter(lambda _:isinstance(_.value, int)) \
76 py> sys | ifilter(lambda _:isinstance(_.value, int)) \
77 77 ... | ieval(lambda _: (_.key, hex(_.value))) | idump
78 78 0 |1
79 79 api_version|0x3f4
@@ -123,8 +123,7 b' except ImportError:'
123 123 grp = None
124 124
125 125 from IPython.external import simplegeneric
126
127 import path
126 from IPython.external import path
128 127
129 128 try:
130 129 from IPython import genutils, generics
@@ -1209,9 +1208,9 b' class ils(Table):'
1209 1208
1210 1209 Examples::
1211 1210
1212 >>> ils
1213 >>> ils("/usr/local/lib/python2.4")
1214 >>> ils("~")
1211 py> ils
1212 py> ils("/usr/local/lib/python2.4")
1213 py> ils("~")
1215 1214 """
1216 1215 def __init__(self, base=os.curdir, dirs=True, files=True):
1217 1216 self.base = os.path.expanduser(base)
@@ -1247,7 +1246,7 b' class iglob(Table):'
1247 1246
1248 1247 Examples::
1249 1248
1250 >>> iglob("*.py")
1249 py> iglob("*.py")
1251 1250 """
1252 1251 def __init__(self, glob):
1253 1252 self.glob = glob
@@ -1272,9 +1271,9 b' class iwalk(Table):'
1272 1271 """
1273 1272 List all files and directories in a directory and it's subdirectory::
1274 1273
1275 >>> iwalk
1276 >>> iwalk("/usr/local/lib/python2.4")
1277 >>> iwalk("~")
1274 py> iwalk
1275 py> iwalk("/usr/local/lib/python2.4")
1276 py> iwalk("~")
1278 1277 """
1279 1278 def __init__(self, base=os.curdir, dirs=True, files=True):
1280 1279 self.base = os.path.expanduser(base)
@@ -1377,7 +1376,7 b' class ipwd(Table):'
1377 1376
1378 1377 Example::
1379 1378
1380 >>> ipwd | isort("uid")
1379 py> ipwd | isort("uid")
1381 1380 """
1382 1381 def __iter__(self):
1383 1382 for entry in pwd.getpwall():
@@ -1561,7 +1560,7 b' class ienv(Table):'
1561 1560
1562 1561 Example::
1563 1562
1564 >>> ienv
1563 py> ienv
1565 1564 """
1566 1565
1567 1566 def __iter__(self):
@@ -1582,8 +1581,8 b' class ihist(Table):'
1582 1581
1583 1582 Example::
1584 1583
1585 >>> ihist
1586 >>> ihist(True) (raw mode)
1584 py> ihist
1585 py> ihist(True) (raw mode)
1587 1586 """
1588 1587 def __init__(self, raw=True):
1589 1588 self.raw = raw
@@ -1617,7 +1616,7 b' class ialias(Table):'
1617 1616
1618 1617 Example::
1619 1618
1620 >>> ialias
1619 py> ialias
1621 1620 """
1622 1621 def __iter__(self):
1623 1622 api = ipapi.get()
@@ -1679,8 +1678,8 b' class ix(Table):'
1679 1678
1680 1679 Examples::
1681 1680
1682 >>> ix("ps x")
1683 >>> ix("find .") | ifile
1681 py> ix("ps x")
1682 py> ix("find .") | ifile
1684 1683 """
1685 1684 def __init__(self, cmd):
1686 1685 self.cmd = cmd
@@ -1718,9 +1717,9 b' class ifilter(Pipe):'
1718 1717
1719 1718 Examples::
1720 1719
1721 >>> ils | ifilter("_.isfile() and size>1000")
1722 >>> igrp | ifilter("len(mem)")
1723 >>> sys.modules | ifilter(lambda _:_.value is not None)
1720 py> ils | ifilter("_.isfile() and size>1000")
1721 py> igrp | ifilter("len(mem)")
1722 py> sys.modules | ifilter(lambda _:_.value is not None)
1724 1723 """
1725 1724
1726 1725 def __init__(self, expr, globals=None, errors="raiseifallfail"):
@@ -1810,8 +1809,8 b' class ieval(Pipe):'
1810 1809
1811 1810 Examples::
1812 1811
1813 >>> ils | ieval("_.abspath()")
1814 >>> sys.path | ieval(ifile)
1812 py> ils | ieval("_.abspath()")
1813 py> sys.path | ieval(ifile)
1815 1814 """
1816 1815
1817 1816 def __init__(self, expr, globals=None, errors="raiseifallfail"):
@@ -1882,7 +1881,7 b' class ienum(Pipe):'
1882 1881
1883 1882 Examples::
1884 1883
1885 >>> xrange(20) | ieval("_,_*_") | ienum | ifilter("index % 2 == 0") | ieval("object")
1884 py> xrange(20) | ieval("_,_*_") | ienum | ifilter("index % 2 == 0") | ieval("object")
1886 1885 """
1887 1886 def __iter__(self):
1888 1887 fields = ("index", "object")
@@ -1896,8 +1895,8 b' class isort(Pipe):'
1896 1895
1897 1896 Examples::
1898 1897
1899 >>> ils | isort("size")
1900 >>> ils | isort("_.isdir(), _.lower()", reverse=True)
1898 py> ils | isort("size")
1899 py> ils | isort("_.isdir(), _.lower()", reverse=True)
1901 1900 """
1902 1901
1903 1902 def __init__(self, key=None, globals=None, reverse=False):
@@ -2054,8 +2053,8 b' class icap(Table):'
2054 2053
2055 2054 Examples::
2056 2055
2057 >>> import time
2058 >>> icap("for i in range(10): print i, time.sleep(0.1)")
2056 py> import time
2057 py> icap("for i in range(10): print i, time.sleep(0.1)")
2059 2058
2060 2059 """
2061 2060 def __init__(self, expr, globals=None):
@@ -4,6 +4,7 b' A module to change reload() so that it acts recursively.'
4 4 To enable it type:
5 5 >>> import __builtin__, deep_reload
6 6 >>> __builtin__.reload = deep_reload.reload
7
7 8 You can then disable it with:
8 9 >>> __builtin__.reload = deep_reload.original_reload
9 10
@@ -97,8 +97,8 b' class IOStream:'
97 97
98 98 def close(self):
99 99 pass
100
101
100
101
102 102 class IOTerm:
103 103 """ Term holds the file or file-like objects for handling I/O operations.
104 104
@@ -113,16 +113,16 b' class IOTerm:'
113 113 self.cin = IOStream(cin,sys.stdin)
114 114 self.cout = IOStream(cout,sys.stdout)
115 115 self.cerr = IOStream(cerr,sys.stderr)
116
116
117 117 # Global variable to be used for all I/O
118 118 Term = IOTerm()
119 119
120 120 import IPython.rlineimpl as readline
121 121 # Remake Term to use the readline i/o facilities
122 122 if sys.platform == 'win32' and readline.have_readline:
123
123
124 124 Term = IOTerm(cout=readline._outputfile,cerr=readline._outputfile)
125
125
126 126
127 127 #****************************************************************************
128 128 # Generic warning/error printer, used by everything else
@@ -130,9 +130,9 b' def warn(msg,level=2,exit_val=1):'
130 130 """Standard warning printer. Gives formatting consistency.
131 131
132 132 Output is sent to Term.cerr (sys.stderr by default).
133
133
134 134 Options:
135
135
136 136 -level(2): allows finer control:
137 137 0 -> Do nothing, dummy function.
138 138 1 -> Print message.
@@ -142,7 +142,7 b' def warn(msg,level=2,exit_val=1):'
142 142
143 143 -exit_val (1): exit value returned by sys.exit() for a level 4
144 144 warning. Ignored for all other levels."""
145
145
146 146 if level>0:
147 147 header = ['','','WARNING: ','ERROR: ','FATAL ERROR: ']
148 148 print >> Term.cerr, '%s%s' % (header[level],msg)
@@ -167,10 +167,10 b' def fatal(msg,exit_val=1):'
167 167
168 168 #---------------------------------------------------------------------------
169 169 # Debugging routines
170 #
170 #
171 171 def debugx(expr,pre_msg=''):
172 172 """Print the value of an expression from the caller's frame.
173
173
174 174 Takes an expression, evaluates it in the caller's frame and prints both
175 175 the given expression and the resulting value (as well as a debug mark
176 176 indicating the name of the calling function. The input must be of a form
@@ -178,7 +178,7 b" def debugx(expr,pre_msg=''):"
178 178
179 179 An optional message can be passed, which will be prepended to the printed
180 180 expr->value pair."""
181
181
182 182 cf = sys._getframe(1)
183 183 print '[DBG:%s] %s%s -> %r' % (cf.f_code.co_name,pre_msg,expr,
184 184 eval(expr,cf.f_globals,cf.f_locals))
@@ -200,18 +200,18 b' try:'
200 200 Return the *USER* CPU time in seconds since the start of the process.
201 201 This is done via a call to resource.getrusage, so it avoids the
202 202 wraparound problems in time.clock()."""
203
203
204 204 return resource.getrusage(resource.RUSAGE_SELF)[0]
205
205
206 206 def clocks():
207 207 """clocks() -> floating point number
208 208
209 209 Return the *SYSTEM* CPU time in seconds since the start of the process.
210 210 This is done via a call to resource.getrusage, so it avoids the
211 211 wraparound problems in time.clock()."""
212
212
213 213 return resource.getrusage(resource.RUSAGE_SELF)[1]
214
214
215 215 def clock():
216 216 """clock() -> floating point number
217 217
@@ -219,9 +219,9 b' try:'
219 219 the process. This is done via a call to resource.getrusage, so it
220 220 avoids the wraparound problems in time.clock()."""
221 221
222 u,s = resource.getrusage(resource.RUSAGE_SELF)[:2]
222 u,s = resource.getrusage(resource.RUSAGE_SELF)[:2]
223 223 return u+s
224
224
225 225 def clock2():
226 226 """clock2() -> (t_user,t_system)
227 227
@@ -247,7 +247,7 b' def timings_out(reps,func,*args,**kw):'
247 247 Under Unix, the return value is the sum of user+system time consumed by
248 248 the process, computed via the resource module. This prevents problems
249 249 related to the wraparound effect which the time.clock() function has.
250
250
251 251 Under Windows the return value is in wall clock seconds. See the
252 252 documentation for the time module for more details."""
253 253
@@ -310,7 +310,7 b" def system(cmd,verbose=0,debug=0,header=''):"
310 310 Options:
311 311
312 312 - verbose (0): print the command to be executed.
313
313
314 314 - debug (0): only print, do not actually execute.
315 315
316 316 - header (''): Header to print on screen prior to the executed command (it
@@ -334,15 +334,15 b' def abbrev_cwd():'
334 334 if len(cwd) < 4:
335 335 return cwd
336 336 drivepart,tail = os.path.splitdrive(cwd)
337
338 337
339 parts = tail.split('/')
338
339 parts = tail.split('/')
340 340 if len(parts) > 2:
341 341 tail = '/'.join(parts[-2:])
342
342
343 343 return (drivepart + (
344 344 cwd == '/' and '/' or tail))
345
345
346 346
347 347 # This function is used by ipython in a lot of places to make system calls.
348 348 # We need it to be slightly different under win32, due to the vagaries of
@@ -354,7 +354,7 b" def shell(cmd,verbose=0,debug=0,header=''):"
354 354 Options:
355 355
356 356 - verbose (0): print the command to be executed.
357
357
358 358 - debug (0): only print, do not actually execute.
359 359
360 360 - header (''): Header to print on screen prior to the executed command (it
@@ -368,7 +368,7 b" def shell(cmd,verbose=0,debug=0,header=''):"
368 368 if verbose or debug: print header+cmd
369 369 # flush stdout so we don't mangle python's buffering
370 370 sys.stdout.flush()
371
371
372 372 if not debug:
373 373 platutils.set_term_title("IPy " + cmd)
374 374 os.system(cmd)
@@ -406,10 +406,10 b" def getoutput(cmd,verbose=0,debug=0,header='',split=0):"
406 406
407 407 Note: a stateful version of this function is available through the
408 408 SystemExec class.
409
410 This is pretty much deprecated and rarely used,
409
410 This is pretty much deprecated and rarely used,
411 411 genutils.getoutputerror may be what you need.
412
412
413 413 """
414 414
415 415 if verbose or debug: print header+cmd
@@ -461,7 +461,7 b' class SystemExec:'
461 461
462 462 Note: here we refer to the system and getoutput functions from this
463 463 library, not the ones from the standard python library.
464
464
465 465 This class offers the system and getoutput functions as methods, but the
466 466 verbose, debug and header parameters can be set for the instance (at
467 467 creation time or later) so that they don't need to be specified on each
@@ -477,13 +477,8 b' class SystemExec:'
477 477
478 478 An instance can then be created as:
479 479 >>> sysexec = SystemExec(verbose=1,debug=0,header='Calling: ')
480
481 And used as:
482 >>> sysexec.xsys('echo "Hello Python"')
483 Calling: echo "Hello Python"
484 Hello Python
485 480 """
486
481
487 482 def __init__(self,verbose=0,debug=0,header='',split=0):
488 483 """Specify the instance's values for verbose, debug and header."""
489 484 setattr_list(self,'verbose debug header split')
@@ -635,7 +630,7 b" def process_cmdline(argv,names=[],defaults={},usage=''):"
635 630 Arguments:
636 631
637 632 - argv: list of arguments, typically sys.argv.
638
633
639 634 - names: list of option names. See DPyGetOpt docs for details on options
640 635 syntax.
641 636
@@ -657,7 +652,7 b" def process_cmdline(argv,names=[],defaults={},usage=''):"
657 652
658 653 defaults.update(getopt.optionValues)
659 654 args = getopt.freeValues
660
655
661 656 return defaults,args
662 657
663 658 #----------------------------------------------------------------------------
@@ -685,7 +680,7 b' def optstr2types(ostr):'
685 680
686 681 #----------------------------------------------------------------------------
687 682 def read_dict(filename,type_conv=None,**opt):
688 """Read a dictionary of key=value pairs from an input file, optionally
683 r"""Read a dictionary of key=value pairs from an input file, optionally
689 684 performing conversions on the resulting values.
690 685
691 686 read_dict(filename,type_conv,**opt) -> dict
@@ -731,20 +726,33 b' def read_dict(filename,type_conv=None,**opt):'
731 726 to make a list of all appearances.
732 727
733 728 Example:
734 If the input file test.ini has:
735 i 3
736 x 4.5
737 y 5.5
738 s hi ho
739 Then:
740 729
730 If the input file test.ini contains (we put it in a string to keep the test
731 self-contained):
732
733 >>> test_ini = '''\
734 ... i 3
735 ... x 4.5
736 ... y 5.5
737 ... s hi ho'''
738
739 Then we can use it as follows:
741 740 >>> type_conv={int:'i',float:'x',None:'s'}
742 >>> read_dict('test.ini')
743 {'i': '3', 's': 'hi ho', 'x': '4.5', 'y': '5.5'}
744 >>> read_dict('test.ini',type_conv)
745 {'i': 3, 's': 'hi ho', 'x': 4.5, 'y': '5.5'}
746 >>> read_dict('test.ini',type_conv,purge=1)
747 {'i': 3, 's': 'hi ho', 'x': 4.5}
741
742 >>> d = read_dict(test_ini)
743
744 >>> sorted(d.items())
745 [('i', '3'), ('s', 'hi ho'), ('x', '4.5'), ('y', '5.5')]
746
747 >>> d = read_dict(test_ini,type_conv)
748
749 >>> sorted(d.items())
750 [('i', 3), ('s', 'hi ho'), ('x', 4.5), ('y', '5.5')]
751
752 >>> d = read_dict(test_ini,type_conv,purge=True)
753
754 >>> sorted(d.items())
755 [('i', 3), ('s', 'hi ho'), ('x', 4.5)]
748 756 """
749 757
750 758 # starting config
@@ -762,9 +770,15 b' def read_dict(filename,type_conv=None,**opt):'
762 770 raise ValueError, 'Unique keys must be given as a string, List or Tuple'
763 771
764 772 dict = {}
773
765 774 # first read in table of values as strings
766 file = open(filename,'r')
767 for line in file.readlines():
775 if '\n' in filename:
776 lines = filename.splitlines()
777 file = None
778 else:
779 file = open(filename,'r')
780 lines = file.readlines()
781 for line in lines:
768 782 line = line.strip()
769 783 if len(line) and line[0]=='#': continue
770 784 if len(line)>0:
@@ -831,7 +845,7 b' def flag_calls(func):'
831 845
832 846 Testing for truth in wrapper.called allows you to determine if a call to
833 847 func() was attempted and succeeded."""
834
848
835 849 def wrapper(*args,**kw):
836 850 wrapper.called = False
837 851 out = func(*args,**kw)
@@ -853,7 +867,7 b' def dhook_wrap(func,*a,**k):'
853 867 """
854 868
855 869 def f(*a,**k):
856
870
857 871 dhook_s = sys.displayhook
858 872 sys.displayhook = sys.__displayhook__
859 873 try:
@@ -873,10 +887,10 b' def doctest_reload():'
873 887 This routine:
874 888
875 889 - reloads doctest
876
890
877 891 - resets its global 'master' attribute to None, so that multiple uses of
878 892 the module interactively don't produce cumulative reports.
879
893
880 894 - Monkeypatches its core test runner method to protect it from IPython's
881 895 modified displayhook. Doctest expects the default displayhook behavior
882 896 deep down, so our modification breaks it completely. For this reason, a
@@ -910,16 +924,16 b' def get_home_dir():'
910 924
911 925 isdir = os.path.isdir
912 926 env = os.environ
913
927
914 928 # first, check py2exe distribution root directory for _ipython.
915 929 # This overrides all. Normally does not exist.
916
930
917 931 if '\\library.zip\\' in IPython.__file__.lower():
918 932 root, rest = IPython.__file__.lower().split('library.zip')
919 933 if isdir(root + '_ipython'):
920 934 os.environ["IPYKITROOT"] = root.rstrip('\\')
921 935 return root
922
936
923 937 try:
924 938 homedir = env['HOME']
925 939 if not isdir(homedir):
@@ -977,7 +991,7 b' class LSString(str):'
977 991 .n (or .nlstr): original value (the string itself).
978 992 .s (or .spstr): value as whitespace-separated string.
979 993 .p (or .paths): list of path objects
980
994
981 995 Any values which require transformations are computed only once and
982 996 cached.
983 997
@@ -1013,14 +1027,14 b' class LSString(str):'
1013 1027 except AttributeError:
1014 1028 self.__paths = [path(p) for p in self.split('\n') if os.path.exists(p)]
1015 1029 return self.__paths
1016
1030
1017 1031 p = paths = property(get_paths)
1018 1032
1019 1033 def print_lsstring(arg):
1020 1034 """ Prettier (non-repr-like) and more informative printer for LSString """
1021 1035 print "LSString (.p, .n, .l, .s available). Value:"
1022 1036 print arg
1023
1037
1024 1038 print_lsstring = result_display.when_type(LSString)(print_lsstring)
1025 1039
1026 1040 #----------------------------------------------------------------------------
@@ -1033,7 +1047,7 b' class SList(list):'
1033 1047 .n (or .nlstr): value as a string, joined on newlines.
1034 1048 .s (or .spstr): value as a string, joined on spaces.
1035 1049 .p (or .paths): list of path objects
1036
1050
1037 1051 Any values which require transformations are computed only once and
1038 1052 cached."""
1039 1053
@@ -1059,32 +1073,32 b' class SList(list):'
1059 1073 return self.__nlstr
1060 1074
1061 1075 n = nlstr = property(get_nlstr)
1062
1076
1063 1077 def get_paths(self):
1064 1078 try:
1065 1079 return self.__paths
1066 1080 except AttributeError:
1067 1081 self.__paths = [path(p) for p in self if os.path.exists(p)]
1068 1082 return self.__paths
1069
1083
1070 1084 p = paths = property(get_paths)
1071 1085
1072 1086 def grep(self, pattern, prune = False, field = None):
1073 """ Return all strings matching 'pattern' (a regex or callable)
1074
1087 """ Return all strings matching 'pattern' (a regex or callable)
1088
1075 1089 This is case-insensitive. If prune is true, return all items
1076 1090 NOT matching the pattern.
1077
1078 If field is specified, the match must occur in the specified
1091
1092 If field is specified, the match must occur in the specified
1079 1093 whitespace-separated field.
1080
1094
1081 1095 Examples::
1082
1096
1083 1097 a.grep( lambda x: x.startswith('C') )
1084 1098 a.grep('Cha.*log', prune=1)
1085 1099 a.grep('chm', field=-1)
1086 1100 """
1087
1101
1088 1102 def match_target(s):
1089 1103 if field is None:
1090 1104 return s
@@ -1094,7 +1108,7 b' class SList(list):'
1094 1108 return tgt
1095 1109 except IndexError:
1096 1110 return ""
1097
1111
1098 1112 if isinstance(pattern, basestring):
1099 1113 pred = lambda x : re.search(pattern, x, re.IGNORECASE)
1100 1114 else:
@@ -1105,25 +1119,25 b' class SList(list):'
1105 1119 return SList([el for el in self if not pred(match_target(el))])
1106 1120 def fields(self, *fields):
1107 1121 """ Collect whitespace-separated fields from string list
1108
1122
1109 1123 Allows quick awk-like usage of string lists.
1110
1124
1111 1125 Example data (in var a, created by 'a = !ls -l')::
1112 1126 -rwxrwxrwx 1 ville None 18 Dec 14 2006 ChangeLog
1113 drwxrwxrwx+ 6 ville None 0 Oct 24 18:05 IPython
1114
1127 drwxrwxrwx+ 6 ville None 0 Oct 24 18:05 IPython
1128
1115 1129 a.fields(0) is ['-rwxrwxrwx', 'drwxrwxrwx+']
1116 1130 a.fields(1,0) is ['1 -rwxrwxrwx', '6 drwxrwxrwx+']
1117 1131 (note the joining by space).
1118 1132 a.fields(-1) is ['ChangeLog', 'IPython']
1119
1133
1120 1134 IndexErrors are ignored.
1121
1135
1122 1136 Without args, fields() just split()'s the strings.
1123 1137 """
1124 1138 if len(fields) == 0:
1125 1139 return [el.split() for el in self]
1126
1140
1127 1141 res = SList()
1128 1142 for el in [f.split() for f in self]:
1129 1143 lineparts = []
@@ -1135,18 +1149,18 b' class SList(list):'
1135 1149 pass
1136 1150 if lineparts:
1137 1151 res.append(" ".join(lineparts))
1138
1139 return res
1152
1153 return res
1140 1154 def sort(self,field= None, nums = False):
1141 1155 """ sort by specified fields (see fields())
1142
1156
1143 1157 Example::
1144 1158 a.sort(1, nums = True)
1145
1159
1146 1160 Sorts a by second field, in numerical order (so that 21 > 3)
1147
1148 """
1149
1161
1162 """
1163
1150 1164 #decorate, sort, undecorate
1151 1165 if field is not None:
1152 1166 dsu = [[SList([line]).fields(field), line] for line in self]
@@ -1160,8 +1174,8 b' class SList(list):'
1160 1174 except ValueError:
1161 1175 n = 0;
1162 1176 dsu[i][0] = n
1163
1164
1177
1178
1165 1179 dsu.sort()
1166 1180 return SList([t[1] for t in dsu])
1167 1181
@@ -1171,9 +1185,9 b' def print_slist(arg):'
1171 1185 if hasattr(arg, 'hideonce') and arg.hideonce:
1172 1186 arg.hideonce = False
1173 1187 return
1174
1188
1175 1189 nlprint(arg)
1176
1190
1177 1191 print_slist = result_display.when_type(SList)(print_slist)
1178 1192
1179 1193
@@ -1187,14 +1201,14 b' def esc_quotes(strng):'
1187 1201 #----------------------------------------------------------------------------
1188 1202 def make_quoted_expr(s):
1189 1203 """Return string s in appropriate quotes, using raw string if possible.
1190
1204
1191 1205 Effectively this turns string: cd \ao\ao\
1192 1206 to: r"cd \ao\ao\_"[:-1]
1193
1207
1194 1208 Note the use of raw string and padding at the end to allow trailing backslash.
1195
1209
1196 1210 """
1197
1211
1198 1212 tail = ''
1199 1213 tailpadding = ''
1200 1214 raw = ''
@@ -1245,7 +1259,7 b" def raw_input_multi(header='', ps1='==> ', ps2='..> ',terminate_str = '.'):"
1245 1259 while new_line.endswith('\\'):
1246 1260 new_line = new_line[:-1] + raw_input(ps2)
1247 1261 lines.append(new_line)
1248
1262
1249 1263 return lines[:-1] # don't return the termination command
1250 1264 except EOFError:
1251 1265 print
@@ -1287,7 +1301,7 b' def ask_yes_no(prompt,default=None):'
1287 1301 print
1288 1302 else:
1289 1303 raise
1290
1304
1291 1305 return answers[ans]
1292 1306
1293 1307 #----------------------------------------------------------------------------
@@ -1344,7 +1358,7 b' def qw(words,flat=0,sep=None,maxsplit=-1):'
1344 1358 >>> qw(['a b','1 2',['m n','p q']],flat=1)
1345 1359 ['a', 'b', '1', '2', 'm', 'n', 'p', 'q']
1346 1360 """
1347
1361
1348 1362 if type(words) in StringTypes:
1349 1363 return [word.strip() for word in words.split(sep,maxsplit)
1350 1364 if word and not word.isspace() ]
@@ -1423,7 +1437,7 b' def igrep(pat,list):'
1423 1437 #----------------------------------------------------------------------------
1424 1438 def indent(str,nspaces=4,ntabs=0):
1425 1439 """Indent a string a given number of spaces or tabstops.
1426
1440
1427 1441 indent(str,nspaces=4,ntabs=0) -> indent str by ntabs+nspaces.
1428 1442 """
1429 1443 if str is None:
@@ -1434,7 +1448,7 b' def indent(str,nspaces=4,ntabs=0):'
1434 1448 return outstr[:-len(ind)]
1435 1449 else:
1436 1450 return outstr
1437
1451
1438 1452 #-----------------------------------------------------------------------------
1439 1453 def native_line_ends(filename,backup=1):
1440 1454 """Convert (in-place) a file to line-ends native to the current OS.
@@ -1460,13 +1474,13 b' def native_line_ends(filename,backup=1):'
1460 1474 os.remove(bak_filename)
1461 1475 except:
1462 1476 pass
1463
1477
1464 1478 #----------------------------------------------------------------------------
1465 1479 def get_pager_cmd(pager_cmd = None):
1466 1480 """Return a pager command.
1467 1481
1468 1482 Makes some attempts at finding an OS-correct one."""
1469
1483
1470 1484 if os.name == 'posix':
1471 1485 default_pager_cmd = 'less -r' # -r for color control sequences
1472 1486 elif os.name in ['nt','dos']:
@@ -1578,7 +1592,7 b' def page(strng,start=0,screen_lines=0,pager_cmd = None):'
1578 1592 return
1579 1593 except IPython.ipapi.TryNext:
1580 1594 pass
1581
1595
1582 1596 # Ugly kludge, but calling curses.initscr() flat out crashes in emacs
1583 1597 TERM = os.environ.get('TERM','dumb')
1584 1598 if TERM in ['dumb','emacs'] and os.name != 'nt':
@@ -1589,7 +1603,7 b' def page(strng,start=0,screen_lines=0,pager_cmd = None):'
1589 1603 str_toprint = os.linesep.join(str_lines)
1590 1604 num_newlines = len(str_lines)
1591 1605 len_str = len(str_toprint)
1592
1606
1593 1607 # Dumb heuristics to guesstimate number of on-screen lines the string
1594 1608 # takes. Very basic, but good enough for docstrings in reasonable
1595 1609 # terminals. If someone later feels like refining it, it's not hard.
@@ -1746,7 +1760,7 b' def uniq_stable(elems):'
1746 1760 Note: All elements in the input must be valid dictionary keys for this
1747 1761 routine to work, as it internally uses a dictionary for efficiency
1748 1762 reasons."""
1749
1763
1750 1764 unique = []
1751 1765 unique_dict = {}
1752 1766 for nn in elems:
@@ -1761,13 +1775,13 b' class NLprinter:'
1761 1775
1762 1776 An instance of this class called nlprint is available and callable as a
1763 1777 function.
1764
1778
1765 1779 nlprint(list,indent=' ',sep=': ') -> prints indenting each level by 'indent'
1766 1780 and using 'sep' to separate the index from the value. """
1767 1781
1768 1782 def __init__(self):
1769 1783 self.depth = 0
1770
1784
1771 1785 def __call__(self,lst,pos='',**kw):
1772 1786 """Prints the nested list numbering levels."""
1773 1787 kw.setdefault('indent',' ')
@@ -1780,7 +1794,7 b' class NLprinter:'
1780 1794 stop = kw['stop']; del kw['stop']
1781 1795 if self.depth == 0 and 'header' in kw.keys():
1782 1796 print kw['header']
1783
1797
1784 1798 for idx in range(start,stop):
1785 1799 elem = lst[idx]
1786 1800 if type(elem)==type([]):
@@ -1929,7 +1943,7 b' def getattr_list(obj,alist,*args):'
1929 1943 raise ValueError,'getattr_list() takes only one optional argument'
1930 1944 else:
1931 1945 return map(lambda attr: getattr(obj,attr),alist)
1932
1946
1933 1947 #----------------------------------------------------------------------------
1934 1948 def map_method(method,object_list,*argseq,**kw):
1935 1949 """map_method(method,object_list,*args,**kw) -> list
@@ -1981,7 +1995,7 b' def dir2(obj):'
1981 1995 are later not really valid for attribute access (many extension libraries
1982 1996 have such bugs).
1983 1997 """
1984
1998
1985 1999 # Start building the attribute list via dir(), and then complete it
1986 2000 # with a few extra special-purpose calls.
1987 2001 words = dir(obj)
@@ -2058,7 +2072,7 b' def popkey(dct,key,default=NotGiven):'
2058 2072
2059 2073 def wrap_deprecated(func, suggest = '<nothing>'):
2060 2074 def newFunc(*args, **kwargs):
2061 warnings.warn("Call to deprecated function %s, use %s instead" %
2075 warnings.warn("Call to deprecated function %s, use %s instead" %
2062 2076 ( func.__name__, suggest),
2063 2077 category=DeprecationWarning,
2064 2078 stacklevel = 2)
@@ -2092,7 +2106,7 b' def num_cpus():'
2092 2106 If it can't find a sensible answer, it returns 1 (though an error *may* make
2093 2107 it return a large positive number that's actually incorrect).
2094 2108 """
2095
2109
2096 2110 # Many thanks to the Parallel Python project (http://www.parallelpython.com)
2097 2111 # for the names of the keys we needed to look up for this function. This
2098 2112 # code was inspired by their equivalent function.
@@ -1007,10 +1007,17 b' class InteractiveShell(object,Magic):'
1007 1007
1008 1008 Simple usage example:
1009 1009
1010 In [1]: x = 'hello'
1010 In [7]: x = 'hello'
1011 1011
1012 In [2]: __IP.complete('x.l')
1013 Out[2]: ['x.ljust', 'x.lower', 'x.lstrip']"""
1012 In [8]: x
1013 Out[8]: 'hello'
1014
1015 In [9]: print x
1016 hello
1017
1018 In [10]: _ip.IP.complete('x.l')
1019 Out[10]: ['x.ljust', 'x.lower', 'x.lstrip']
1020 """
1014 1021
1015 1022 complete = self.Completer.complete
1016 1023 state = 0
@@ -1026,6 +1033,8 b' class InteractiveShell(object,Magic):'
1026 1033 state += 1
1027 1034 outcomps = comps.keys()
1028 1035 outcomps.sort()
1036 print "T:",text,"OC:",outcomps # dbg
1037 #print "vars:",self.user_ns.keys()
1029 1038 return outcomps
1030 1039
1031 1040 def set_completer_frame(self, frame=None):
@@ -1636,6 +1645,7 b' want to merge them back into the new files.""" % locals()'
1636 1645 # previous call (which most likely existed in a separate scope).
1637 1646 local_varnames = local_ns.keys()
1638 1647 self.user_ns.update(local_ns)
1648 #self.user_ns['local_ns'] = local_ns # dbg
1639 1649
1640 1650 # Patch for global embedding to make sure that things don't overwrite
1641 1651 # user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
@@ -2361,16 +2371,18 b' want to merge them back into the new files.""" % locals()'
2361 2371 def handle_auto(self, line_info):
2362 2372 """Hande lines which can be auto-executed, quoting if requested."""
2363 2373
2364 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
2365 2374 line = line_info.line
2366 2375 iFun = line_info.iFun
2367 2376 theRest = line_info.theRest
2368 2377 pre = line_info.pre
2369 2378 continue_prompt = line_info.continue_prompt
2370 2379 obj = line_info.ofind(self)['obj']
2371
2380
2381 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
2382
2372 2383 # This should only be active for single-line input!
2373 2384 if continue_prompt:
2385 print 'getting out!' # dbg
2374 2386 self.log(line,line,continue_prompt)
2375 2387 return line
2376 2388
@@ -89,7 +89,7 b' class Struct:'
89 89 accessed using the dictionary syntax. Again, an example:
90 90
91 91 This doesn't work:
92 >> s=Struct(4='hi') #doctest: +IGNORE_EXCEPTION_DETAIL
92 py> s=Struct(4='hi') #doctest: +IGNORE_EXCEPTION_DETAIL
93 93 Traceback (most recent call last):
94 94 ...
95 95 SyntaxError: keyword can't be an expression
@@ -172,7 +172,13 b" if __name__ == '__main__':"
172 172 # A comment
173 173 remote() # this means the code below only runs remotely
174 174 print 'Hello remote world'
175 x = 3.14
175 x = range(10)
176 176 # Comments are OK
177 177 # Even misindented.
178 178 y = x+1
179
180
181 with pfor('i',sequence) as pr:
182 print x[i]
183
184 print pr.x + pr.y
1 NO CONTENT: file renamed from IPython/testing/attic/parametric.py to IPython/testing/parametric.py
@@ -12,6 +12,10 b' deb: plugin dtexample.py'
12 12 nosetests -vs --with-ipdoctest --doctest-tests --doctest-extension=txt \
13 13 test_combo.txt
14 14
15 iptest: plugin
16 nosetests -vs --with-ipdoctest --doctest-tests --doctest-extension=txt \
17 IPython
18
15 19 IPython_doctest_plugin.egg-info: ipdoctest.py setup.py
16 20 python setup.py install --prefix=$(PREFIX)
17 21 touch $@
@@ -298,9 +298,9 b' class IPDocTestParser(doctest.DocTestParser):'
298 298 """Convert input IPython source into valid Python."""
299 299 out = []
300 300 newline = out.append
301 for line in source.splitlines():
301 for lnum,line in enumerate(source.splitlines()):
302 302 #newline(_ip.IPipython.prefilter(line,True))
303 newline(_ip.IP.prefilter(line,True))
303 newline(_ip.IP.prefilter(line,lnum>0))
304 304 newline('') # ensure a closing newline, needed by doctest
305 305 return '\n'.join(out)
306 306
@@ -538,6 +538,20 b' class ExtensionDoctest(doctests.Doctest):'
538 538 """
539 539 #print 'Filename:',filename # dbg
540 540
541 # temporarily hardcoded list, will move to driver later
542 exclude = ['IPython/external/',
543 'IPython/Extensions/ipy_',
544 'IPython/platutils_win32',
545 'IPython/frontend/cocoa',
546 'IPython_doctest_plugin',
547 'IPython/Gnuplot',
548 'IPython/Extensions/PhysicalQIn']
549
550 for fex in exclude:
551 if fex in filename: # substring
552 #print '###>>> SKIP:',filename # dbg
553 return False
554
541 555 if is_extension_module(filename):
542 556 return True
543 557 else:
General Comments 0
You need to be logged in to leave comments. Login now