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