Merge lp:~fdo.perez/ipython/trunk-dev into lp:ipython/0.11

Proposed by Fernando Perez
Status: Merged
Merged at revision: not available
Proposed branch: lp:~fdo.perez/ipython/trunk-dev
Merge into: lp:ipython/0.11
Diff against target: None lines
To merge this branch: bzr merge lp:~fdo.perez/ipython/trunk-dev
Reviewer Review Type Date Requested Status
Brian Granger Needs Fixing
Review via email: mp+4450@code.launchpad.net
To post a comment you must log in.
Revision history for this message
Fernando Perez (fdo.perez) wrote :

I had to nuke my lp copy of my trunk because I did some local patch reordering, so I've just re-uploaded a fresh copy. The code is the same as before.

Ready for review.

lp:~fdo.perez/ipython/trunk-dev updated
1172. By Fernando Perez

Close https://bugs.launchpad.net/ipython/+bug/341726

Apply patch submitted by Alexander Clausen <alex-AT-gc-web.de>. Fixes
incorrect bug reporting URL for IPython and stale SVN references.

1173. By Fernando Perez

Fix https://bugs.launchpad.net/ipython/+bug/239054

- Made a more robust reset method to fully flush internal state and restore
the system to a clean state. We'll need to see later if %reset should just
call this. For now it's used to release resources.

1174. By Fernando Perez

Fix https://bugs.launchpad.net/ipython/+bug/284660

Since we now require python 2.4, I applied a simpler version of the patch
mentioned there, simply using the set() builtin everywhere.

1175. By Fernando Perez

Merging from upstream (with a few local cleanups when resolving conflicts).

1176. By Fernando Perez

Add a note about the conflict winpdb causes with PyTables.

1177. By Fernando Perez

Fix problems with multiline doctests and add docs about testing.

Also enabled some more testings that were blacklisted, now that the testing
machinery is more robust.

Revision history for this message
Brian Granger (ellisonbg) wrote :

I just had fun doing this code review. Launchpad has really improved its code review interface. I really like how you can look through the diffs for each file now!

One general comment: I know you like to code in a single branch, but it makes it more difficult to review a branch when there are many revisions on a wide range of topics. I don't think each revision should go in its own branch, but when there is a larger set of revisions addressing a single issue, having all of those revisions in a single topic branch would be nice and make review easier. Also, smaller branches allow code that *is* finished to get into trunk faster without waiting for unrelated code to be finished and reviewed. I am guilty of the "big branch" workflow myself though.

r1168:

As you go through file and clean up the copyright info, please convert the copyright header to our standard one that references the ipython development team. Any specific mention of module authors or maintainers should go into the module docstring.

r1169:

Are the numpy helper scripts for converting docstrings in place and working with our IPython?

How do we want to handle references in our docs. Sphinx can now create a nice references section in the pdf files, but you have to use a particular format for the references. The current form of the references you have put in::

    .. _PEP 257: http://www.python.org/peps/pep-0257.html

I don't think will end up in the references section. How does numpy handle such things. Have a look at how references are handled in the kernel documentation to see how I have been handling this. My way may not be the best. Let's figure out how all of us should handle this and then document it in our docs.

r1171:

In ipy_profile_zope.py. Should we just remove all the old __author__, etc. module attributes?

All other revisions are great.

review: Needs Fixing
lp:~fdo.perez/ipython/trunk-dev updated
1178. By Fernando Perez

Merging upstream changes from trunk (after fixing small conflicts).

Revision history for this message
Fernando Perez (fdo.perez) wrote :
Download full text (3.2 KiB)

Hey,

I know we talked offline about most of this, but I'll leave things
here for recording purposes.

On Mon, Mar 16, 2009 at 9:39 AM, Brian Granger <email address hidden> wrote:
> Review: Needs Fixing
> I just had fun doing this code review.  Launchpad has really improved its code review interface.  I really like how you can look through the diffs for each file now!

Yes, it's gotten much better. Launchpad is slowly but surely improving.

>
> One general comment:  I know you like to code in a single branch, but it makes it more difficult to review a branch when there are many revisions on a wide range of topics.  I don't think each revision should go in its own branch, but when there is a larger set of revisions addressing a single issue, having all of those revisions in a single topic branch would be nice and make review easier.  Also, smaller branches allow code that *is* finished to get into trunk faster without waiting for unrelated code to be finished and reviewed.  I am guilty of the "big branch" workflow myself though.

Me too, it's certainly a bad habit. As we spoke about, we could
probably settle on a workflow with:

- per-person permanent 'trunk-dev' branches, on which we do easy,
incremental reviewing and merging.
- short-lived 'feature branches' for standalone ideas, more like a
patch in other workflows, just a patch that keeps evolving and that's
easy to track as it changes.

I'll try to do better in the future on this, and I really appreciate
that you took the time to go over this much code. Many thanks.

>
> r1168:
>
> As you go through file and clean up the copyright info, please convert the copyright header to our standard one that references the ipython development team. Any specific mention of module authors or maintainers should go into the module docstring.

As I mentioned, I was really going after the 'import Release'
statements, not after the authorship notices. But from now on, I'll
try to cleanup the copyright notices as I work on files.

> r1169:
>
> Are the numpy helper scripts for converting docstrings in place and working with our IPython?
>
> How do we want to handle references in our docs.  Sphinx can now create a nice references section in the pdf files, but you have to use a particular format for the references.  The current form of the references you have put in::
>
>    .. _PEP 257: http://www.python.org/peps/pep-0257.html
>
> I don't think will end up in the references section.  How does numpy handle such things.  Have a look at how references are handled in the kernel documentation to see how I have been handling this.  My way may not be the best.  Let's figure out how all of us should handle this and then document it in our docs.

This one, I don't know. I'm going to look into what Matthew Brett did
for Nipy to see if I can find a good overall solution.

> r1171:
>
> In ipy_profile_zope.py.  Should we just remove all the old __author__, etc. module attributes?

I'll do what we discussed: put the authorship notes I find in the
top-level docstring. This has the added benefit of putting them in
the generated API docs.

> All other revisions are great.

Thanks again for reviewing such a monster!

I'l...

Read more...

lp:~fdo.perez/ipython/trunk-dev updated
1179. By Fernando Perez

Merging from upstream trunk

1180. By Fernando Perez

Update copyright/author statements.

- Updated copyright statements to use the new form:

# Copyright (C) 2008-2009 The IPython Development Team

I left the old notices in place (just updating the year in some cases),
because as far as I know, old copyright statements are not meant to be
retroactively modified.

- Also, on most files, replaced __author__ marks with an 'Authors' section
in the module docstring. This reduces top-level code in the module, while
ensuring that the Author(s) get properly acknowledged in auto-generated API
docs (sphinx doesn't read __author__ marks, but it will include the module
docstring).

I only left a few in place for very old files that we ship externally, and
for those by Laurent: he had his authorship mark both in the docstring and
in __author__ variables, so I think out of courtesy it would be better to
ask him about it on the list. All the others were I found regular
__author__ variables, I moved them to the main docstring.

Revision history for this message
Fernando Perez (fdo.perez) wrote :

"""
> r1168:
>
> As you go through file and clean up the copyright info, please convert the copyright header to our standard one that references the ipython development team. Any specific mention of module authors or maintainers should go into the module docstring.

As I mentioned, I was really going after the 'import Release'
statements, not after the authorship notices. But from now on, I'll
try to cleanup the copyright notices as I work on files.
"""

I did try to update at least those where I went fixing __author__ marks, as per your other comment. See the log comment in
http://bazaar.launchpad.net/~fdo.perez/ipython/trunk-dev/revision/1180
for more details on the logic I used. I took the 'team' 2008 statement and pushed to 09, and just closed the year gap on the old statements but otherwise left them as they were. I think that's how copyright statements are supposed to be updated, but I'm not sure. Feel free to let me know if it should be done otherwise.

> r1169:
>
> Are the numpy helper scripts for converting docstrings in place and working with our IPython?

Yes, they are. I've started using numpy docstrings in all new functions, and they work fine. I haven't gone updating old ones though... I did add mention of this in the dev docs.

"""
> How do we want to handle references in our docs.  Sphinx can now create a nice references section in the pdf files, but you have to use a particular format for the references.  The current form of the references you have put in::
>
>    .. _PEP 257: http://www.python.org/peps/pep-0257.html
>
> I don't think will end up in the references section.  How does numpy handle such things.  Have a look at how references are handled in the kernel documentation to see how I have been handling this.  My way may not be the best.  Let's figure out how all of us should handle this and then document it in our docs.

This one, I don't know. I'm going to look into what Matthew Brett did
for Nipy to see if I can find a good overall solution.
"""

I have to admit that I'm stumped on how to handle this one. Since it's not anything new in this branch per se, are you OK with merging and working on it together on trunk? I'm happy to make any local changes to the branch before merging, but I don't have a full solution for the references problem.

"""
> r1171:
>
> In ipy_profile_zope.py.  Should we just remove all the old __author__, etc. module attributes?

I'll do what we discussed: put the authorship notes I find in the
top-level docstring. This has the added benefit of putting them in
the generated API docs.
"""

I did go through most, as noted in the changelog. There's only a few left of very old external files, and Laurent's, which we should ask him about on list.

Thanks for the review!

lp:~fdo.perez/ipython/trunk-dev updated
1181. By Fernando Perez

Add information about our testing system, test writing tips, etc.

Revision history for this message
Brian Granger (ellisonbg) wrote :

> I did try to update at least those where I went fixing __author__ marks, as per your other comment.  See the log comment in
> http://bazaar.launchpad.net/~fdo.perez/ipython/trunk-dev/revision/1180
> for more details on the logic I used.  I took the 'team' 2008 statement and pushed to 09, and just closed the year gap on the old statements but otherwise left them as they were.   I think that's how copyright statements are supposed to be updated, but I'm not sure.  Feel free to let me know if it should be done otherwise.

Sounds fine by me.

>> r1169:
>>
>> Are the numpy helper scripts for converting docstrings in place and working with our IPython?
>
> Yes, they are.  I've started using numpy docstrings in all new functions, and they work fine.  I haven't gone updating old ones though...  I did add mention of this in the dev docs.

Great, I will start to write my docstring to this format.

>> How do we want to handle references in our docs.  Sphinx can now create a nice references section in the pdf files, but you have to use a particular format for the references.  The current form of the references you have put in::
>>
>>    .. _PEP 257: http://www.python.org/peps/pep-0257.html
>>
>> I don't think will end up in the references section.  How does numpy handle such things.  Have a look at how references are handled in the kernel documentation to see how I have been handling this.  My way may not be the best.  Let's figure out how all of us should handle this and then document it in our docs.
>
>
> This one, I don't know. I'm going to look into what Matthew Brett did
> for Nipy to see if I can find a good overall solution.
> """
>
> I have to admit that I'm stumped on how to handle this one.  Since it's not anything new in this branch per se, are you OK with merging and working on it together on trunk?  I'm happy to make any local changes to the branch before merging, but I don't have a full solution for the references problem.

That is fine. Just do the merge and we can slowly figure this one out.
 It is not a big deal because our existing refs don't do anything in
particular in this area, so we will have to change things anyway.

> Thanks for the review!

No problem.

Brian

--
Brian E. Granger, Ph.D.
Assistant Professor of Physics
Cal Poly State University, San Luis Obispo
<email address hidden>
<email address hidden>

lp:~fdo.perez/ipython/trunk-dev updated
1182. By Fernando Perez

Add a .bzrignore file for cleaner 'bzr status' output

Revision history for this message
Fernando Perez (fdo.perez) wrote :

On Tue, Mar 17, 2009 at 7:15 AM, Brian Granger <email address hidden> wrote:

> That is fine. Just do the merge and we can slowly figure this one out.
>  It is not a big deal because our existing refs don't do anything in
> particular in this area, so we will have to change things anyway.

OK. I just did the merge, this is large enough that I'll put a
message on the list so everyone can test it.

Thanks again for the review work, this one was a lot to look at :)

Cheers,

f

Preview Diff

[H/L] Next/Prev Comment, [J/K] Next/Prev File, [N/P] Next/Prev Hunk
=== modified file 'IPython/ColorANSI.py'
--- IPython/ColorANSI.py 2008-08-28 22:00:22 +0000
+++ IPython/ColorANSI.py 2009-03-11 06:53:19 +0000
@@ -1,7 +1,6 @@
1# -*- coding: utf-8 -*-1# -*- coding: utf-8 -*-
2"""Tools for coloring text in ANSI terminals.2"""Tools for coloring text in ANSI terminals.
33"""
4$Id: ColorANSI.py 2167 2007-03-21 06:57:50Z fperez $"""
54
6#*****************************************************************************5#*****************************************************************************
7# Copyright (C) 2002-2006 Fernando Perez. <fperez@colorado.edu>6# Copyright (C) 2002-2006 Fernando Perez. <fperez@colorado.edu>
@@ -10,10 +9,6 @@
10# the file COPYING, distributed as part of this software.9# the file COPYING, distributed as part of this software.
11#*****************************************************************************10#*****************************************************************************
1211
13from IPython import Release
14__author__ = '%s <%s>' % Release.authors['Fernando']
15__license__ = Release.license
16
17__all__ = ['TermColors','InputTermColors','ColorScheme','ColorSchemeTable']12__all__ = ['TermColors','InputTermColors','ColorScheme','ColorSchemeTable']
1813
19import os14import os
2015
=== modified file 'IPython/ConfigLoader.py'
--- IPython/ConfigLoader.py 2008-02-28 18:21:11 +0000
+++ IPython/ConfigLoader.py 2009-03-11 06:53:19 +0000
@@ -1,7 +1,6 @@
1# -*- coding: utf-8 -*-1# -*- coding: utf-8 -*-
2"""Configuration loader2"""Configuration loader
33"""
4$Id: ConfigLoader.py 1005 2006-01-12 08:39:26Z fperez $"""
54
6#*****************************************************************************5#*****************************************************************************
7# Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>6# Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
@@ -10,10 +9,6 @@
10# the file COPYING, distributed as part of this software.9# the file COPYING, distributed as part of this software.
11#*****************************************************************************10#*****************************************************************************
1211
13from IPython import Release
14__author__ = '%s <%s>' % Release.authors['Fernando']
15__license__ = Release.license
16
17import exceptions12import exceptions
18import os13import os
19from pprint import pprint14from pprint import pprint
@@ -73,14 +68,14 @@
73 # avoid including the same file more than once68 # avoid including the same file more than once
74 if fname in self.included:69 if fname in self.included:
75 return data70 return data
76 Xinfo = ultraTB.AutoFormattedTB()71 Xinfo = ultraTB.AutoFormattedTB(color_scheme='NoColor')
77 if convert==None and recurse_key : convert = {qwflat:recurse_key}72 if convert==None and recurse_key : convert = {qwflat:recurse_key}
78 # for production, change warn to 0:73 # for production, change warn to 0:
79 data.merge(read_dict(fname,convert,fs=self.field_sep,strip=1,74 data.merge(read_dict(fname,convert,fs=self.field_sep,strip=1,
80 warn=0,no_empty=0,**kw))75 warn=0,no_empty=0,**kw))
81 # keep track of successfully loaded files76 # keep track of successfully loaded files
82 self.included.append(fname)77 self.included.append(fname)
83 if recurse_key in data.keys():78 if recurse_key in data:
84 for incfilename in data[recurse_key]:79 for incfilename in data[recurse_key]:
85 found=080 found=0
86 try:81 try:
8782
=== modified file 'IPython/CrashHandler.py'
--- IPython/CrashHandler.py 2008-02-28 18:21:11 +0000
+++ IPython/CrashHandler.py 2009-03-11 06:53:19 +0000
@@ -1,7 +1,6 @@
1# -*- coding: utf-8 -*-1# -*- coding: utf-8 -*-
2"""sys.excepthook for IPython itself, leaves a detailed report on disk.2"""sys.excepthook for IPython itself, leaves a detailed report on disk.
33"""
4$Id: CrashHandler.py 2908 2007-12-30 21:07:46Z vivainio $"""
54
6#*****************************************************************************5#*****************************************************************************
7# Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>6# Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
87
=== modified file 'IPython/DPyGetOpt.py'
--- IPython/DPyGetOpt.py 2008-02-28 18:21:11 +0000
+++ IPython/DPyGetOpt.py 2009-03-11 06:53:19 +0000
@@ -1,8 +1,6 @@
1# -*- coding: utf-8 -*-1# -*- coding: utf-8 -*-
2"""DPyGetOpt -- Demiurge Python GetOptions Module2"""DPyGetOpt -- Demiurge Python GetOptions Module
33
4 $Id: DPyGetOpt.py 2872 2007-11-25 17:58:05Z fperez $
5
6This module is modeled after perl's Getopt::Long module-- which4This module is modeled after perl's Getopt::Long module-- which
7is, in turn, modeled after GNU's extended getopt() function.5is, in turn, modeled after GNU's extended getopt() function.
86
@@ -32,8 +30,7 @@
32and -baz options that appear on within the parsed argument list30and -baz options that appear on within the parsed argument list
33must have a real number argument and that the accumulated list31must have a real number argument and that the accumulated list
34of values will be available under the name 'foo'32of values will be available under the name 'foo'
3533"""
36$Id: DPyGetOpt.py 2872 2007-11-25 17:58:05Z fperez $"""
3734
38#*****************************************************************************35#*****************************************************************************
39#36#
4037
=== modified file 'IPython/Debugger.py'
--- IPython/Debugger.py 2008-06-07 06:50:18 +0000
+++ IPython/Debugger.py 2009-03-11 06:53:19 +0000
@@ -13,9 +13,7 @@
13changes. Licensing should therefore be under the standard Python terms. For13changes. Licensing should therefore be under the standard Python terms. For
14details on the PSF (Python Software Foundation) standard license, see:14details on the PSF (Python Software Foundation) standard license, see:
1515
16http://www.python.org/2.2.3/license.html16http://www.python.org/2.2.3/license.html"""
17
18$Id: Debugger.py 2913 2007-12-31 12:42:14Z vivainio $"""
1917
20#*****************************************************************************18#*****************************************************************************
21#19#
@@ -27,10 +25,6 @@
27#25#
28#*****************************************************************************26#*****************************************************************************
2927
30from IPython import Release
31__author__ = '%s <%s>' % Release.authors['Fernando']
32__license__ = 'Python'
33
34import bdb28import bdb
35import cmd29import cmd
36import linecache30import linecache
@@ -39,7 +33,7 @@
3933
40from IPython import PyColorize, ColorANSI, ipapi34from IPython import PyColorize, ColorANSI, ipapi
41from IPython.genutils import Term35from IPython.genutils import Term
42from IPython.excolors import ExceptionColors36from IPython.excolors import exception_colors
4337
44# See if we can use pydb.38# See if we can use pydb.
45has_pydb = False39has_pydb = False
@@ -210,7 +204,7 @@
210204
211 # Create color table: we copy the default one from the traceback205 # Create color table: we copy the default one from the traceback
212 # module and add a few attributes needed for debugging206 # module and add a few attributes needed for debugging
213 self.color_scheme_table = ExceptionColors.copy()207 self.color_scheme_table = exception_colors()
214208
215 # shorthands 209 # shorthands
216 C = ColorANSI.TermColors210 C = ColorANSI.TermColors
@@ -257,8 +251,7 @@
257251
258 # Create color table: we copy the default one from the traceback252 # Create color table: we copy the default one from the traceback
259 # module and add a few attributes needed for debugging253 # module and add a few attributes needed for debugging
260 ExceptionColors.set_active_scheme(color_scheme)254 self.color_scheme_table = exception_colors()
261 self.color_scheme_table = ExceptionColors.copy()
262255
263 # shorthands 256 # shorthands
264 C = ColorANSI.TermColors257 C = ColorANSI.TermColors
265258
=== modified file 'IPython/Extensions/InterpreterExec.py'
--- IPython/Extensions/InterpreterExec.py 2008-02-28 18:21:11 +0000
+++ IPython/Extensions/InterpreterExec.py 2009-03-11 06:53:19 +0000
@@ -4,8 +4,7 @@
4We define a special input line filter to allow typing lines which begin with4We define a special input line filter to allow typing lines which begin with
5'~', '/' or '.'. If one of those strings is encountered, it is automatically5'~', '/' or '.'. If one of those strings is encountered, it is automatically
6executed.6executed.
77"""
8$Id: InterpreterExec.py 2724 2007-09-07 08:05:38Z fperez $"""
98
10#*****************************************************************************9#*****************************************************************************
11# Copyright (C) 2004 W.J. van der Laan <gnufnork@hetdigitalegat.nl>10# Copyright (C) 2004 W.J. van der Laan <gnufnork@hetdigitalegat.nl>
@@ -15,11 +14,6 @@
15# the file COPYING, distributed as part of this software.14# the file COPYING, distributed as part of this software.
16#*****************************************************************************15#*****************************************************************************
1716
18from IPython import Release
19__author__ = 'W.J. van der Laan <gnufnork@hetdigitalegat.nl>, '\
20 '%s <%s>' % Release.authors['Fernando']
21__license__ = Release.license
22
23# TODO: deprecated17# TODO: deprecated
24def prefilter_shell(self,line,continuation):18def prefilter_shell(self,line,continuation):
25 """Alternate prefilter, modified for shell-like functionality.19 """Alternate prefilter, modified for shell-like functionality.
2620
=== modified file 'IPython/Extensions/clearcmd.py'
--- IPython/Extensions/clearcmd.py 2008-02-16 09:50:47 +0000
+++ IPython/Extensions/clearcmd.py 2009-03-10 19:39:05 +0000
@@ -5,43 +5,65 @@
5import gc5import gc
6ip = IPython.ipapi.get()6ip = IPython.ipapi.get()
77
8
9def clear_f(self,arg):8def clear_f(self,arg):
10 """ Clear various data (e.g. stored history data)9 """ Clear various data (e.g. stored history data)
11 10
11 %clear in - clear input history
12 %clear out - clear output history12 %clear out - clear output history
13 %clear in - clear input history
14 %clear shadow_compress - Compresses shadow history (to speed up ipython)13 %clear shadow_compress - Compresses shadow history (to speed up ipython)
15 %clear shadow_nuke - permanently erase all entries in shadow history14 %clear shadow_nuke - permanently erase all entries in shadow history
16 %clear dhist - clear dir history15 %clear dhist - clear dir history
16 %clear array - clear only variables that are NumPy arrays
17
18 Examples:
19
20 In [1]: clear in
21 Flushing input history
22
23 In [2]: clear shadow_compress
24 Compressing shadow history
25
26 In [3]: clear shadow_nuke
27 Erased all keys from shadow history
28
29 In [4]: clear dhist
30 Clearing directory history
17 """31 """
18 32
19 api = self.getapi()33 api = self.getapi()
34 user_ns = self.user_ns # local lookup, heavily used
35
36
20 for target in arg.split():37 for target in arg.split():
38
21 if target == 'out':39 if target == 'out':
22 print "Flushing output cache (%d entries)" % len(api.user_ns['_oh'])40 print "Flushing output cache (%d entries)" % len(user_ns['_oh'])
23 self.outputcache.flush()41 self.outputcache.flush()
42
24 elif target == 'in':43 elif target == 'in':
25 print "Flushing input history"44 print "Flushing input history"
26 from IPython import iplib
27 pc = self.outputcache.prompt_count + 145 pc = self.outputcache.prompt_count + 1
28 for n in range(1, pc):46 for n in range(1, pc):
29 key = '_i'+`n`47 key = '_i'+`n`
48 user_ns.pop(key,None)
30 try:49 try:
31 del self.user_ns[key]50 del user_ns[key]
32 except: pass51 except: pass
33 # must be done in-place52 # must be done in-place
34 self.input_hist[:] = ['\n'] * pc 53 self.input_hist[:] = ['\n'] * pc
35 self.input_hist_raw[:] = ['\n'] * pc54 self.input_hist_raw[:] = ['\n'] * pc
55
36 elif target == 'array':56 elif target == 'array':
57 # Support cleaning up numpy arrays
37 try:58 try:
38 pylab=ip.IP.pylab59 from numpy import ndarray
39 for x in self.user_ns.keys():60 # This must be done with items and not iteritems because we're
40 if isinstance(self.user_ns[x],pylab.arraytype):61 # going to modify the dict in-place.
41 del self.user_ns[x]62 for x,val in user_ns.items():
63 if isinstance(val,ndarray):
64 del user_ns[x]
42 except AttributeError:65 except AttributeError:
43 print "Clear array only available in -pylab mode"66 print "Clear array only works if Numpy is available."
44 gc.collect()
4567
46 elif target == 'shadow_compress':68 elif target == 'shadow_compress':
47 print "Compressing shadow history"69 print "Compressing shadow history"
@@ -51,16 +73,15 @@
51 print "Erased all keys from shadow history "73 print "Erased all keys from shadow history "
52 for k in ip.db.keys('shadowhist/*'):74 for k in ip.db.keys('shadowhist/*'):
53 del ip.db[k]75 del ip.db[k]
76
54 elif target == 'dhist':77 elif target == 'dhist':
55 print "Clearing directory history"78 print "Clearing directory history"
56 del ip.user_ns['_dh'][:]79 del user_ns['_dh'][:]
5780
58 81 gc.collect()
82
83# Activate the extension
59ip.expose_magic("clear",clear_f)84ip.expose_magic("clear",clear_f)
60import ipy_completers85import ipy_completers
61ipy_completers.quick_completer(86ipy_completers.quick_completer(
62 '%clear','in out shadow_nuke shadow_compress dhist')87 '%clear','in out shadow_nuke shadow_compress dhist')
63
64
65
66
6788
=== modified file 'IPython/Extensions/ext_rescapture.py'
--- IPython/Extensions/ext_rescapture.py 2008-02-16 09:50:47 +0000
+++ IPython/Extensions/ext_rescapture.py 2009-03-11 06:53:19 +0000
@@ -6,9 +6,6 @@
6var = %magic blah blah6var = %magic blah blah
77
8var = !ls8var = !ls
9
10$Id: genutils.py 1077 2006-01-24 18:15:27Z vivainio $
11
12"""9"""
1310
14import IPython.ipapi11import IPython.ipapi
1512
=== modified file 'IPython/Extensions/ipy_profile_zope.py'
--- IPython/Extensions/ipy_profile_zope.py 2008-02-16 09:50:47 +0000
+++ IPython/Extensions/ipy_profile_zope.py 2009-03-13 17:56:47 +0000
@@ -12,7 +12,6 @@
1212
13__author__ = """Stefan Eletzhofer <stefan.eletzhofer@inquant.de>"""13__author__ = """Stefan Eletzhofer <stefan.eletzhofer@inquant.de>"""
14__docformat__ = 'plaintext'14__docformat__ = 'plaintext'
15__revision__ = "$Revision$"
1615
17from IPython import ipapi16from IPython import ipapi
18from IPython import Release17from IPython import Release
1918
=== modified file 'IPython/Extensions/pspersistence.py'
--- IPython/Extensions/pspersistence.py 2008-06-03 20:03:02 +0000
+++ IPython/Extensions/pspersistence.py 2009-03-11 06:53:19 +0000
@@ -3,8 +3,6 @@
3%store magic for lightweight persistence.3%store magic for lightweight persistence.
44
5Stores variables, aliases etc. in PickleShare database.5Stores variables, aliases etc. in PickleShare database.
6
7$Id: iplib.py 1107 2006-01-30 19:02:20Z vivainio $
8"""6"""
97
10import IPython.ipapi8import IPython.ipapi
119
=== modified file 'IPython/FakeModule.py'
--- IPython/FakeModule.py 2008-02-28 18:21:11 +0000
+++ IPython/FakeModule.py 2009-03-11 06:53:19 +0000
@@ -4,8 +4,7 @@
44
5Needed to allow pickle to correctly resolve namespaces during IPython5Needed to allow pickle to correctly resolve namespaces during IPython
6sessions.6sessions.
77"""
8$Id: FakeModule.py 2754 2007-09-09 10:16:59Z fperez $"""
98
10#*****************************************************************************9#*****************************************************************************
11# Copyright (C) 2002-2004 Fernando Perez. <fperez@colorado.edu>10# Copyright (C) 2002-2004 Fernando Perez. <fperez@colorado.edu>
1211
=== modified file 'IPython/Gnuplot2.py'
--- IPython/Gnuplot2.py 2008-02-28 18:21:11 +0000
+++ IPython/Gnuplot2.py 2009-03-11 06:53:19 +0000
@@ -12,8 +12,7 @@
12Gnuplot, so it should be safe to do:12Gnuplot, so it should be safe to do:
1313
14import IPython.Gnuplot2 as Gnuplot14import IPython.Gnuplot2 as Gnuplot
1515"""
16$Id: Gnuplot2.py 1210 2006-03-13 01:19:31Z fperez $"""
1716
18import cStringIO17import cStringIO
19import os18import os
2019
=== modified file 'IPython/GnuplotInteractive.py'
--- IPython/GnuplotInteractive.py 2008-02-28 18:21:11 +0000
+++ IPython/GnuplotInteractive.py 2009-03-11 06:53:19 +0000
@@ -9,8 +9,7 @@
9See gphelp() below for details on the services offered by this module.9See gphelp() below for details on the services offered by this module.
1010
11Inspired by a suggestion/request from Arnd Baecker.11Inspired by a suggestion/request from Arnd Baecker.
1212"""
13$Id: GnuplotInteractive.py 389 2004-10-09 07:59:30Z fperez $"""
1413
15__all__ = ['Gnuplot','gp','gp_new','plot','plot2','splot','replot',14__all__ = ['Gnuplot','gp','gp_new','plot','plot2','splot','replot',
16 'hardcopy','gpdata','gpfile','gpstring','gpfunc','gpgrid',15 'hardcopy','gpdata','gpfile','gpstring','gpfunc','gpgrid',
1716
=== modified file 'IPython/GnuplotRuntime.py'
--- IPython/GnuplotRuntime.py 2008-02-28 18:21:11 +0000
+++ IPython/GnuplotRuntime.py 2009-03-11 06:53:19 +0000
@@ -47,8 +47,7 @@
47http://gnuplot-py.sourceforge.net/47http://gnuplot-py.sourceforge.net/
4848
49Inspired by a suggestion/request from Arnd Baecker.49Inspired by a suggestion/request from Arnd Baecker.
5050"""
51$Id: GnuplotRuntime.py 389 2004-10-09 07:59:30Z fperez $"""
5251
53__all__ = ['Gnuplot','gp','gp_new','Data','File','Func','GridData',52__all__ = ['Gnuplot','gp','gp_new','Data','File','Func','GridData',
54 'pm3d_config','eps_fix_bbox']53 'pm3d_config','eps_fix_bbox']
5554
=== modified file 'IPython/Itpl.py'
--- IPython/Itpl.py 2008-05-15 05:05:58 +0000
+++ IPython/Itpl.py 2009-03-11 06:53:19 +0000
@@ -27,7 +27,7 @@
27 import Itpl27 import Itpl
28 sys.stdout = Itpl.filter()28 sys.stdout = Itpl.filter()
29 f = "fancy"29 f = "fancy"
30 print "Isn't this $f?"30 print "Is this not $f?"
31 print "Standard output has been replaced with a $sys.stdout object."31 print "Standard output has been replaced with a $sys.stdout object."
32 sys.stdout = Itpl.unfilter()32 sys.stdout = Itpl.unfilter()
33 print "Okay, back $to $normal."33 print "Okay, back $to $normal."
@@ -43,9 +43,7 @@
43 print str(s)43 print str(s)
44 foo = "bar"44 foo = "bar"
45 print str(s)45 print str(s)
4646"""
47$Id: Itpl.py 2918 2007-12-31 14:34:47Z vivainio $
48""" # ' -> close an open quote for stupid emacs
4947
50#*****************************************************************************48#*****************************************************************************
51#49#
5250
=== modified file 'IPython/Logger.py'
--- IPython/Logger.py 2008-08-14 12:48:09 +0000
+++ IPython/Logger.py 2009-03-11 06:53:19 +0000
@@ -1,8 +1,6 @@
1# -*- coding: utf-8 -*-1# -*- coding: utf-8 -*-
2"""2"""
3Logger class for IPython's logging facilities.3Logger class for IPython's logging facilities.
4
5$Id: Logger.py 2875 2007-11-26 08:37:39Z fperez $
6"""4"""
75
8#*****************************************************************************6#*****************************************************************************
@@ -16,11 +14,6 @@
16#****************************************************************************14#****************************************************************************
17# Modules and globals15# Modules and globals
1816
19from IPython import Release
20__author__ = '%s <%s>\n%s <%s>' % \
21 ( Release.authors['Janko'] + Release.authors['Fernando'] )
22__license__ = Release.license
23
24# Python standard modules17# Python standard modules
25import glob18import glob
26import os19import os
2720
=== modified file 'IPython/Magic.py'
--- IPython/Magic.py 2008-09-17 19:07:48 +0000
+++ IPython/Magic.py 2009-03-13 17:56:19 +0000
@@ -1,7 +1,6 @@
1# -*- coding: utf-8 -*-1# -*- coding: utf-8 -*-
2"""Magic functions for InteractiveShell.2"""Magic functions for InteractiveShell.
33"""
4$Id: Magic.py 2996 2008-01-30 06:31:39Z fperez $"""
54
6#*****************************************************************************5#*****************************************************************************
7# Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and6# Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
@@ -14,11 +13,6 @@
14#****************************************************************************13#****************************************************************************
15# Modules and globals14# Modules and globals
1615
17from IPython import Release
18__author__ = '%s <%s>\n%s <%s>' % \
19 ( Release.authors['Janko'] + Release.authors['Fernando'] )
20__license__ = Release.license
21
22# Python standard modules16# Python standard modules
23import __builtin__17import __builtin__
24import bdb18import bdb
@@ -1050,10 +1044,33 @@
1050 def magic_reset(self, parameter_s=''):1044 def magic_reset(self, parameter_s=''):
1051 """Resets the namespace by removing all names defined by the user.1045 """Resets the namespace by removing all names defined by the user.
10521046
1053 Input/Output history are left around in case you need them."""1047 Input/Output history are left around in case you need them.
10541048
1055 ans = self.shell.ask_yes_no(1049 Parameters
1056 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")1050 ----------
1051 -y : force reset without asking for confirmation.
1052
1053 Examples
1054 --------
1055 In [6]: a = 1
1056
1057 In [7]: a
1058 Out[7]: 1
1059
1060 In [8]: 'a' in _ip.user_ns
1061 Out[8]: True
1062
1063 In [9]: %reset -f
1064
1065 In [10]: 'a' in _ip.user_ns
1066 Out[10]: False
1067 """
1068
1069 if parameter_s == '-f':
1070 ans = True
1071 else:
1072 ans = self.shell.ask_yes_no(
1073 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
1057 if not ans:1074 if not ans:
1058 print 'Nothing done.'1075 print 'Nothing done.'
1059 return1076 return
@@ -1063,7 +1080,7 @@
1063 1080
1064 # Also flush the private list of module references kept for script1081 # Also flush the private list of module references kept for script
1065 # execution protection1082 # execution protection
1066 self.shell._user_main_modules[:] = []1083 self.shell.clear_main_mod_cache()
10671084
1068 def magic_logstart(self,parameter_s=''):1085 def magic_logstart(self,parameter_s=''):
1069 """Start logging anywhere in a session.1086 """Start logging anywhere in a session.
@@ -1422,7 +1439,8 @@
1422 return None1439 return None
14231440
1424 @testdec.skip_doctest1441 @testdec.skip_doctest
1425 def magic_run(self, parameter_s ='',runner=None):1442 def magic_run(self, parameter_s ='',runner=None,
1443 file_finder=get_py_filename):
1426 """Run the named file inside IPython as a program.1444 """Run the named file inside IPython as a program.
14271445
1428 Usage:\\1446 Usage:\\
@@ -1537,7 +1555,7 @@
1537 mode='list',list_all=1)1555 mode='list',list_all=1)
15381556
1539 try:1557 try:
1540 filename = get_py_filename(arg_lst[0])1558 filename = file_finder(arg_lst[0])
1541 except IndexError:1559 except IndexError:
1542 warn('you must provide at least a filename.')1560 warn('you must provide at least a filename.')
1543 print '\n%run:\n',OInspect.getdoc(self.magic_run)1561 print '\n%run:\n',OInspect.getdoc(self.magic_run)
@@ -1573,10 +1591,13 @@
1573 main_mod = FakeModule()1591 main_mod = FakeModule()
1574 prog_ns = main_mod.__dict__1592 prog_ns = main_mod.__dict__
1575 prog_ns['__name__'] = name1593 prog_ns['__name__'] = name
1594
1576 # The shell MUST hold a reference to main_mod so after %run exits,1595 # The shell MUST hold a reference to main_mod so after %run exits,
1577 # the python deletion mechanism doesn't zero it out (leaving1596 # the python deletion mechanism doesn't zero it out (leaving
1578 # dangling references)1597 # dangling references). However, we should drop old versions of
1579 self.shell._user_main_modules.append(main_mod)1598 # main_mod. There is now a proper API to manage this caching in
1599 # the main shell object, we use that.
1600 self.shell.cache_main_mod(main_mod)
15801601
1581 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must1602 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
1582 # set the __file__ global in the script's namespace1603 # set the __file__ global in the script's namespace
15831604
=== modified file 'IPython/OInspect.py'
--- IPython/OInspect.py 2008-07-29 22:57:51 +0000
+++ IPython/OInspect.py 2009-03-11 06:53:19 +0000
@@ -5,8 +5,6 @@
55
6Similar in spirit to the inspect module, but all calls take a name argument to6Similar in spirit to the inspect module, but all calls take a name argument to
7reference the name under which an object is being read.7reference the name under which an object is being read.
8
9$Id: OInspect.py 2843 2007-10-15 21:22:32Z fperez $
10"""8"""
119
12#*****************************************************************************10#*****************************************************************************
@@ -16,10 +14,6 @@
16# the file COPYING, distributed as part of this software.14# the file COPYING, distributed as part of this software.
17#*****************************************************************************15#*****************************************************************************
1816
19from IPython import Release
20__author__ = '%s <%s>' % Release.authors['Fernando']
21__license__ = Release.license
22
23__all__ = ['Inspector','InspectColors']17__all__ = ['Inspector','InspectColors']
2418
25# stdlib modules19# stdlib modules
2620
=== modified file 'IPython/OutputTrap.py'
--- IPython/OutputTrap.py 2008-02-28 18:21:11 +0000
+++ IPython/OutputTrap.py 2009-03-11 06:53:19 +0000
@@ -1,7 +1,6 @@
1# -*- coding: utf-8 -*-1# -*- coding: utf-8 -*-
2"""Class to trap stdout and stderr and log them separately.2"""Class to trap stdout and stderr and log them separately.
33"""
4$Id: OutputTrap.py 958 2005-12-27 23:17:51Z fperez $"""
54
6#*****************************************************************************5#*****************************************************************************
7# Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>6# Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
@@ -10,10 +9,6 @@
10# the file COPYING, distributed as part of this software.9# the file COPYING, distributed as part of this software.
11#*****************************************************************************10#*****************************************************************************
1211
13from IPython import Release
14__author__ = '%s <%s>' % Release.authors['Fernando']
15__license__ = Release.license
16
17import exceptions12import exceptions
18import sys13import sys
19from cStringIO import StringIO14from cStringIO import StringIO
2015
=== modified file 'IPython/Prompts.py'
--- IPython/Prompts.py 2008-02-28 18:21:11 +0000
+++ IPython/Prompts.py 2009-03-11 06:53:19 +0000
@@ -1,8 +1,7 @@
1# -*- coding: utf-8 -*-1# -*- coding: utf-8 -*-
2"""2"""
3Classes for handling input/output prompts.3Classes for handling input/output prompts.
44"""
5$Id: Prompts.py 3026 2008-02-07 16:03:16Z vivainio $"""
65
7#*****************************************************************************6#*****************************************************************************
8# Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu>7# Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu>
98
=== modified file 'IPython/PyColorize.py'
--- IPython/PyColorize.py 2008-08-23 22:34:55 +0000
+++ IPython/PyColorize.py 2009-03-11 06:53:19 +0000
@@ -1,34 +1,33 @@
1# -*- coding: utf-8 -*-1# -*- coding: utf-8 -*-
2"""2"""
3 Class and program to colorize python source code for ANSI terminals.3Class and program to colorize python source code for ANSI terminals.
44
5 Based on an HTML code highlighter by Jurgen Hermann found at:5Based on an HTML code highlighter by Jurgen Hermann found at:
6 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/522986http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52298
77
8 Modifications by Fernando Perez (fperez@colorado.edu).8Modifications by Fernando Perez (fperez@colorado.edu).
99
10 Information on the original HTML highlighter follows:10Information on the original HTML highlighter follows:
11 11
12 MoinMoin - Python Source Parser12MoinMoin - Python Source Parser
1313
14 Title: Colorize Python source using the built-in tokenizer14Title: Colorize Python source using the built-in tokenizer
15 15
16 Submitter: Jurgen Hermann16Submitter: Jurgen Hermann
17 Last Updated:2001/04/0617Last Updated:2001/04/06
18 18
19 Version no:1.219Version no:1.2
2020
21 Description:21Description:
2222
23 This code is part of MoinMoin (http://moin.sourceforge.net/) and converts23This code is part of MoinMoin (http://moin.sourceforge.net/) and converts
24 Python source code to HTML markup, rendering comments, keywords,24Python source code to HTML markup, rendering comments, keywords,
25 operators, numeric and string literals in different colors.25operators, numeric and string literals in different colors.
2626
27 It shows how to use the built-in keyword, token and tokenize modules to27It shows how to use the built-in keyword, token and tokenize modules to
28 scan Python source code and re-emit it with no changes to its original28scan Python source code and re-emit it with no changes to its original
29 formatting (which is the hard part).29formatting (which is the hard part).
3030"""
31 $Id: PyColorize.py 2586 2007-08-06 19:30:09Z vivainio $"""
3231
33__all__ = ['ANSICodeColors','Parser']32__all__ = ['ANSICodeColors','Parser']
3433
3534
=== modified file 'IPython/Shell.py'
--- IPython/Shell.py 2008-08-24 06:10:55 +0000
+++ IPython/Shell.py 2009-03-11 06:53:19 +0000
@@ -3,8 +3,7 @@
33
4All the matplotlib support code was co-developed with John Hunter,4All the matplotlib support code was co-developed with John Hunter,
5matplotlib's author.5matplotlib's author.
66"""
7$Id: Shell.py 3024 2008-02-07 15:34:42Z darren.dale $"""
87
9#*****************************************************************************8#*****************************************************************************
10# Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu>9# Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu>
@@ -13,10 +12,6 @@
13# the file COPYING, distributed as part of this software.12# the file COPYING, distributed as part of this software.
14#*****************************************************************************13#*****************************************************************************
1514
16from IPython import Release
17__author__ = '%s <%s>' % Release.authors['Fernando']
18__license__ = Release.license
19
20# Code begins15# Code begins
21# Stdlib imports16# Stdlib imports
22import __builtin__17import __builtin__
2318
=== modified file 'IPython/UserConfig/ipythonrc'
--- IPython/UserConfig/ipythonrc 2008-02-28 18:21:11 +0000
+++ IPython/UserConfig/ipythonrc 2009-03-13 17:56:47 +0000
@@ -1,5 +1,4 @@
1# -*- Mode: Shell-Script -*- Not really, but shows comments correctly1# -*- Mode: Shell-Script -*- Not really, but shows comments correctly
2# $Id: ipythonrc 2156 2007-03-19 02:32:19Z fperez $
32
4#***************************************************************************3#***************************************************************************
5#4#
65
=== modified file 'IPython/__init__.py'
--- IPython/__init__.py 2008-08-02 09:05:40 +0000
+++ IPython/__init__.py 2009-03-11 06:53:19 +0000
@@ -25,9 +25,8 @@
2525
26 iii - serve as an embeddable, ready to go interpreter for your own programs.26 iii - serve as an embeddable, ready to go interpreter for your own programs.
2727
28IPython requires Python 2.3 or newer.28IPython requires Python 2.4 or newer.
2929"""
30$Id: __init__.py 2399 2007-05-26 10:23:10Z vivainio $"""
3130
32#*****************************************************************************31#*****************************************************************************
33# Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>32# Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
3433
=== modified file 'IPython/background_jobs.py'
--- IPython/background_jobs.py 2008-02-28 18:21:11 +0000
+++ IPython/background_jobs.py 2009-03-11 06:53:19 +0000
@@ -17,8 +17,6 @@
1717
18(although ultimately no code from this text was used, as IPython's system is a18(although ultimately no code from this text was used, as IPython's system is a
19separate implementation).19separate implementation).
20
21$Id: background_jobs.py 994 2006-01-08 08:29:44Z fperez $
22"""20"""
2321
24#*****************************************************************************22#*****************************************************************************
@@ -28,10 +26,6 @@
28# the file COPYING, distributed as part of this software.26# the file COPYING, distributed as part of this software.
29#*****************************************************************************27#*****************************************************************************
3028
31from IPython import Release
32__author__ = '%s <%s>' % Release.authors['Fernando']
33__license__ = Release.license
34
35# Code begins29# Code begins
36import sys30import sys
37import threading31import threading
3832
=== modified file 'IPython/completer.py'
--- IPython/completer.py 2008-08-21 09:42:55 +0000
+++ IPython/completer.py 2009-03-11 01:24:53 +0000
@@ -6,7 +6,6 @@
6functionality specific to IPython, so this module will continue to live as an6functionality specific to IPython, so this module will continue to live as an
7IPython-specific utility.7IPython-specific utility.
88
9---------------------------------------------------------------------------
10Original rlcompleter documentation:9Original rlcompleter documentation:
1110
12This requires the latest extension to the readline module (the11This requires the latest extension to the readline module (the
1312
=== modified file 'IPython/deep_reload.py'
--- IPython/deep_reload.py 2008-07-17 06:37:49 +0000
+++ IPython/deep_reload.py 2009-03-11 06:53:19 +0000
@@ -12,8 +12,7 @@
12 >>> __builtin__.dreload = deep_reload.reload12 >>> __builtin__.dreload = deep_reload.reload
13 13
14This code is almost entirely based on knee.py from the standard library.14This code is almost entirely based on knee.py from the standard library.
1515"""
16$Id: deep_reload.py 958 2005-12-27 23:17:51Z fperez $"""
1716
18#*****************************************************************************17#*****************************************************************************
19# Copyright (C) 2001 Nathaniel Gray <n8gray@caltech.edu>18# Copyright (C) 2001 Nathaniel Gray <n8gray@caltech.edu>
@@ -22,12 +21,6 @@
22# the file COPYING, distributed as part of this software.21# the file COPYING, distributed as part of this software.
23#*****************************************************************************22#*****************************************************************************
2423
25from IPython import Release # do it explicitly so pydoc can see it - pydoc bug
26__author__ = '%s <%s>' % Release.authors['Nathan']
27__license__ = Release.license
28__version__ = "0.5"
29__date__ = "21 August 2001"
30
31import __builtin__24import __builtin__
32import imp25import imp
33import sys26import sys
3427
=== modified file 'IPython/excolors.py'
--- IPython/excolors.py 2008-02-16 09:50:47 +0000
+++ IPython/excolors.py 2009-03-13 17:56:47 +0000
@@ -1,8 +1,7 @@
1# -*- coding: utf-8 -*-1# -*- coding: utf-8 -*-
2"""2"""
3Color schemes for exception handling code in IPython.3Color schemes for exception handling code in IPython.
44"""
5$Id: Prompts.py 638 2005-07-18 03:01:41Z fperez $"""
65
7#*****************************************************************************6#*****************************************************************************
8# Copyright (C) 2005-2006 Fernando Perez <fperez@colorado.edu>7# Copyright (C) 2005-2006 Fernando Perez <fperez@colorado.edu>
@@ -11,99 +10,128 @@
11# the file COPYING, distributed as part of this software.10# the file COPYING, distributed as part of this software.
12#*****************************************************************************11#*****************************************************************************
1312
14from IPython import Release
15__author__ = '%s <%s>' % Release.authors['Fernando']
16__license__ = Release.license
17__version__ = Release.version
18
19#****************************************************************************13#****************************************************************************
20# Required modules14# Required modules
21from IPython.ColorANSI import ColorSchemeTable, TermColors, ColorScheme15from IPython.ColorANSI import ColorSchemeTable, TermColors, ColorScheme
2216
23ExceptionColors = ColorSchemeTable()17def exception_colors():
2418 """Return a color table with fields for exception reporting.
25# Populate it with color schemes19
26C = TermColors # shorthand and local lookup20 The table is an instance of ColorSchemeTable with schemes added for
27ExceptionColors.add_scheme(ColorScheme(21 'Linux', 'LightBG' and 'NoColor' and fields for exception handling filled
28 'NoColor',22 in.
29 # The color to be used for the top line23
30 topline = C.NoColor,24 Examples:
3125
32 # The colors to be used in the traceback26 >>> ec = exception_colors()
33 filename = C.NoColor,27 >>> ec.active_scheme_name
34 lineno = C.NoColor,28 ''
35 name = C.NoColor,29 >>> print ec.active_colors
36 vName = C.NoColor,30 None
37 val = C.NoColor,31
38 em = C.NoColor,32 Now we activate a color scheme:
39 33 >>> ec.set_active_scheme('NoColor')
40 # Emphasized colors for the last frame of the traceback34 >>> ec.active_scheme_name
41 normalEm = C.NoColor,35 'NoColor'
42 filenameEm = C.NoColor,36 >>> ec.active_colors.keys()
43 linenoEm = C.NoColor,37 ['em', 'caret', '__allownew', 'name', 'val', 'vName', 'Normal', 'normalEm',
44 nameEm = C.NoColor,38 'filename', 'linenoEm', 'excName', 'lineno', 'valEm', 'filenameEm',
45 valEm = C.NoColor,39 'nameEm', 'line', 'topline']
46 40 """
47 # Colors for printing the exception41
48 excName = C.NoColor,42 ex_colors = ColorSchemeTable()
49 line = C.NoColor,43
50 caret = C.NoColor,44 # Populate it with color schemes
51 Normal = C.NoColor45 C = TermColors # shorthand and local lookup
52 ))46 ex_colors.add_scheme(ColorScheme(
5347 'NoColor',
54# make some schemes as instances so we can copy them for modification easily48 # The color to be used for the top line
55ExceptionColors.add_scheme(ColorScheme(49 topline = C.NoColor,
56 'Linux',50
57 # The color to be used for the top line51 # The colors to be used in the traceback
58 topline = C.LightRed,52 filename = C.NoColor,
5953 lineno = C.NoColor,
60 # The colors to be used in the traceback54 name = C.NoColor,
61 filename = C.Green,55 vName = C.NoColor,
62 lineno = C.Green,56 val = C.NoColor,
63 name = C.Purple,57 em = C.NoColor,
64 vName = C.Cyan,58
65 val = C.Green,59 # Emphasized colors for the last frame of the traceback
66 em = C.LightCyan,60 normalEm = C.NoColor,
6761 filenameEm = C.NoColor,
68 # Emphasized colors for the last frame of the traceback62 linenoEm = C.NoColor,
69 normalEm = C.LightCyan,63 nameEm = C.NoColor,
70 filenameEm = C.LightGreen,64 valEm = C.NoColor,
71 linenoEm = C.LightGreen,65
72 nameEm = C.LightPurple,66 # Colors for printing the exception
73 valEm = C.LightBlue,67 excName = C.NoColor,
7468 line = C.NoColor,
75 # Colors for printing the exception69 caret = C.NoColor,
76 excName = C.LightRed,70 Normal = C.NoColor
77 line = C.Yellow,71 ))
78 caret = C.White,72
79 Normal = C.Normal73 # make some schemes as instances so we can copy them for modification easily
80 ))74 ex_colors.add_scheme(ColorScheme(
8175 'Linux',
82# For light backgrounds, swap dark/light colors76 # The color to be used for the top line
83ExceptionColors.add_scheme(ColorScheme(77 topline = C.LightRed,
84 'LightBG',78
85 # The color to be used for the top line79 # The colors to be used in the traceback
86 topline = C.Red,80 filename = C.Green,
87 81 lineno = C.Green,
88 # The colors to be used in the traceback82 name = C.Purple,
89 filename = C.LightGreen,83 vName = C.Cyan,
90 lineno = C.LightGreen,84 val = C.Green,
91 name = C.LightPurple,85 em = C.LightCyan,
92 vName = C.Cyan,86
93 val = C.LightGreen,87 # Emphasized colors for the last frame of the traceback
94 em = C.Cyan,88 normalEm = C.LightCyan,
9589 filenameEm = C.LightGreen,
96 # Emphasized colors for the last frame of the traceback90 linenoEm = C.LightGreen,
97 normalEm = C.Cyan,91 nameEm = C.LightPurple,
98 filenameEm = C.Green,92 valEm = C.LightBlue,
99 linenoEm = C.Green,93
100 nameEm = C.Purple,94 # Colors for printing the exception
101 valEm = C.Blue,95 excName = C.LightRed,
10296 line = C.Yellow,
103 # Colors for printing the exception97 caret = C.White,
104 excName = C.Red,98 Normal = C.Normal
105 #line = C.Brown, # brown often is displayed as yellow99 ))
106 line = C.Red,100
107 caret = C.Normal,101 # For light backgrounds, swap dark/light colors
108 Normal = C.Normal102 ex_colors.add_scheme(ColorScheme(
109 ))103 'LightBG',
104 # The color to be used for the top line
105 topline = C.Red,
106
107 # The colors to be used in the traceback
108 filename = C.LightGreen,
109 lineno = C.LightGreen,
110 name = C.LightPurple,
111 vName = C.Cyan,
112 val = C.LightGreen,
113 em = C.Cyan,
114
115 # Emphasized colors for the last frame of the traceback
116 normalEm = C.Cyan,
117 filenameEm = C.Green,
118 linenoEm = C.Green,
119 nameEm = C.Purple,
120 valEm = C.Blue,
121
122 # Colors for printing the exception
123 excName = C.Red,
124 #line = C.Brown, # brown often is displayed as yellow
125 line = C.Red,
126 caret = C.Normal,
127 Normal = C.Normal,
128 ))
129
130 return ex_colors
131
132
133# For backwards compatibility, keep around a single global object. Note that
134# this should NOT be used, the factory function should be used instead, since
135# these objects are stateful and it's very easy to get strange bugs if any code
136# modifies the module-level object's state.
137ExceptionColors = exception_colors()
110138
=== modified file 'IPython/external/Itpl.py'
--- IPython/external/Itpl.py 2008-06-06 19:58:56 +0000
+++ IPython/external/Itpl.py 2009-03-11 06:53:19 +0000
@@ -27,7 +27,7 @@
27 import Itpl27 import Itpl
28 sys.stdout = Itpl.filter()28 sys.stdout = Itpl.filter()
29 f = "fancy"29 f = "fancy"
30 print "Isn't this $f?"30 print "Is this not $f?"
31 print "Standard output has been replaced with a $sys.stdout object."31 print "Standard output has been replaced with a $sys.stdout object."
32 sys.stdout = Itpl.unfilter()32 sys.stdout = Itpl.unfilter()
33 print "Okay, back $to $normal."33 print "Okay, back $to $normal."
@@ -43,9 +43,7 @@
43 print str(s)43 print str(s)
44 foo = "bar"44 foo = "bar"
45 print str(s)45 print str(s)
4646"""
47$Id: Itpl.py 2305 2007-05-04 05:34:42Z bgranger $
48""" # ' -> close an open quote for stupid emacs
4947
50#*****************************************************************************48#*****************************************************************************
51#49#
5250
=== modified file 'IPython/genutils.py'
--- IPython/genutils.py 2008-09-03 23:31:20 +0000
+++ IPython/genutils.py 2009-03-11 06:53:19 +0000
@@ -1,11 +1,9 @@
1# -*- coding: utf-8 -*-1# -*- coding: utf-8 -*-
2"""2"""General purpose utilities.
3General purpose utilities.
43
5This is a grab-bag of stuff I find useful in most programs I write. Some of4This is a grab-bag of stuff I find useful in most programs I write. Some of
6these things are also convenient when working at the command line.5these things are also convenient when working at the command line.
76"""
8$Id: genutils.py 2998 2008-01-31 10:06:04Z vivainio $"""
97
10#*****************************************************************************8#*****************************************************************************
11# Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>9# Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
@@ -14,10 +12,6 @@
14# the file COPYING, distributed as part of this software.12# the file COPYING, distributed as part of this software.
15#*****************************************************************************13#*****************************************************************************
1614
17from IPython import Release
18__author__ = '%s <%s>' % Release.authors['Fernando']
19__license__ = Release.license
20
21#****************************************************************************15#****************************************************************************
22# required modules from the Python standard library16# required modules from the Python standard library
23import __main__17import __main__
@@ -1234,11 +1228,11 @@
1234def make_quoted_expr(s):1228def make_quoted_expr(s):
1235 """Return string s in appropriate quotes, using raw string if possible.1229 """Return string s in appropriate quotes, using raw string if possible.
12361230
1237 Effectively this turns string: cd \ao\ao\1231 XXX - example removed because it caused encoding errors in documentation
1238 to: r"cd \ao\ao\_"[:-1]1232 generation. We need a new example that doesn't contain invalid chars.
12391233
1240 Note the use of raw string and padding at the end to allow trailing backslash.1234 Note the use of raw string and padding at the end to allow trailing
12411235 backslash.
1242 """1236 """
12431237
1244 tail = ''1238 tail = ''
12451239
=== modified file 'IPython/history.py'
--- IPython/history.py 2008-09-13 08:39:54 +0000
+++ IPython/history.py 2008-11-10 00:15:00 +0000
@@ -1,5 +1,4 @@
1# -*- coding: utf-8 -*-1# -*- coding: utf-8 -*-
2
3""" History related magics and functionality """2""" History related magics and functionality """
43
5# Stdlib imports4# Stdlib imports
@@ -7,7 +6,7 @@
7import os6import os
87
9# IPython imports8# IPython imports
10from IPython.genutils import Term, ask_yes_no9from IPython.genutils import Term, ask_yes_no, warn
11import IPython.ipapi10import IPython.ipapi
1211
13def magic_history(self, parameter_s = ''):12def magic_history(self, parameter_s = ''):
@@ -47,8 +46,6 @@
47 -f FILENAME: instead of printing the output to the screen, redirect it to46 -f FILENAME: instead of printing the output to the screen, redirect it to
48 the given file. The file is always overwritten, though IPython asks for47 the given file. The file is always overwritten, though IPython asks for
49 confirmation first if it already exists.48 confirmation first if it already exists.
50
51
52 """49 """
5350
54 ip = self.api51 ip = self.api
@@ -62,31 +59,28 @@
62 try:59 try:
63 outfname = opts['f']60 outfname = opts['f']
64 except KeyError:61 except KeyError:
65 outfile = Term.cout62 outfile = Term.cout # default
66 # We don't want to close stdout at the end!63 # We don't want to close stdout at the end!
67 close_at_end = False64 close_at_end = False
68 else:65 else:
69 if os.path.exists(outfname):66 if os.path.exists(outfname):
70 ans = ask_yes_no("File %r exists. Overwrite?" % outfname)67 if not ask_yes_no("File %r exists. Overwrite?" % outfname):
71 if not ans:
72 print 'Aborting.'68 print 'Aborting.'
73 return69 return
74 else:70
75 outfile = open(outfname,'w')71 outfile = open(outfname,'w')
76 close_at_end = True72 close_at_end = True
77 73
7874 if 't' in opts:
79 if opts.has_key('t'):
80 input_hist = shell.input_hist75 input_hist = shell.input_hist
81 elif opts.has_key('r'):76 elif 'r' in opts:
82 input_hist = shell.input_hist_raw77 input_hist = shell.input_hist_raw
83 else:78 else:
84 input_hist = shell.input_hist79 input_hist = shell.input_hist
85 80
86
87 default_length = 4081 default_length = 40
88 pattern = None82 pattern = None
89 if opts.has_key('g'):83 if 'g' in opts:
90 init = 184 init = 1
91 final = len(input_hist)85 final = len(input_hist)
92 parts = parameter_s.split(None,1)86 parts = parameter_s.split(None,1)
@@ -138,13 +132,11 @@
138 outfile.close()132 outfile.close()
139133
140134
141
142def magic_hist(self, parameter_s=''):135def magic_hist(self, parameter_s=''):
143 """Alternate name for %history."""136 """Alternate name for %history."""
144 return self.magic_history(parameter_s)137 return self.magic_history(parameter_s)
145138
146139
147
148def rep_f(self, arg):140def rep_f(self, arg):
149 r""" Repeat a command, or get command to input line for editing141 r""" Repeat a command, or get command to input line for editing
150142
@@ -173,11 +165,9 @@
173 %rep foo165 %rep foo
174 166
175 Place the most recent line that has the substring "foo" to next input.167 Place the most recent line that has the substring "foo" to next input.
176 (e.g. 'svn ci -m foobar').168 (e.g. 'svn ci -m foobar').
177
178 """169 """
179 170
180
181 opts,args = self.parse_options(arg,'',mode='list')171 opts,args = self.parse_options(arg,'',mode='list')
182 ip = self.api 172 ip = self.api
183 if not args:173 if not args:
@@ -206,7 +196,6 @@
206 ip.set_next_input(str(h).rstrip())196 ip.set_next_input(str(h).rstrip())
207 return197 return
208 198
209
210 try:199 try:
211 lines = self.extract_input_slices(args, True)200 lines = self.extract_input_slices(args, True)
212 print "lines",lines201 print "lines",lines
@@ -215,7 +204,6 @@
215 print "Not found in recent history:", args204 print "Not found in recent history:", args
216 205
217206
218
219_sentinel = object()207_sentinel = object()
220208
221class ShadowHist:209class ShadowHist:
@@ -259,23 +247,12 @@
259 if k == idx:247 if k == idx:
260 return v248 return v
261249
262def test_shist():
263 from IPython.Extensions import pickleshare
264 db = pickleshare.PickleShareDB('~/shist')
265 s = ShadowHist(db)
266 s.add('hello')
267 s.add('world')
268 s.add('hello')
269 s.add('hello')
270 s.add('karhu')
271 print "all",s.all()
272 print s.get(2)
273250
274def init_ipython(ip):251def init_ipython(ip):
252 import ipy_completers
253
275 ip.expose_magic("rep",rep_f) 254 ip.expose_magic("rep",rep_f)
276 ip.expose_magic("hist",magic_hist) 255 ip.expose_magic("hist",magic_hist)
277 ip.expose_magic("history",magic_history)256 ip.expose_magic("history",magic_history)
278257
279 import ipy_completers
280 ipy_completers.quick_completer('%hist' ,'-g -t -r -n')258 ipy_completers.quick_completer('%hist' ,'-g -t -r -n')
281#test_shist()
282259
=== modified file 'IPython/hooks.py'
--- IPython/hooks.py 2008-06-07 06:50:18 +0000
+++ IPython/hooks.py 2009-03-11 06:53:19 +0000
@@ -31,8 +31,7 @@
3131
32You can then enable the functionality by doing 'import myiphooks'32You can then enable the functionality by doing 'import myiphooks'
33somewhere in your configuration files or ipython command line.33somewhere in your configuration files or ipython command line.
3434"""
35$Id: hooks.py 2998 2008-01-31 10:06:04Z vivainio $"""
3635
37#*****************************************************************************36#*****************************************************************************
38# Copyright (C) 2005 Fernando Perez. <fperez@colorado.edu>37# Copyright (C) 2005 Fernando Perez. <fperez@colorado.edu>
@@ -41,11 +40,7 @@
41# the file COPYING, distributed as part of this software.40# the file COPYING, distributed as part of this software.
42#*****************************************************************************41#*****************************************************************************
4342
44from IPython import Release
45from IPython import ipapi43from IPython import ipapi
46__author__ = '%s <%s>' % Release.authors['Fernando']
47__license__ = Release.license
48__version__ = Release.version
4944
50import os,bisect45import os,bisect
51from genutils import Term,shell46from genutils import Term,shell
5247
=== modified file 'IPython/ipapi.py'
--- IPython/ipapi.py 2008-08-13 06:05:45 +0000
+++ IPython/ipapi.py 2009-03-11 01:24:53 +0000
@@ -24,7 +24,6 @@
24personal configuration (as opposed to boilerplate ipythonrc-PROFILENAME 24personal configuration (as opposed to boilerplate ipythonrc-PROFILENAME
25stuff) in there. 25stuff) in there.
2626
27-----------------------------------------------
28import IPython.ipapi27import IPython.ipapi
29ip = IPython.ipapi.get()28ip = IPython.ipapi.get()
3029
3130
=== modified file 'IPython/iplib.py'
--- IPython/iplib.py 2008-08-14 12:50:55 +0000
+++ IPython/iplib.py 2009-03-13 17:56:19 +0000
@@ -2,10 +2,9 @@
2"""2"""
3IPython -- An enhanced Interactive Python3IPython -- An enhanced Interactive Python
44
5Requires Python 2.3 or newer.5Requires Python 2.4 or newer.
66
7This file contains all the classes and helper functions specific to IPython.7This file contains all the classes and helper functions specific to IPython.
8
9"""8"""
109
11#*****************************************************************************10#*****************************************************************************
@@ -27,12 +26,6 @@
27#****************************************************************************26#****************************************************************************
28# Modules and globals27# Modules and globals
2928
30from IPython import Release
31__author__ = '%s <%s>\n%s <%s>' % \
32 ( Release.authors['Janko'] + Release.authors['Fernando'] )
33__license__ = Release.license
34__version__ = Release.version
35
36# Python standard modules29# Python standard modules
37import __main__30import __main__
38import __builtin__31import __builtin__
@@ -342,15 +335,19 @@
342 # code ran is deleted. Now that this object is a true module (needed335 # code ran is deleted. Now that this object is a true module (needed
343 # so docetst and other tools work correctly), the Python module336 # so docetst and other tools work correctly), the Python module
344 # teardown mechanism runs over it, and sets to None every variable337 # teardown mechanism runs over it, and sets to None every variable
345 # present in that module. This means that later calls to functions338 # present in that module. Top-level references to objects from the
346 # defined in the script (which have become interactively visible after339 # script survive, because the user_ns is updated with them. However,
347 # script exit) fail, because they hold references to objects that have340 # calling functions defined in the script that use other things from
348 # become overwritten into None. The only solution I see right now is341 # the script will fail, because the function's closure had references
349 # to protect every FakeModule used by %run by holding an internal342 # to the original objects, which are now all None. So we must protect
350 # reference to it. This private list will be used for that. The343 # these modules from deletion by keeping a cache. To avoid keeping
351 # %reset command will flush it as well.344 # stale modules around (we only need the one from the last run), we use
352 self._user_main_modules = []345 # a dict keyed with the full path to the script, so only the last
353346 # version of the module is held in the cache. The %reset command will
347 # flush this cache. See the cache_main_mod() and clear_main_mod_cache()
348 # methods for details on use.
349 self._user_main_modules = {}
350
354 # List of input with multi-line handling.351 # List of input with multi-line handling.
355 # Fill its zero entry, user counter starts at 1352 # Fill its zero entry, user counter starts at 1
356 self.input_hist = InputList(['\n'])353 self.input_hist = InputList(['\n'])
@@ -601,10 +598,6 @@
601 598
602 #TODO: remove this, redundant599 #TODO: remove this, redundant
603 self.add_builtins()600 self.add_builtins()
604
605
606
607
608 # end __init__601 # end __init__
609602
610 def var_expand(self,cmd,depth=0):603 def var_expand(self,cmd,depth=0):
@@ -633,16 +626,15 @@
633 """626 """
634 rc = self.rc627 rc = self.rc
635 try:628 try:
636 self.db = pickleshare.PickleShareDB(rc.ipythondir + "/db") 629 self.db = pickleshare.PickleShareDB(rc.ipythondir + "/db")
637 except exceptions.UnicodeDecodeError:630 except exceptions.UnicodeDecodeError:
638 print "Your ipythondir can't be decoded to unicode!"631 print "Your ipythondir can't be decoded to unicode!"
639 print "Please set HOME environment variable to something that"632 print "Please set HOME environment variable to something that"
640 print r"only has ASCII characters, e.g. c:\home"633 print r"only has ASCII characters, e.g. c:\home"
641 print "Now it is",rc.ipythondir634 print "Now it is",rc.ipythondir
642 sys.exit()635 sys.exit()
643 self.shadowhist = IPython.history.ShadowHist(self.db) 636 self.shadowhist = IPython.history.ShadowHist(self.db)
644 637
645
646 def post_config_initialization(self):638 def post_config_initialization(self):
647 """Post configuration init method639 """Post configuration init method
648640
@@ -909,7 +901,6 @@
909 call_pdb = property(_get_call_pdb,_set_call_pdb,None,901 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
910 'Control auto-activation of pdb at exceptions')902 'Control auto-activation of pdb at exceptions')
911 903
912
913 # These special functions get installed in the builtin namespace, to904 # These special functions get installed in the builtin namespace, to
914 # provide programmatic (pure python) access to magics, aliases and system905 # provide programmatic (pure python) access to magics, aliases and system
915 # calls. This is important for logging, user scripting, and more.906 # calls. This is important for logging, user scripting, and more.
@@ -1139,7 +1130,8 @@
1139 inif = 'ipythonrc.ini'1130 inif = 'ipythonrc.ini'
1140 else:1131 else:
1141 inif = 'ipythonrc'1132 inif = 'ipythonrc'
1142 minimal_setup = {'ipy_user_conf.py' : 'import ipy_defaults', inif : '# intentionally left blank' } 1133 minimal_setup = {'ipy_user_conf.py' : 'import ipy_defaults',
1134 inif : '# intentionally left blank' }
1143 os.makedirs(ipythondir, mode = 0777)1135 os.makedirs(ipythondir, mode = 0777)
1144 for f, cont in minimal_setup.items():1136 for f, cont in minimal_setup.items():
1145 open(ipythondir + '/' + f,'w').write(cont)1137 open(ipythondir + '/' + f,'w').write(cont)
@@ -1298,7 +1290,6 @@
1298 finally:1290 finally:
1299 readline.read_history_file(self.histfile)1291 readline.read_history_file(self.histfile)
1300 return wrapper1292 return wrapper
1301
1302 1293
1303 def pre_readline(self):1294 def pre_readline(self):
1304 """readline hook to be used at the start of each line.1295 """readline hook to be used at the start of each line.
@@ -1396,7 +1387,59 @@
1396 if self.rc.quiet:1387 if self.rc.quiet:
1397 return True1388 return True
1398 return ask_yes_no(prompt,default)1389 return ask_yes_no(prompt,default)
1399 1390
1391 def cache_main_mod(self,mod):
1392 """Cache a main module.
1393
1394 When scripts are executed via %run, we must keep a reference to their
1395 __main__ module (a FakeModule instance) around so that Python doesn't
1396 clear it, rendering objects defined therein useless.
1397
1398 This method keeps said reference in a private dict, keyed by the
1399 absolute path of the module object (which corresponds to the script
1400 path). This way, for multiple executions of the same script we only
1401 keep one copy of __main__ (the last one), thus preventing memory leaks
1402 from old references while allowing the objects from the last execution
1403 to be accessible.
1404
1405 Parameters
1406 ----------
1407 mod : a module object
1408
1409 Examples
1410 --------
1411
1412 In [10]: import IPython
1413
1414 In [11]: _ip.IP.cache_main_mod(IPython)
1415
1416 In [12]: IPython.__file__ in _ip.IP._user_main_modules
1417 Out[12]: True
1418 """
1419 self._user_main_modules[os.path.abspath(mod.__file__) ] = mod
1420
1421 def clear_main_mod_cache(self):
1422 """Clear the cache of main modules.
1423
1424 Mainly for use by utilities like %reset.
1425
1426 Examples
1427 --------
1428
1429 In [15]: import IPython
1430
1431 In [16]: _ip.IP.cache_main_mod(IPython)
1432
1433 In [17]: len(_ip.IP._user_main_modules) > 0
1434 Out[17]: True
1435
1436 In [18]: _ip.IP.clear_main_mod_cache()
1437
1438 In [19]: len(_ip.IP._user_main_modules) == 0
1439 Out[19]: True
1440 """
1441 self._user_main_modules.clear()
1442
1400 def _should_recompile(self,e):1443 def _should_recompile(self,e):
1401 """Utility routine for edit_syntax_error"""1444 """Utility routine for edit_syntax_error"""
14021445
@@ -1552,8 +1595,6 @@
1552 self.set_completer()1595 self.set_completer()
1553 except KeyboardInterrupt:1596 except KeyboardInterrupt:
1554 self.write("\nKeyboardInterrupt\n")1597 self.write("\nKeyboardInterrupt\n")
1555
1556
15571598
1558 def mainloop(self,banner=None):1599 def mainloop(self,banner=None):
1559 """Creates the local namespace and starts the mainloop.1600 """Creates the local namespace and starts the mainloop.
@@ -1576,7 +1617,9 @@
1576 try:1617 try:
1577 self.interact(banner)1618 self.interact(banner)
1578 #self.interact_with_readline() 1619 #self.interact_with_readline()
1579 # XXX for testing of a readline-decoupled repl loop, call interact_with_readline above1620
1621 # XXX for testing of a readline-decoupled repl loop, call
1622 # interact_with_readline above
15801623
1581 break1624 break
1582 except KeyboardInterrupt:1625 except KeyboardInterrupt:
15831626
=== modified file 'IPython/ipmaker.py'
--- IPython/ipmaker.py 2008-06-04 08:15:46 +0000
+++ IPython/ipmaker.py 2009-03-11 06:53:19 +0000
@@ -5,8 +5,7 @@
5Requires Python 2.1 or better.5Requires Python 2.1 or better.
66
7This file contains the main make_IPython() starter function.7This file contains the main make_IPython() starter function.
88"""
9$Id: ipmaker.py 2930 2008-01-11 07:03:11Z vivainio $"""
109
11#*****************************************************************************10#*****************************************************************************
12# Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>11# Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
1312
=== modified file 'IPython/ipstruct.py'
--- IPython/ipstruct.py 2008-08-02 09:07:37 +0000
+++ IPython/ipstruct.py 2009-03-11 06:53:19 +0000
@@ -1,7 +1,6 @@
1# -*- coding: utf-8 -*-1# -*- coding: utf-8 -*-
2"""Mimic C structs with lots of extra functionality.2"""Mimic C structs with lots of extra functionality.
33"""
4$Id: ipstruct.py 1950 2006-11-28 19:15:35Z vivainio $"""
54
6#*****************************************************************************5#*****************************************************************************
7# Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>6# Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
@@ -10,10 +9,6 @@
10# the file COPYING, distributed as part of this software.9# the file COPYING, distributed as part of this software.
11#*****************************************************************************10#*****************************************************************************
1211
13from IPython import Release
14__author__ = '%s <%s>' % Release.authors['Fernando']
15__license__ = Release.license
16
17__all__ = ['Struct']12__all__ = ['Struct']
1813
19import types14import types
@@ -163,8 +158,22 @@
163 return self.__dict__[key]158 return self.__dict__[key]
164159
165 def __contains__(self,key):160 def __contains__(self,key):
166 """Allows use of the 'in' operator."""161 """Allows use of the 'in' operator.
167 return self.__dict__.has_key(key)162
163 Examples:
164 >>> s = Struct(x=1)
165 >>> 'x' in s
166 True
167 >>> 'y' in s
168 False
169 >>> s[4] = None
170 >>> 4 in s
171 True
172 >>> s.z = None
173 >>> 'z' in s
174 True
175 """
176 return key in self.__dict__
168177
169 def __iadd__(self,other):178 def __iadd__(self,other):
170 """S += S2 is a shorthand for S.merge(S2)."""179 """S += S2 is a shorthand for S.merge(S2)."""
@@ -246,12 +255,13 @@
246 Optionally, one or more key=value pairs can be given at the end for255 Optionally, one or more key=value pairs can be given at the end for
247 direct update."""256 direct update."""
248257
249 # The funny name __loc_data__ is to prevent a common variable name which258 # The funny name __loc_data__ is to prevent a common variable name
250 # could be a fieled of a Struct to collide with this parameter. The problem259 # which could be a fieled of a Struct to collide with this
251 # would arise if the function is called with a keyword with this same name260 # parameter. The problem would arise if the function is called with a
252 # that a user means to add as a Struct field.261 # keyword with this same name that a user means to add as a Struct
262 # field.
253 newdict = Struct.__make_dict(self,__loc_data__,**kw)263 newdict = Struct.__make_dict(self,__loc_data__,**kw)
254 for k,v in newdict.items():264 for k,v in newdict.iteritems():
255 self[k] = v265 self[k] = v
256266
257 def merge(self,__loc_data__=None,__conflict_solve=None,**kw):267 def merge(self,__loc_data__=None,__conflict_solve=None,**kw):
258268
=== modified file 'IPython/kernel/core/ultraTB.py'
--- IPython/kernel/core/ultraTB.py 2008-06-06 19:41:55 +0000
+++ IPython/kernel/core/ultraTB.py 2009-03-11 06:53:19 +0000
@@ -1,5 +1,4 @@
1# encoding: utf-81# -*- coding: utf-8 -*-
2
3"""2"""
4ultraTB.py -- Spice up your tracebacks!3ultraTB.py -- Spice up your tracebacks!
54
@@ -60,26 +59,15 @@
60You can implement other color schemes easily, the syntax is fairly59You can implement other color schemes easily, the syntax is fairly
61self-explanatory. Please send back new schemes you develop to the author for60self-explanatory. Please send back new schemes you develop to the author for
62possible inclusion in future releases.61possible inclusion in future releases.
6362"""
64$Id: ultraTB.py 2480 2007-07-06 19:33:43Z fperez $"""63
6564#*****************************************************************************
66__docformat__ = "restructuredtext en"65# Copyright (C) 2001 Nathaniel Gray <n8gray@caltech.edu>
6766# Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
68#-------------------------------------------------------------------------------
69# Copyright (C) 2008 The IPython Development Team
70#67#
71# Distributed under the terms of the BSD License. The full license is in68# Distributed under the terms of the BSD License. The full license is in
72# the file COPYING, distributed as part of this software.69# the file COPYING, distributed as part of this software.
73#-------------------------------------------------------------------------------70#*****************************************************************************
74
75#-------------------------------------------------------------------------------
76# Imports
77#-------------------------------------------------------------------------------
78
79from IPython import Release
80__author__ = '%s <%s>\n%s <%s>' % (Release.authors['Nathan']+
81 Release.authors['Fernando'])
82__license__ = Release.license
8371
84# Required modules72# Required modules
85import inspect73import inspect
@@ -104,7 +92,7 @@
104# Modified pdb which doesn't damage IPython's readline handling92# Modified pdb which doesn't damage IPython's readline handling
105from IPython import Debugger, PyColorize93from IPython import Debugger, PyColorize
106from IPython.ipstruct import Struct94from IPython.ipstruct import Struct
107from IPython.excolors import ExceptionColors95from IPython.excolors import exception_colors
108from IPython.genutils import Term,uniq_stable,error,info96from IPython.genutils import Term,uniq_stable,error,info
10997
110# Globals98# Globals
@@ -141,11 +129,18 @@
141 FIXED version with which we monkeypatch the stdlib to work around a bug."""129 FIXED version with which we monkeypatch the stdlib to work around a bug."""
142130
143 file = getsourcefile(object) or getfile(object)131 file = getsourcefile(object) or getfile(object)
144 module = getmodule(object, file)132 # If the object is a frame, then trying to get the globals dict from its
145 if module:133 # module won't work. Instead, the frame object itself has the globals
146 lines = linecache.getlines(file, module.__dict__)134 # dictionary.
135 globals_dict = None
136 if inspect.isframe(object):
137 # XXX: can this ever be false?
138 globals_dict = object.f_globals
147 else:139 else:
148 lines = linecache.getlines(file)140 module = getmodule(object, file)
141 if module:
142 globals_dict = module.__dict__
143 lines = linecache.getlines(file, globals_dict)
149 if not lines:144 if not lines:
150 raise IOError('could not get source code')145 raise IOError('could not get source code')
151146
@@ -202,11 +197,31 @@
202if sys.version_info[:2] >= (2,5):197if sys.version_info[:2] >= (2,5):
203 inspect.findsource = findsource198 inspect.findsource = findsource
204199
200def fix_frame_records_filenames(records):
201 """Try to fix the filenames in each record from inspect.getinnerframes().
202
203 Particularly, modules loaded from within zip files have useless filenames
204 attached to their code object, and inspect.getinnerframes() just uses it.
205 """
206 fixed_records = []
207 for frame, filename, line_no, func_name, lines, index in records:
208 # Look inside the frame's globals dictionary for __file__, which should
209 # be better.
210 better_fn = frame.f_globals.get('__file__', None)
211 if isinstance(better_fn, str):
212 # Check the type just in case someone did something weird with
213 # __file__. It might also be None if the error occurred during
214 # import.
215 filename = better_fn
216 fixed_records.append((frame, filename, line_no, func_name, lines, index))
217 return fixed_records
218
219
205def _fixed_getinnerframes(etb, context=1,tb_offset=0):220def _fixed_getinnerframes(etb, context=1,tb_offset=0):
206 import linecache221 import linecache
207 LNUM_POS, LINES_POS, INDEX_POS = 2, 4, 5222 LNUM_POS, LINES_POS, INDEX_POS = 2, 4, 5
208223
209 records = inspect.getinnerframes(etb, context)224 records = fix_frame_records_filenames(inspect.getinnerframes(etb, context))
210225
211 # If the error is at the console, don't build any context, since it would226 # If the error is at the console, don't build any context, since it would
212 # otherwise produce 5 blank lines printed out (there is no file at the227 # otherwise produce 5 blank lines printed out (there is no file at the
@@ -299,7 +314,7 @@
299 self.call_pdb = call_pdb314 self.call_pdb = call_pdb
300315
301 # Create color table316 # Create color table
302 self.color_scheme_table = ExceptionColors 317 self.color_scheme_table = exception_colors()
303318
304 self.set_colors(color_scheme)319 self.set_colors(color_scheme)
305 self.old_scheme = color_scheme # save initial value for toggles320 self.old_scheme = color_scheme # save initial value for toggles
@@ -356,8 +371,8 @@
356 371
357 def __call__(self, etype, value, elist):372 def __call__(self, etype, value, elist):
358 Term.cout.flush()373 Term.cout.flush()
359 Term.cerr.flush()
360 print >> Term.cerr, self.text(etype,value,elist)374 print >> Term.cerr, self.text(etype,value,elist)
375 Term.cerr.flush()
361376
362 def text(self,etype, value, elist,context=5):377 def text(self,etype, value, elist,context=5):
363 """Return a color formatted string with the traceback info."""378 """Return a color formatted string with the traceback info."""
@@ -424,7 +439,8 @@
424 439
425 Also lifted nearly verbatim from traceback.py440 Also lifted nearly verbatim from traceback.py
426 """441 """
427 442
443 have_filedata = False
428 Colors = self.Colors444 Colors = self.Colors
429 list = []445 list = []
430 try:446 try:
@@ -438,8 +454,9 @@
438 try:454 try:
439 msg, (filename, lineno, offset, line) = value455 msg, (filename, lineno, offset, line) = value
440 except:456 except:
441 pass457 have_filedata = False
442 else:458 else:
459 have_filedata = True
443 #print 'filename is',filename # dbg460 #print 'filename is',filename # dbg
444 if not filename: filename = "<string>"461 if not filename: filename = "<string>"
445 list.append('%s File %s"%s"%s, line %s%d%s\n' % \462 list.append('%s File %s"%s"%s, line %s%d%s\n' % \
@@ -469,6 +486,12 @@
469 Colors.Normal, s))486 Colors.Normal, s))
470 else:487 else:
471 list.append('%s\n' % str(stype))488 list.append('%s\n' % str(stype))
489
490 # vds:>>
491 if have_filedata:
492 __IPYTHON__.hooks.synchronize_with_editor(filename, lineno, 0)
493 # vds:<<
494
472 return list495 return list
473496
474 def _some_str(self, value):497 def _some_str(self, value):
@@ -780,6 +803,15 @@
780 for name in names:803 for name in names:
781 value = text_repr(getattr(evalue, name))804 value = text_repr(getattr(evalue, name))
782 exception.append('\n%s%s = %s' % (indent, name, value))805 exception.append('\n%s%s = %s' % (indent, name, value))
806
807 # vds: >>
808 if records:
809 filepath, lnum = records[-1][1:3]
810 #print "file:", str(file), "linenb", str(lnum) # dbg
811 filepath = os.path.abspath(filepath)
812 __IPYTHON__.hooks.synchronize_with_editor(filepath, lnum, 0)
813 # vds: <<
814
783 # return all our info assembled as a single string815 # return all our info assembled as a single string
784 return '%s\n\n%s\n%s' % (head,'\n'.join(frames),''.join(exception[0]) )816 return '%s\n\n%s\n%s' % (head,'\n'.join(frames),''.join(exception[0]) )
785817
@@ -834,8 +866,8 @@
834 (etype, evalue, etb) = info or sys.exc_info()866 (etype, evalue, etb) = info or sys.exc_info()
835 self.tb = etb867 self.tb = etb
836 Term.cout.flush()868 Term.cout.flush()
837 Term.cerr.flush()
838 print >> Term.cerr, self.text(etype, evalue, etb)869 print >> Term.cerr, self.text(etype, evalue, etb)
870 Term.cerr.flush()
839871
840 # Changed so an instance can just be called as VerboseTB_inst() and print872 # Changed so an instance can just be called as VerboseTB_inst() and print
841 # out the right info on its own.873 # out the right info on its own.
@@ -845,7 +877,10 @@
845 self.handler()877 self.handler()
846 else:878 else:
847 self.handler((etype, evalue, etb))879 self.handler((etype, evalue, etb))
848 self.debugger()880 try:
881 self.debugger()
882 except KeyboardInterrupt:
883 print "\nKeyboardInterrupt"
849884
850#----------------------------------------------------------------------------885#----------------------------------------------------------------------------
851class FormattedTB(VerboseTB,ListTB):886class FormattedTB(VerboseTB,ListTB):
@@ -953,14 +988,17 @@
953 if out is None:988 if out is None:
954 out = Term.cerr989 out = Term.cerr
955 Term.cout.flush()990 Term.cout.flush()
956 out.flush()
957 if tb_offset is not None:991 if tb_offset is not None:
958 tb_offset, self.tb_offset = self.tb_offset, tb_offset992 tb_offset, self.tb_offset = self.tb_offset, tb_offset
959 print >> out, self.text(etype, evalue, etb)993 print >> out, self.text(etype, evalue, etb)
960 self.tb_offset = tb_offset994 self.tb_offset = tb_offset
961 else:995 else:
962 print >> out, self.text(etype, evalue, etb)996 print >> out, self.text(etype, evalue, etb)
963 self.debugger()997 out.flush()
998 try:
999 self.debugger()
1000 except KeyboardInterrupt:
1001 print "\nKeyboardInterrupt"
9641002
965 def text(self,etype=None,value=None,tb=None,context=5,mode=None):1003 def text(self,etype=None,value=None,tb=None,context=5,mode=None):
966 if etype is None:1004 if etype is None:
9671005
=== modified file 'IPython/kernel/core/util.py'
--- IPython/kernel/core/util.py 2008-06-06 19:41:55 +0000
+++ IPython/kernel/core/util.py 2009-03-11 01:24:53 +0000
@@ -70,8 +70,8 @@
70def make_quoted_expr(s):70def make_quoted_expr(s):
71 """Return string s in appropriate quotes, using raw string if possible.71 """Return string s in appropriate quotes, using raw string if possible.
72 72
73 Effectively this turns string: cd \ao\ao\73 XXX - example removed because it caused encoding errors in documentation
74 to: r"cd \ao\ao\_"[:-1]74 generation. We need a new example that doesn't contain invalid chars.
75 75
76 Note the use of raw string and padding at the end to allow trailing76 Note the use of raw string and padding at the end to allow trailing
77 backslash.77 backslash.
7878
=== modified file 'IPython/kernel/scripts/ipcluster' (properties changed: -x to +x)
=== modified file 'IPython/kernel/scripts/ipcluster.py' (properties changed: -x to +x)
=== modified file 'IPython/kernel/scripts/ipcontroller' (properties changed: -x to +x)
=== modified file 'IPython/kernel/scripts/ipcontroller.py' (properties changed: -x to +x)
=== modified file 'IPython/kernel/scripts/ipengine' (properties changed: -x to +x)
=== modified file 'IPython/kernel/scripts/ipengine.py' (properties changed: -x to +x)
=== modified file 'IPython/macro.py'
--- IPython/macro.py 2008-02-16 09:50:47 +0000
+++ IPython/macro.py 2009-03-11 06:53:19 +0000
@@ -9,7 +9,6 @@
99
10import IPython.ipapi 10import IPython.ipapi
1111
12
13from IPython.genutils import Term12from IPython.genutils import Term
14from IPython.ipapi import IPyAutocall13from IPython.ipapi import IPyAutocall
1514
@@ -41,4 +40,4 @@
41 40
42 def __getstate__(self):41 def __getstate__(self):
43 """ needed for safe pickling via %store """42 """ needed for safe pickling via %store """
44 return {'value': self.value}
45\ No newline at end of file43\ No newline at end of file
44 return {'value': self.value}
4645
=== modified file 'IPython/numutils.py'
--- IPython/numutils.py 2008-02-28 18:21:11 +0000
+++ IPython/numutils.py 2009-03-11 06:53:19 +0000
@@ -4,8 +4,7 @@
44
5Most of this module requires Numerical Python or is meant to be used with it.5Most of this module requires Numerical Python or is meant to be used with it.
6See http://www.pfdubois.com/numpy for details.6See http://www.pfdubois.com/numpy for details.
77"""
8$Id: numutils.py 958 2005-12-27 23:17:51Z fperez $"""
98
10#*****************************************************************************9#*****************************************************************************
11# Copyright (C) 2001-2005 Fernando Perez <fperez@colorado.edu>10# Copyright (C) 2001-2005 Fernando Perez <fperez@colorado.edu>
@@ -14,10 +13,6 @@
14# the file COPYING, distributed as part of this software.13# the file COPYING, distributed as part of this software.
15#*****************************************************************************14#*****************************************************************************
1615
17from IPython import Release
18__author__ = '%s <%s>' % Release.authors['Fernando']
19__license__ = Release.license
20
21__all__ = ['sum_flat','mean_flat','rms_flat','base_repr','binary_repr',16__all__ = ['sum_flat','mean_flat','rms_flat','base_repr','binary_repr',
22 'amin','amax','amap','zeros_like','empty_like',17 'amin','amax','amap','zeros_like','empty_like',
23 'frange','diagonal_matrix','identity',18 'frange','diagonal_matrix','identity',
2419
=== modified file 'IPython/platutils.py'
--- IPython/platutils.py 2008-07-06 16:54:20 +0000
+++ IPython/platutils.py 2009-03-11 06:27:38 +0000
@@ -12,10 +12,6 @@
12# the file COPYING, distributed as part of this software.12# the file COPYING, distributed as part of this software.
13#*****************************************************************************13#*****************************************************************************
1414
15from IPython import Release
16__author__ = '%s <%s>' % Release.authors['Ville']
17__license__ = Release.license
18
19import os15import os
20import sys16import sys
2117
@@ -35,8 +31,26 @@
35# Functionality that's logically common to all platforms goes here, each31# Functionality that's logically common to all platforms goes here, each
36# platform-specific module only provides the bits that are OS-dependent.32# platform-specific module only provides the bits that are OS-dependent.
3733
38def freeze_term_title():34# XXX - I'm still not happy with a module global for this, but at least now
39 _platutils.ignore_termtitle = True35# there is a public, cross-platform way of toggling the term title control on
36# and off. We should make this a stateful object later on so that each user
37# can have its own instance if needed.
38def toggle_set_term_title(val):
39 """Control whether set_term_title is active or not.
40
41 set_term_title() allows writing to the console titlebar. In embedded
42 widgets this can cause problems, so this call can be used to toggle it on
43 or off as needed.
44
45 The default state of the module is for the function to be disabled.
46
47 Parameters
48 ----------
49 val : bool
50 If True, set_term_title() actually writes to the terminal (using the
51 appropriate platform-specific module). If False, it is a no-op.
52 """
53 _platutils.ignore_termtitle = not(val)
4054
4155
42def set_term_title(title):56def set_term_title(title):
@@ -45,3 +59,12 @@
45 if _platutils.ignore_termtitle:59 if _platutils.ignore_termtitle:
46 return60 return
47 _platutils.set_term_title(title)61 _platutils.set_term_title(title)
62
63
64#-----------------------------------------------------------------------------
65# Deprecated functions
66#-----------------------------------------------------------------------------
67def freeze_term_title():
68 warnings.warn("This function is deprecated, use toggle_set_term_title()")
69 _platutils.ignore_termtitle = True
70
4871
=== modified file 'IPython/platutils_posix.py'
--- IPython/platutils_posix.py 2008-07-06 16:54:20 +0000
+++ IPython/platutils_posix.py 2009-03-11 06:27:38 +0000
@@ -12,14 +12,10 @@
12# the file COPYING, distributed as part of this software.12# the file COPYING, distributed as part of this software.
13#*****************************************************************************13#*****************************************************************************
1414
15from IPython import Release
16__author__ = '%s <%s>' % Release.authors['Ville']
17__license__ = Release.license
18
19import sys15import sys
20import os16import os
2117
22ignore_termtitle = False18ignore_termtitle = True
2319
24def _dummy_op(*a, **b):20def _dummy_op(*a, **b):
25 """ A no-op function """21 """ A no-op function """
@@ -27,7 +23,7 @@
27def _set_term_title_xterm(title):23def _set_term_title_xterm(title):
28 """ Change virtual terminal title in xterm-workalikes """24 """ Change virtual terminal title in xterm-workalikes """
2925
30 sys.stdout.write('\033]%d;%s\007' % (0,title))26 sys.stdout.write('\033]0;%s\007' % title)
3127
3228
33if os.environ.get('TERM','') == 'xterm':29if os.environ.get('TERM','') == 'xterm':
3430
=== modified file 'IPython/platutils_win32.py'
--- IPython/platutils_win32.py 2008-07-06 16:54:20 +0000
+++ IPython/platutils_win32.py 2009-03-11 06:53:19 +0000
@@ -12,13 +12,9 @@
12# the file COPYING, distributed as part of this software.12# the file COPYING, distributed as part of this software.
13#*****************************************************************************13#*****************************************************************************
1414
15from IPython import Release
16__author__ = '%s <%s>' % Release.authors['Ville']
17__license__ = Release.license
18
19import os15import os
2016
21ignore_termtitle = False17ignore_termtitle = True
2218
23try:19try:
24 import ctypes20 import ctypes
2521
=== modified file 'IPython/rlineimpl.py'
--- IPython/rlineimpl.py 2008-02-16 09:50:47 +0000
+++ IPython/rlineimpl.py 2009-03-11 06:53:19 +0000
@@ -5,8 +5,7 @@
55
6In addition to normal readline stuff, this module provides have_readline6In addition to normal readline stuff, this module provides have_readline
7boolean and _outputfile variable used in genutils.7boolean and _outputfile variable used in genutils.
88"""
9$Id: Magic.py 1096 2006-01-28 20:08:02Z vivainio $"""
109
11import sys10import sys
1211
@@ -53,4 +52,4 @@
53 _rl.clear_history52 _rl.clear_history
54 except AttributeError:53 except AttributeError:
55 def clear_history(): pass54 def clear_history(): pass
56 _rl.clear_history = clear_history
57\ No newline at end of file55\ No newline at end of file
56 _rl.clear_history = clear_history
5857
=== modified file 'IPython/shellglobals.py'
--- IPython/shellglobals.py 2008-03-22 15:03:36 +0000
+++ IPython/shellglobals.py 2009-03-11 06:53:19 +0000
@@ -1,6 +1,13 @@
1from IPython.genutils import Term,warn,error,flag_calls, ask_yes_no1"""Some globals used by the main Shell classes.
22"""
3import thread,inspect3
4#-----------------------------------------------------------------------------
5# Module imports
6#-----------------------------------------------------------------------------
7
8# stdlib
9import inspect
10import thread
411
5try:12try:
6 import ctypes13 import ctypes
@@ -8,8 +15,12 @@
8except ImportError:15except ImportError:
9 HAS_CTYPES = False16 HAS_CTYPES = False
1017
18# our own
19from IPython.genutils import Term,warn,error,flag_calls, ask_yes_no
1120
21#-----------------------------------------------------------------------------
12# Globals22# Globals
23#-----------------------------------------------------------------------------
13# global flag to pass around information about Ctrl-C without exceptions24# global flag to pass around information about Ctrl-C without exceptions
14KBINT = False25KBINT = False
1526
@@ -22,13 +33,11 @@
22# Tag when runcode() is active, for exception handling33# Tag when runcode() is active, for exception handling
23CODE_RUN = None34CODE_RUN = None
2435
25
26#-----------------------------------------------------------------------------36#-----------------------------------------------------------------------------
27# This class is trivial now, but I want to have it in to publish a clean37# This class is trivial now, but I want to have it in to publish a clean
28# interface. Later when the internals are reorganized, code that uses this38# interface. Later when the internals are reorganized, code that uses this
29# shouldn't have to change.39# shouldn't have to change.
3040
31
32if HAS_CTYPES:41if HAS_CTYPES:
33 # Add async exception support. Trick taken from:42 # Add async exception support. Trick taken from:
34 # http://sebulba.wikispaces.com/recipe+thread243 # http://sebulba.wikispaces.com/recipe+thread2
@@ -81,16 +90,12 @@
81 # Set global flag so that runsource can know that Ctrl-C was hit90 # Set global flag so that runsource can know that Ctrl-C was hit
82 KBINT = True91 KBINT = True
8392
93
84def run_in_frontend(src):94def run_in_frontend(src):
85 """ Check if source snippet can be run in the REPL thread, as opposed to GUI mainloop95 """ Check if source snippet can be run in the REPL thread, as opposed to
86 96 GUI mainloop (to prevent unnecessary hanging of mainloop).
87 (to prevent unnecessary hanging of mainloop).
88
89 """97 """
90 98
91 if src.startswith('_ip.system(') and not '\n' in src:99 if src.startswith('_ip.system(') and not '\n' in src:
92 return True100 return True
93 return False101 return False
94
95
96
97102
=== modified file 'IPython/strdispatch.py'
--- IPython/strdispatch.py 2008-07-30 20:08:19 +0000
+++ IPython/strdispatch.py 2009-03-11 06:53:19 +0000
@@ -8,7 +8,6 @@
8from IPython.hooks import CommandChainDispatcher8from IPython.hooks import CommandChainDispatcher
9import IPython.hooks9import IPython.hooks
1010
11
12# Code begins11# Code begins
13class StrDispatch(object):12class StrDispatch(object):
14 """Dispatch (lookup) a set of strings / regexps for match.13 """Dispatch (lookup) a set of strings / regexps for match.
1514
=== modified file 'IPython/testing/decorators.py'
--- IPython/testing/decorators.py 2008-09-15 02:07:52 +0000
+++ IPython/testing/decorators.py 2009-03-11 01:24:53 +0000
@@ -1,12 +1,10 @@
1"""Decorators for labeling test objects.1"""Decorators for labeling test objects.
22
3Decorators that merely return a modified version of the original3Decorators that merely return a modified version of the original function
4function object are straightforward. Decorators that return a new4object are straightforward. Decorators that return a new function object need
5function object need to use5to use nose.tools.make_decorator(original_function)(decorator) in returning the
6nose.tools.make_decorator(original_function)(decorator) in returning6decorator, in order to preserve metadata such as function name, setup and
7the decorator, in order to preserve metadata such as function name,7teardown functions and so on - see nose.tools for more information.
8setup and teardown functions and so on - see nose.tools for more
9information.
108
11This module provides a set of useful decorators meant to be ready to use in9This module provides a set of useful decorators meant to be ready to use in
12your own tests. See the bottom of the file for the ready-made ones, and if you10your own tests. See the bottom of the file for the ready-made ones, and if you
@@ -115,6 +113,115 @@
115 113
116 return decor114 return decor
117115
116
117# Inspired by numpy's skipif, but uses the full apply_wrapper utility to
118# preserve function metadata better and allows the skip condition to be a
119# callable.
120def skipif(skip_condition, msg=None):
121 ''' Make function raise SkipTest exception if skip_condition is true
122
123 Parameters
124 ----------
125 skip_condition : bool or callable.
126 Flag to determine whether to skip test. If the condition is a
127 callable, it is used at runtime to dynamically make the decision. This
128 is useful for tests that may require costly imports, to delay the cost
129 until the test suite is actually executed.
130 msg : string
131 Message to give on raising a SkipTest exception
132
133 Returns
134 -------
135 decorator : function
136 Decorator, which, when applied to a function, causes SkipTest
137 to be raised when the skip_condition was True, and the function
138 to be called normally otherwise.
139
140 Notes
141 -----
142 You will see from the code that we had to further decorate the
143 decorator with the nose.tools.make_decorator function in order to
144 transmit function name, and various other metadata.
145 '''
146
147 def skip_decorator(f):
148 # Local import to avoid a hard nose dependency and only incur the
149 # import time overhead at actual test-time.
150 import nose
151
152 # Allow for both boolean or callable skip conditions.
153 if callable(skip_condition):
154 skip_val = lambda : skip_condition()
155 else:
156 skip_val = lambda : skip_condition
157
158 def get_msg(func,msg=None):
159 """Skip message with information about function being skipped."""
160 if msg is None: out = 'Test skipped due to test condition.'
161 else: out = msg
162 return "Skipping test: %s. %s" % (func.__name__,out)
163
164 # We need to define *two* skippers because Python doesn't allow both
165 # return with value and yield inside the same function.
166 def skipper_func(*args, **kwargs):
167 """Skipper for normal test functions."""
168 if skip_val():
169 raise nose.SkipTest(get_msg(f,msg))
170 else:
171 return f(*args, **kwargs)
172
173 def skipper_gen(*args, **kwargs):
174 """Skipper for test generators."""
175 if skip_val():
176 raise nose.SkipTest(get_msg(f,msg))
177 else:
178 for x in f(*args, **kwargs):
179 yield x
180
181 # Choose the right skipper to use when building the actual generator.
182 if nose.util.isgenerator(f):
183 skipper = skipper_gen
184 else:
185 skipper = skipper_func
186
187 return nose.tools.make_decorator(f)(skipper)
188
189 return skip_decorator
190
191# A version with the condition set to true, common case just to attacha message
192# to a skip decorator
193def skip(msg=None):
194 """Decorator factory - mark a test function for skipping from test suite.
195
196 :Parameters:
197 msg : string
198 Optional message to be added.
199
200 :Returns:
201 decorator : function
202 Decorator, which, when applied to a function, causes SkipTest
203 to be raised, with the optional message added.
204 """
205
206 return skipif(True,msg)
207
208
209#-----------------------------------------------------------------------------
210# Utility functions for decorators
211def numpy_not_available():
212 """Can numpy be imported? Returns true if numpy does NOT import.
213
214 This is used to make a decorator to skip tests that require numpy to be
215 available, but delay the 'import numpy' to test execution time.
216 """
217 try:
218 import numpy
219 np_not_avail = False
220 except ImportError:
221 np_not_avail = True
222
223 return np_not_avail
224
118#-----------------------------------------------------------------------------225#-----------------------------------------------------------------------------
119# Decorators for public use226# Decorators for public use
120227
@@ -125,36 +232,13 @@
125 omit from testing, while preserving the docstring for introspection, help,232 omit from testing, while preserving the docstring for introspection, help,
126 etc.""") 233 etc.""")
127234
128def skip(msg=''):
129 """Decorator - mark a test function for skipping from test suite.
130
131 This function *is* already a decorator, it is not a factory like
132 make_label_dec or some of those in decorators_numpy.
133
134 :Parameters:
135
136 func : function
137 Test function to be skipped
138
139 msg : string
140 Optional message to be added.
141 """
142
143 import nose
144
145 def inner(func):
146
147 def wrapper(*a,**k):
148 if msg: out = '\n'+msg
149 else: out = ''
150 raise nose.SkipTest("Skipping test for function: %s%s" %
151 (func.__name__,out))
152
153 return apply_wrapper(wrapper,func)
154
155 return inner
156
157# Decorators to skip certain tests on specific platforms.235# Decorators to skip certain tests on specific platforms.
158skip_win32 = skipif(sys.platform=='win32',"This test does not run under Windows")236skip_win32 = skipif(sys.platform=='win32',
237 "This test does not run under Windows")
159skip_linux = skipif(sys.platform=='linux2',"This test does not run under Linux")238skip_linux = skipif(sys.platform=='linux2',"This test does not run under Linux")
160skip_osx = skipif(sys.platform=='darwin',"This test does not run under OSX")239skip_osx = skipif(sys.platform=='darwin',"This test does not run under OS X")
240
241
242skipif_not_numpy = skipif(numpy_not_available,"This test requires numpy")
243
244skipknownfailure = skip('This test is known to fail')
161245
=== modified file 'IPython/testing/decorators_numpy.py'
--- IPython/testing/decorators_numpy.py 2008-08-02 09:07:37 +0000
+++ IPython/testing/decorators_numpy.py 2009-03-11 01:24:53 +0000
@@ -46,13 +46,16 @@
46 return t46 return t
47 return set_test47 return set_test
4848
49def skipif(skip_condition, msg=None):49def skipif(skip_condition=True, msg=None):
50 ''' Make function raise SkipTest exception if skip_condition is true50 ''' Make function raise SkipTest exception if skip_condition is true
5151
52 Parameters52 Parameters
53 ---------53 ----------
54 skip_condition : bool54 skip_condition : bool or callable.
55 Flag to determine whether to skip test (True) or not (False)55 Flag to determine whether to skip test. If the condition is a
56 callable, it is used at runtime to dynamically make the decision. This
57 is useful for tests that may require costly imports, to delay the cost
58 until the test suite is actually executed.
56 msg : string59 msg : string
57 Message to give on raising a SkipTest exception60 Message to give on raising a SkipTest exception
5861
5962
=== modified file 'IPython/testing/iptest.py'
--- IPython/testing/iptest.py 2008-08-24 06:37:40 +0000
+++ IPython/testing/iptest.py 2009-03-11 05:49:08 +0000
@@ -1,16 +1,53 @@
1#!/usr/bin/env python
2# -*- coding: utf-8 -*-1# -*- coding: utf-8 -*-
3"""IPython Test Suite Runner.2"""IPython Test Suite Runner.
3
4This module provides a main entry point to a user script to test IPython itself
5from the command line. The main() routine can be used in a similar manner to
6the ``nosetests`` script, and it takes similar arguments, but if no arguments
7are given it defaults to testing all of IPython. This should be preferred to
8using plain ``nosetests`` because a number of nose plugins necessary to test
9IPython correctly are automatically configured by this code.
4"""10"""
511
12#-----------------------------------------------------------------------------
13# Module imports
14#-----------------------------------------------------------------------------
15
16# stdlib
6import sys17import sys
7import warnings18import warnings
819
20# third-party
21import nose.plugins.builtin
9from nose.core import TestProgram22from nose.core import TestProgram
10import nose.plugins.builtin
1123
24# Our own imports
12from IPython.testing.plugin.ipdoctest import IPythonDoctest25from IPython.testing.plugin.ipdoctest import IPythonDoctest
1326
27#-----------------------------------------------------------------------------
28# Constants and globals
29#-----------------------------------------------------------------------------
30
31# For the IPythonDoctest plugin, we need to exclude certain patterns that cause
32# testing problems. We should strive to minimize the number of skipped
33# modules, since this means untested code. As the testing machinery
34# solidifies, this list should eventually become empty.
35EXCLUDE = ['IPython/external/',
36 'IPython/platutils_win32',
37 'IPython/frontend/cocoa',
38 'IPython_doctest_plugin',
39 'IPython/Gnuplot',
40 'IPython/Extensions/ipy_',
41 'IPython/Extensions/clearcmd',
42 'IPython/Extensions/PhysicalQIn',
43 'IPython/Extensions/scitedirector',
44 'IPython/testing/plugin',
45 ]
46
47#-----------------------------------------------------------------------------
48# Functions and classes
49#-----------------------------------------------------------------------------
50
14def main():51def main():
15 """Run the IPython test suite.52 """Run the IPython test suite.
16 """53 """
@@ -18,36 +55,39 @@
18 warnings.filterwarnings('ignore', 55 warnings.filterwarnings('ignore',
19 'This will be removed soon. Use IPython.testing.util instead')56 'This will be removed soon. Use IPython.testing.util instead')
2057
21 58 argv = sys.argv + [ '--with-ipdoctest',
22 # construct list of plugins, omitting the existing doctest plugin59 '--doctest-tests','--doctest-extension=txt',
23 plugins = [IPythonDoctest()]60 '--detailed-errors',
61
62 # We add --exe because of setuptools' imbecility (it
63 # blindly does chmod +x on ALL files). Nose does the
64 # right thing and it tries to avoid executables,
65 # setuptools unfortunately forces our hand here. This
66 # has been discussed on the distutils list and the
67 # setuptools devs refuse to fix this problem!
68 '--exe',
69 ]
70
71 # Detect if any tests were required by explicitly calling an IPython
72 # submodule or giving a specific path
73 has_tests = False
74 for arg in sys.argv:
75 if 'IPython' in arg or arg.endswith('.py') or \
76 (':' in arg and '.py' in arg):
77 has_tests = True
78 break
79 # If nothing was specifically requested, test full IPython
80 if not has_tests:
81 argv.append('IPython')
82
83 # Construct list of plugins, omitting the existing doctest plugin.
84 plugins = [IPythonDoctest(EXCLUDE)]
24 for p in nose.plugins.builtin.plugins:85 for p in nose.plugins.builtin.plugins:
25 plug = p()86 plug = p()
26 if plug.name == 'doctest':87 if plug.name == 'doctest':
27 continue88 continue
2889
29 #print 'adding plugin:',plug.name # dbg90 #print '*** adding plugin:',plug.name # dbg
30 plugins.append(plug)91 plugins.append(plug)
3192
32 argv = sys.argv + ['--doctest-tests','--doctest-extension=txt',
33 '--detailed-errors',
34
35 # We add --exe because of setuptools' imbecility (it
36 # blindly does chmod +x on ALL files). Nose does the
37 # right thing and it tries to avoid executables,
38 # setuptools unfortunately forces our hand here. This
39 # has been discussed on the distutils list and the
40 # setuptools devs refuse to fix this problem!
41 '--exe',
42 ]
43
44 has_ip = False
45 for arg in sys.argv:
46 if 'IPython' in arg:
47 has_ip = True
48 break
49
50 if not has_ip:
51 argv.append('IPython')
52
53 TestProgram(argv=argv,plugins=plugins)93 TestProgram(argv=argv,plugins=plugins)
5494
=== modified file 'IPython/testing/plugin/Makefile'
--- IPython/testing/plugin/Makefile 2008-09-03 15:54:03 +0000
+++ IPython/testing/plugin/Makefile 2008-11-09 05:54:34 +0000
@@ -36,8 +36,8 @@
36magic: plugin36magic: plugin
37 $(NOSE) IPython.Magic37 $(NOSE) IPython.Magic
3838
39ipipe: plugin39excolors: plugin
40 $(NOSE) IPython.Extensions.ipipe40 $(NOSE) IPython.excolors
4141
42iplib: plugin42iplib: plugin
43 $(NOSE) IPython.iplib43 $(NOSE) IPython.iplib
4444
=== modified file 'IPython/testing/plugin/ipdoctest.py'
--- IPython/testing/plugin/ipdoctest.py 2008-08-24 06:10:55 +0000
+++ IPython/testing/plugin/ipdoctest.py 2009-03-11 05:49:08 +0000
@@ -65,13 +65,28 @@
65# test globals. Once we move over to a clean magic system, this will be done65# test globals. Once we move over to a clean magic system, this will be done
66# with much less ugliness.66# with much less ugliness.
6767
68class py_file_finder(object):
69 def __init__(self,test_filename):
70 self.test_filename = test_filename
71
72 def __call__(self,name):
73 from IPython.genutils import get_py_filename
74 try:
75 get_py_filename(name)
76 except IOError:
77 test_dir = os.path.dirname(self.test_filename)
78 new_path = os.path.join(test_dir,name)
79 return get_py_filename(new_path)
80
81
68def _run_ns_sync(self,arg_s,runner=None):82def _run_ns_sync(self,arg_s,runner=None):
69 """Modified version of %run that syncs testing namespaces.83 """Modified version of %run that syncs testing namespaces.
7084
71 This is strictly needed for running doctests that call %run.85 This is strictly needed for running doctests that call %run.
72 """86 """
7387
74 out = _ip.IP.magic_run_ori(arg_s,runner)88 finder = py_file_finder(_run_ns_sync.test_filename)
89 out = _ip.IP.magic_run_ori(arg_s,runner,finder)
75 _run_ns_sync.test_globs.update(_ip.user_ns)90 _run_ns_sync.test_globs.update(_ip.user_ns)
76 return out91 return out
7792
@@ -129,8 +144,7 @@
129144
130 # Start IPython instance. We customize it to start with minimal frills.145 # Start IPython instance. We customize it to start with minimal frills.
131 user_ns,global_ns = IPython.ipapi.make_user_namespaces(ipnsdict(),dict())146 user_ns,global_ns = IPython.ipapi.make_user_namespaces(ipnsdict(),dict())
132 147 IPython.Shell.IPShell(['--colors=NoColor','--noterm_title'],
133 IPython.Shell.IPShell(['--classic','--noterm_title'],
134 user_ns,global_ns)148 user_ns,global_ns)
135149
136 # Deactivate the various python system hooks added by ipython for150 # Deactivate the various python system hooks added by ipython for
@@ -172,13 +186,19 @@
172 return os.path.splitext(filename)[1].lower() in ('.so','.pyd')186 return os.path.splitext(filename)[1].lower() in ('.so','.pyd')
173187
174188
175class nodoc(object):189class DocTestSkip(object):
190 """Object wrapper for doctests to be skipped."""
191
192 ds_skip = """Doctest to skip.
193 >>> 1 #doctest: +SKIP
194 """
195
176 def __init__(self,obj):196 def __init__(self,obj):
177 self.obj = obj197 self.obj = obj
178198
179 def __getattribute__(self,key):199 def __getattribute__(self,key):
180 if key == '__doc__':200 if key == '__doc__':
181 return None201 return DocTestSkip.ds_skip
182 else:202 else:
183 return getattr(object.__getattribute__(self,'obj'),key)203 return getattr(object.__getattribute__(self,'obj'),key)
184204
@@ -222,7 +242,7 @@
222242
223 if hasattr(obj,"skip_doctest"):243 if hasattr(obj,"skip_doctest"):
224 #print 'SKIPPING DOCTEST FOR:',obj # dbg244 #print 'SKIPPING DOCTEST FOR:',obj # dbg
225 obj = nodoc(obj)245 obj = DocTestSkip(obj)
226246
227 doctest.DocTestFinder._find(self,tests, obj, name, module,247 doctest.DocTestFinder._find(self,tests, obj, name, module,
228 source_lines, globs, seen)248 source_lines, globs, seen)
@@ -638,7 +658,8 @@
638 # when called (rather than unconconditionally updating test.globs here658 # when called (rather than unconconditionally updating test.globs here
639 # for all examples, most of which won't be calling %run anyway).659 # for all examples, most of which won't be calling %run anyway).
640 _run_ns_sync.test_globs = test.globs660 _run_ns_sync.test_globs = test.globs
641661 _run_ns_sync.test_filename = test.filename
662
642 return super(IPDocTestRunner,self).run(test,663 return super(IPDocTestRunner,self).run(test,
643 compileflags,out,clear_globs)664 compileflags,out,clear_globs)
644665
@@ -656,6 +677,22 @@
656 name = 'extdoctest' # call nosetests with --with-extdoctest677 name = 'extdoctest' # call nosetests with --with-extdoctest
657 enabled = True678 enabled = True
658679
680 def __init__(self,exclude_patterns=None):
681 """Create a new ExtensionDoctest plugin.
682
683 Parameters
684 ----------
685
686 exclude_patterns : sequence of strings, optional
687 These patterns are compiled as regular expressions, subsequently used
688 to exclude any filename which matches them from inclusion in the test
689 suite (using pattern.search(), NOT pattern.match() ).
690 """
691 if exclude_patterns is None:
692 exclude_patterns = []
693 self.exclude_patterns = map(re.compile,exclude_patterns)
694 doctests.Doctest.__init__(self)
695
659 def options(self, parser, env=os.environ):696 def options(self, parser, env=os.environ):
660 Plugin.options(self, parser, env)697 Plugin.options(self, parser, env)
661 parser.add_option('--doctest-tests', action='store_true',698 parser.add_option('--doctest-tests', action='store_true',
@@ -688,6 +725,7 @@
688 self.globs = None725 self.globs = None
689 self.extraglobs = None726 self.extraglobs = None
690727
728
691 def loadTestsFromExtensionModule(self,filename):729 def loadTestsFromExtensionModule(self,filename):
692 bpath,mod = os.path.split(filename)730 bpath,mod = os.path.split(filename)
693 modname = os.path.splitext(mod)[0]731 modname = os.path.splitext(mod)[0]
@@ -703,8 +741,8 @@
703 # a few modifications to control output checking.741 # a few modifications to control output checking.
704742
705 def loadTestsFromModule(self, module):743 def loadTestsFromModule(self, module):
706 #print 'lTM',module # dbg744 #print '*** ipdoctest - lTM',module # dbg
707745
708 if not self.matches(module.__name__):746 if not self.matches(module.__name__):
709 log.debug("Doctest doesn't want module %s", module)747 log.debug("Doctest doesn't want module %s", module)
710 return748 return
@@ -733,8 +771,6 @@
733771
734772
735 def loadTestsFromFile(self, filename):773 def loadTestsFromFile(self, filename):
736 #print 'lTF',filename # dbg
737
738 if is_extension_module(filename):774 if is_extension_module(filename):
739 for t in self.loadTestsFromExtensionModule(filename):775 for t in self.loadTestsFromExtensionModule(filename):
740 yield t776 yield t
@@ -761,22 +797,10 @@
761 Modified version that accepts extension modules as valid containers for797 Modified version that accepts extension modules as valid containers for
762 doctests.798 doctests.
763 """799 """
764 print 'Filename:',filename # dbg800 #print '*** ipdoctest- wantFile:',filename # dbg
765801
766 # XXX - temporarily hardcoded list, will move to driver later802 for pat in self.exclude_patterns:
767 exclude = ['IPython/external/',803 if pat.search(filename):
768 'IPython/platutils_win32',
769 'IPython/frontend/cocoa',
770 'IPython_doctest_plugin',
771 'IPython/Gnuplot',
772 'IPython/Extensions/ipy_',
773 'IPython/Extensions/PhysicalQIn',
774 'IPython/Extensions/scitedirector',
775 'IPython/testing/plugin',
776 ]
777
778 for fex in exclude:
779 if fex in filename: # substring
780 #print '###>>> SKIP:',filename # dbg804 #print '###>>> SKIP:',filename # dbg
781 return False805 return False
782806
@@ -791,6 +815,23 @@
791 """815 """
792 name = 'ipdoctest' # call nosetests with --with-ipdoctest816 name = 'ipdoctest' # call nosetests with --with-ipdoctest
793 enabled = True817 enabled = True
818
819 def makeTest(self, obj, parent):
820 """Look for doctests in the given object, which will be a
821 function, method or class.
822 """
823 # always use whitespace and ellipsis options
824 optionflags = doctest.NORMALIZE_WHITESPACE | doctest.ELLIPSIS
825
826 doctests = self.finder.find(obj, module=getmodule(parent))
827 if doctests:
828 for test in doctests:
829 if len(test.examples) == 0:
830 continue
831
832 yield DocTestCase(test, obj=obj,
833 optionflags=optionflags,
834 checker=self.checker)
794835
795 def configure(self, options, config):836 def configure(self, options, config):
796837
797838
=== added file 'IPython/tests/tclass.py'
--- IPython/tests/tclass.py 1970-01-01 00:00:00 +0000
+++ IPython/tests/tclass.py 2009-03-13 17:56:19 +0000
@@ -0,0 +1,26 @@
1"""Simple script to instantiate a class for testing %run"""
2
3import sys
4
5# An external test will check that calls to f() work after %run
6class foo: pass
7
8def f():
9 return foo()
10
11# We also want to ensure that while objects remain available for immediate
12# access, objects from *previous* runs of the same script get collected, to
13# avoid accumulating massive amounts of old references.
14class C(object):
15 def __init__(self,name):
16 self.name = name
17
18 def __del__(self):
19 print 'Deleting object:',self.name
20
21try:
22 name = sys.argv[1]
23except IndexError:
24 pass
25else:
26 c = C(name)
027
=== modified file 'IPython/tests/test_magic.py'
--- IPython/tests/test_magic.py 2008-09-17 19:01:11 +0000
+++ IPython/tests/test_magic.py 2009-03-13 17:56:19 +0000
@@ -1,8 +1,21 @@
1""" Tests for various magic functions1"""Tests for various magic functions.
22
3Needs to be run by nose (to make ipython session available)3Needs to be run by nose (to make ipython session available).
4
5"""4"""
5
6# Standard library imports
7import os
8import sys
9
10# Third-party imports
11import nose.tools as nt
12
13# From our own code
14from IPython.testing import decorators as dec
15
16#-----------------------------------------------------------------------------
17# Test functions begin
18
6def test_rehashx():19def test_rehashx():
7 # clear up everything20 # clear up everything
8 _ip.IP.alias_table.clear()21 _ip.IP.alias_table.clear()
@@ -19,3 +32,96 @@
19 # rehashx must fill up syscmdlist32 # rehashx must fill up syscmdlist
20 scoms = _ip.db['syscmdlist']33 scoms = _ip.db['syscmdlist']
21 assert len(scoms) > 1034 assert len(scoms) > 10
35
36
37def doctest_run_ns():
38 """Classes declared %run scripts must be instantiable afterwards.
39
40 In [11]: run tclass
41
42 In [12]: isinstance(f(),foo)
43 Out[12]: True
44 """
45
46
47def doctest_run_ns2():
48 """Classes declared %run scripts must be instantiable afterwards.
49
50 In [3]: run tclass.py
51
52 In [4]: run tclass first_pass
53
54 In [5]: run tclass second_pass
55 Deleting object: first_pass
56 """
57
58
59def doctest_hist_f():
60 """Test %hist -f with temporary filename.
61
62 In [9]: import tempfile
63
64 In [10]: tfile = tempfile.mktemp('.py','tmp-ipython-')
65
66 In [11]: %history -n -f $tfile 3
67 """
68
69
70def doctest_hist_r():
71 """Test %hist -r
72
73 XXX - This test is not recording the output correctly. Not sure why...
74
75 In [6]: x=1
76
77 In [7]: hist -n -r 2
78 x=1 # random
79 hist -n -r 2 # random
80 """
81
82
83def test_shist():
84 # Simple tests of ShadowHist class - test generator.
85 import os, shutil, tempfile
86
87 from IPython.Extensions import pickleshare
88 from IPython.history import ShadowHist
89
90 tfile = tempfile.mktemp('','tmp-ipython-')
91
92 db = pickleshare.PickleShareDB(tfile)
93 s = ShadowHist(db)
94 s.add('hello')
95 s.add('world')
96 s.add('hello')
97 s.add('hello')
98 s.add('karhu')
99
100 yield nt.assert_equals,s.all(),[(1, 'hello'), (2, 'world'), (3, 'karhu')]
101
102 yield nt.assert_equal,s.get(2),'world'
103
104 shutil.rmtree(tfile)
105
106@dec.skipif_not_numpy
107def test_numpy_clear_array_undec():
108 _ip.ex('import numpy as np')
109 _ip.ex('a = np.empty(2)')
110
111 yield nt.assert_true,'a' in _ip.user_ns
112 _ip.magic('clear array')
113 yield nt.assert_false,'a' in _ip.user_ns
114
115
116@dec.skip()
117def test_fail_dec(*a,**k):
118 yield nt.assert_true, False
119
120@dec.skip('This one shouldn not run')
121def test_fail_dec2(*a,**k):
122 yield nt.assert_true, False
123
124@dec.skipknownfailure
125def test_fail_dec3(*a,**k):
126 yield nt.assert_true, False
127
22128
=== modified file 'IPython/twshell.py'
--- IPython/twshell.py 2008-04-26 07:17:18 +0000
+++ IPython/twshell.py 2009-03-11 06:53:19 +0000
@@ -1,3 +1,7 @@
1"""Twisted shell support.
2
3XXX - This module is missing proper docs.
4"""
1import sys5import sys
26
3from twisted.internet import reactor, threads7from twisted.internet import reactor, threads
48
=== modified file 'IPython/ultraTB.py'
--- IPython/ultraTB.py 2008-08-24 06:10:55 +0000
+++ IPython/ultraTB.py 2009-03-11 06:53:19 +0000
@@ -59,8 +59,7 @@
59You can implement other color schemes easily, the syntax is fairly59You can implement other color schemes easily, the syntax is fairly
60self-explanatory. Please send back new schemes you develop to the author for60self-explanatory. Please send back new schemes you develop to the author for
61possible inclusion in future releases.61possible inclusion in future releases.
6262"""
63$Id: ultraTB.py 2908 2007-12-30 21:07:46Z vivainio $"""
6463
65#*****************************************************************************64#*****************************************************************************
66# Copyright (C) 2001 Nathaniel Gray <n8gray@caltech.edu>65# Copyright (C) 2001 Nathaniel Gray <n8gray@caltech.edu>
@@ -70,11 +69,6 @@
70# the file COPYING, distributed as part of this software.69# the file COPYING, distributed as part of this software.
71#*****************************************************************************70#*****************************************************************************
7271
73from IPython import Release
74__author__ = '%s <%s>\n%s <%s>' % (Release.authors['Nathan']+
75 Release.authors['Fernando'])
76__license__ = Release.license
77
78# Required modules72# Required modules
79import inspect73import inspect
80import keyword74import keyword
@@ -98,7 +92,7 @@
98# Modified pdb which doesn't damage IPython's readline handling92# Modified pdb which doesn't damage IPython's readline handling
99from IPython import Debugger, PyColorize93from IPython import Debugger, PyColorize
100from IPython.ipstruct import Struct94from IPython.ipstruct import Struct
101from IPython.excolors import ExceptionColors95from IPython.excolors import exception_colors
102from IPython.genutils import Term,uniq_stable,error,info96from IPython.genutils import Term,uniq_stable,error,info
10397
104# Globals98# Globals
@@ -320,7 +314,7 @@
320 self.call_pdb = call_pdb314 self.call_pdb = call_pdb
321315
322 # Create color table316 # Create color table
323 self.color_scheme_table = ExceptionColors 317 self.color_scheme_table = exception_colors()
324318
325 self.set_colors(color_scheme)319 self.set_colors(color_scheme)
326 self.old_scheme = color_scheme # save initial value for toggles320 self.old_scheme = color_scheme # save initial value for toggles
327321
=== modified file 'IPython/usage.py'
--- IPython/usage.py 2008-02-28 18:21:11 +0000
+++ IPython/usage.py 2009-03-11 06:53:19 +0000
@@ -6,13 +6,6 @@
6# the file COPYING, distributed as part of this software.6# the file COPYING, distributed as part of this software.
7#*****************************************************************************7#*****************************************************************************
88
9# $Id: usage.py 2723 2007-09-07 07:44:16Z fperez $
10
11from IPython import Release
12__author__ = '%s <%s>' % Release.authors['Fernando']
13__license__ = Release.license
14__version__ = Release.version
15
16__doc__ = """9__doc__ = """
17IPython -- An enhanced Interactive Python10IPython -- An enhanced Interactive Python
18=========================================11=========================================
@@ -650,5 +643,3 @@
650The following magic functions are currently available:643The following magic functions are currently available:
651644
652"""645"""
653
654
655646
=== modified file 'IPython/wildcard.py'
--- IPython/wildcard.py 2008-02-16 09:50:47 +0000
+++ IPython/wildcard.py 2009-03-11 06:53:19 +0000
@@ -1,7 +1,5 @@
1# -*- coding: utf-8 -*-1# -*- coding: utf-8 -*-
2"""Support for wildcard pattern matching in object inspection.2"""Support for wildcard pattern matching in object inspection.
3
4$Id: OInspect.py 608 2005-07-06 17:52:32Z fperez $
5"""3"""
64
7#*****************************************************************************5#*****************************************************************************
86
=== modified file 'docs/Makefile'
--- docs/Makefile 2008-08-28 23:34:53 +0000
+++ docs/Makefile 2009-03-11 01:24:53 +0000
@@ -5,13 +5,14 @@
5SPHINXOPTS =5SPHINXOPTS =
6SPHINXBUILD = sphinx-build6SPHINXBUILD = sphinx-build
7PAPER =7PAPER =
8SRCDIR = source
89
9# Internal variables.10# Internal variables.
10PAPEROPT_a4 = -D latex_paper_size=a411PAPEROPT_a4 = -D latex_paper_size=a4
11PAPEROPT_letter = -D latex_paper_size=letter12PAPEROPT_letter = -D latex_paper_size=letter
12ALLSPHINXOPTS = -d build/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source13ALLSPHINXOPTS = -d build/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) $(SRCDIR)
1314
14.PHONY: help clean html web pickle htmlhelp latex changes linkcheck15.PHONY: help clean html web pickle htmlhelp latex changes linkcheck api
1516
16help:17help:
17 @echo "Please use \`make <target>' where <target> is one of"18 @echo "Please use \`make <target>' where <target> is one of"
@@ -28,7 +29,7 @@
28 @echo "dist all, and then puts the results in dist/"29 @echo "dist all, and then puts the results in dist/"
2930
30clean:31clean:
31 -rm -rf build/* dist/*32 -rm -rf build/* dist/* $(SRCDIR)/api/generated
3233
33pdf: latex34pdf: latex
34 cd build/latex && make all-pdf35 cd build/latex && make all-pdf
@@ -41,12 +42,16 @@
41 cp -al build/html dist/42 cp -al build/html dist/
42 @echo "Build finished. Final docs are in dist/"43 @echo "Build finished. Final docs are in dist/"
4344
44html:45html: api
45 mkdir -p build/html build/doctrees46 mkdir -p build/html build/doctrees
46 $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) build/html47 $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) build/html
47 @echo48 @echo
48 @echo "Build finished. The HTML pages are in build/html."49 @echo "Build finished. The HTML pages are in build/html."
4950
51api:
52 python autogen_api.py
53 @echo "Build API docs finished."
54
50pickle:55pickle:
51 mkdir -p build/pickle build/doctrees56 mkdir -p build/pickle build/doctrees
52 $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) build/pickle57 $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) build/pickle
5358
=== added file 'docs/autogen_api.py'
--- docs/autogen_api.py 1970-01-01 00:00:00 +0000
+++ docs/autogen_api.py 2009-03-11 01:24:53 +0000
@@ -0,0 +1,33 @@
1#!/usr/bin/env python
2"""Script to auto-generate our API docs.
3"""
4# stdlib imports
5import os
6import sys
7
8# local imports
9sys.path.append(os.path.abspath('sphinxext'))
10from apigen import ApiDocWriter
11
12#*****************************************************************************
13if __name__ == '__main__':
14 pjoin = os.path.join
15 package = 'IPython'
16 outdir = pjoin('source','api','generated')
17 docwriter = ApiDocWriter(package,rst_extension='.txt')
18 docwriter.package_skip_patterns += [r'\.fixes$',
19 r'\.externals$',
20 r'\.Extensions',
21 r'\.kernel.config',
22 r'\.attic',
23 ]
24 docwriter.module_skip_patterns += [ r'\.FakeModule',
25 r'\.cocoa',
26 r'\.ipdoctest',
27 r'\.Gnuplot',
28 ]
29 docwriter.write_api_docs(outdir)
30 docwriter.write_index(outdir, 'gen',
31 relative_to = pjoin('source','api')
32 )
33 print '%d files written' % len(docwriter.written_modules)
034
=== added directory 'docs/source/api'
=== added file 'docs/source/api/index.txt'
--- docs/source/api/index.txt 1970-01-01 00:00:00 +0000
+++ docs/source/api/index.txt 2009-03-11 01:24:53 +0000
@@ -0,0 +1,12 @@
1.. _api-index:
2
3###################
4 The IPython API
5###################
6
7.. htmlonly::
8
9 :Release: |version|
10 :Date: |today|
11
12.. include:: generated/gen.txt
013
=== modified file 'docs/source/conf.py'
--- docs/source/conf.py 2008-09-14 07:58:49 +0000
+++ docs/source/conf.py 2009-03-11 01:24:53 +0000
@@ -36,9 +36,13 @@
36# Add any Sphinx extension module names here, as strings. They can be extensions36# Add any Sphinx extension module names here, as strings. They can be extensions
37# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.37# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
38extensions = ['sphinx.ext.autodoc',38extensions = ['sphinx.ext.autodoc',
39 'inheritance_diagram', 'only_directives',39 'sphinx.ext.doctest',
40
41 'only_directives',
42 'inheritance_diagram',
40 'ipython_console_highlighting', 43 'ipython_console_highlighting',
41 # 'plot_directive', # disabled for now, needs matplotlib44 # 'plot_directive', # disabled for now, needs matplotlib
45 'numpydoc', # to preprocess docstrings
42 ]46 ]
4347
44# Add any paths that contain templates here, relative to this directory.48# Add any paths that contain templates here, relative to this directory.
4549
=== added file 'docs/source/development/coding_guide.txt'
--- docs/source/development/coding_guide.txt 1970-01-01 00:00:00 +0000
+++ docs/source/development/coding_guide.txt 2008-10-04 07:47:34 +0000
@@ -0,0 +1,141 @@
1==============
2 Coding guide
3==============
4
5
6Coding conventions
7==================
8
9In general, we'll try to follow the standard Python style conventions as
10described in Python's `PEP 8`_, the official Python Style Guide.
11
12.. _PEP 8: http://www.python.org/peps/pep-0008.html
13
14Other comments:
15
16- In a large file, top level classes and functions should be separated by 2-3
17 lines to make it easier to separate them visually.
18
19- Use 4 spaces for indentation, *never* use hard tabs.
20
21- Keep the ordering of methods the same in classes that have the same methods.
22 This is particularly true for classes that implement similar interfaces and
23 for interfaces that are similar.
24
25Naming conventions
26------------------
27
28In terms of naming conventions, we'll follow the guidelines of PEP 8. Some of
29the existing code doesn't honor this perfectly, but for all new IPython code
30(and much existing code is being refactored), we'll use:
31
32- All ``lowercase`` module names.
33
34- ``CamelCase`` for class names.
35
36- ``lowercase_with_underscores`` for methods, functions, variables and
37 attributes.
38
39This may be confusing as some of the existing codebase uses a different
40convention (``lowerCamelCase`` for methods and attributes). Slowly, we will
41move IPython over to the new convention, providing shadow names for backward
42compatibility in public interfaces.
43
44There are, however, some important exceptions to these rules. In some cases,
45IPython code will interface with packages (Twisted, Wx, Qt) that use other
46conventions. At some level this makes it impossible to adhere to our own
47standards at all times. In particular, when subclassing classes that use other
48naming conventions, you must follow their naming conventions. To deal with
49cases like this, we propose the following policy:
50
51- If you are subclassing a class that uses different conventions, use its
52 naming conventions throughout your subclass. Thus, if you are creating a
53 Twisted Protocol class, used Twisted's
54 ``namingSchemeForMethodsAndAttributes.``
55
56- All IPython's official interfaces should use our conventions. In some cases
57 this will mean that you need to provide shadow names (first implement
58 ``fooBar`` and then ``foo_bar = fooBar``). We want to avoid this at all
59 costs, but it will probably be necessary at times. But, please use this
60 sparingly!
61
62Implementation-specific *private* methods will use
63``_single_underscore_prefix``. Names with a leading double underscore will
64*only* be used in special cases, as they makes subclassing difficult (such
65names are not easily seen by child classes).
66
67Occasionally some run-in lowercase names are used, but mostly for very short
68names or where we are implementing methods very similar to existing ones in a
69base class (like ``runlines()`` where ``runsource()`` and ``runcode()`` had
70established precedent).
71
72The old IPython codebase has a big mix of classes and modules prefixed with an
73explicit ``IP``. In Python this is mostly unnecessary, redundant and frowned
74upon, as namespaces offer cleaner prefixing. The only case where this approach
75is justified is for classes which are expected to be imported into external
76namespaces and a very generic name (like Shell) is too likely to clash with
77something else. We'll need to revisit this issue as we clean up and refactor
78the code, but in general we should remove as many unnecessary ``IP``/``ip``
79prefixes as possible. However, if a prefix seems absolutely necessary the more
80specific ``IPY`` or ``ipy`` are preferred.
81
82
83.. _devel-testing:
84
85Testing system
86==============
87
88It is extremely important that all code contributed to IPython has tests. Tests
89should be written as unittests, doctests or as entities that the `Nose`_
90testing package will find. Regardless of how the tests are written, we will use
91`Nose`_ for discovering and running the tests. `Nose`_ will be required to run
92the IPython test suite, but will not be required to simply use IPython.
93
94.. _Nose: http://code.google.com/p/python-nose/
95
96Tests of `Twisted`__ using code should be written by subclassing the
97``TestCase`` class that comes with ``twisted.trial.unittest``. When this is
98done, `Nose`_ will be able to run the tests and the twisted reactor will be
99handled correctly.
100
101.. __: http://www.twistedmatrix.com
102
103Each subpackage in IPython should have its own ``tests`` directory that
104contains all of the tests for that subpackage. This allows each subpackage to
105be self-contained. If a subpackage has any dependencies beyond the Python
106standard library, the tests for that subpackage should be skipped if the
107dependencies are not found. This is very important so users don't get tests
108failing simply because they don't have dependencies.
109
110We also need to look into use Noses ability to tag tests to allow a more
111modular approach of running tests.
112
113.. _devel-config:
114
115Configuration system
116====================
117
118IPython uses `.ini`_ files for configuration purposes. This represents a huge
119improvement over the configuration system used in IPython. IPython works with
120these files using the `ConfigObj`_ package, which IPython includes as
121``ipython1/external/configobj.py``.
122
123Currently, we are using raw `ConfigObj`_ objects themselves. Each subpackage of
124IPython should contain a ``config`` subdirectory that contains all of the
125configuration information for the subpackage. To see how configuration
126information is defined (along with defaults) see at the examples in
127``ipython1/kernel/config`` and ``ipython1/core/config``. Likewise, to see how
128the configuration information is used, see examples in
129``ipython1/kernel/scripts/ipengine.py``.
130
131Eventually, we will add a new layer on top of the raw `ConfigObj`_ objects. We
132are calling this new layer, ``tconfig``, as it will use a `Traits`_-like
133validation model. We won't actually use `Traits`_, but will implement
134something similar in pure Python. But, even in this new system, we will still
135use `ConfigObj`_ and `.ini`_ files underneath the hood. Talk to Fernando if you
136are interested in working on this part of IPython. The current prototype of
137``tconfig`` is located in the IPython sandbox.
138
139.. _.ini: http://docs.python.org/lib/module-ConfigParser.html
140.. _ConfigObj: http://www.voidspace.org.uk/python/configobj.html
141.. _Traits: http://code.enthought.com/traits/
0142
=== added file 'docs/source/development/doc_guide.txt'
--- docs/source/development/doc_guide.txt 1970-01-01 00:00:00 +0000
+++ docs/source/development/doc_guide.txt 2009-03-11 06:58:43 +0000
@@ -0,0 +1,103 @@
1.. _documenting-ipython:
2
3=====================
4 Documenting IPython
5=====================
6
7Standalone documentation
8========================
9
10All standalone documentation should be written in plain text (``.txt``) files
11using `reStructuredText`_ for markup and formatting. All such documentation
12should be placed in the top level directory ``docs`` of the IPython source
13tree. Or, when appropriate, a suitably named subdirectory should be used. The
14documentation in this location will serve as the main source for IPython
15documentation and all existing documentation should be converted to this
16format.
17
18The actual HTML and PDF docs are built using the Sphinx_ documentation
19generation tool. Sphinx has been adopted as the default documentation tool for
20Python itself as of version 2.6, as well as by a number of projects that
21IPython is related with, such as numpy, scipy, matplotlib, sage and nipy.
22
23.. _reStructuredText: http://docutils.sourceforge.net/rst.html
24.. _Sphinx: http://sphinx.pocoo.org/
25
26
27The rest of this document is mostly taken from the `matploblib
28documentation`__; we are using a number of Sphinx tools and extensions written
29by the matplotlib team and will mostly follow their conventions, which are
30nicely spelled out in their guide. What follows is thus a lightly adapted
31version of the matplotlib documentation guide, taken with permission from the
32MPL team.
33
34.. __: http://matplotlib.sourceforge.net/devel/documenting_mpl.html
35
36
37A bit of Python code::
38
39 for i in range(10):
40 print i,
41 print "A big number:",2**34
42
43An interactive Python session::
44
45 >>> from IPython import genutils
46 >>> genutils.get_ipython_dir()
47 '/home/fperez/.ipython'
48
49
50An IPython session:
51
52.. code-block:: ipython
53
54 In [7]: import IPython
55
56 In [8]: print "This IPython is version:",IPython.__version__
57 This IPython is version: 0.9.1
58
59 In [9]: 2+4
60 Out[9]: 6
61
62
63A bit of shell code:
64
65.. code-block:: bash
66
67 cd /tmp
68 echo "My home directory is: $HOME"
69 ls
70
71
72Docstring format
73================
74
75Good docstrings are very important. Unfortunately, Python itself only provides
76a rather loose standard for docstrings (`PEP 257`_), and there is no universally
77accepted convention for all the different parts of a complete docstring.
78However, the NumPy project has established a very reasonable standard, and has
79developed some tools to support the smooth inclusion of such docstrings in
80Sphinx-generated manuals. Rather than inventing yet another pseudo-standard,
81IPython will be henceforth documented using the NumPy conventions; we carry
82copies of some of the NumPy support tools to remain self-contained, but share
83back upstream with NumPy any improvements or fixes we may make to the tools.
84
85The `NumPy documentation guidelines`_ contain detailed information on this
86standard, and for a quick overview, the NumPy `example docstring`_ is a useful
87read.
88
89As in the past IPython used epydoc, currently many docstrings still use epydoc
90conventions. We will update them as we go, but all new code should be fully
91documented using the NumPy standard.
92
93.. _PEP 257: http://www.python.org/peps/pep-0257.html
94.. _NumPy documentation guidelines: http://projects.scipy.org/numpy/wiki/CodingStyleGuidelines
95
96.. _example docstring: http://projects.scipy.org/numpy/browser/trunk/doc/EXAMPLE_DOCSTRING.txt
97
98Additional PEPs of interest regarding documentation of code. While both of
99these were rejected, the ideas therein form much of the basis of docutils (the
100machinery to process reStructuredText):
101
102- `Docstring Processing System Framework <http://www.python.org/peps/pep-0256.html>`_
103- `Docutils Design Specification <http://www.python.org/peps/pep-0258.html>`_
0104
=== modified file 'docs/source/development/index.txt'
--- docs/source/development/index.txt 2008-09-11 23:58:46 +0000
+++ docs/source/development/index.txt 2008-10-04 07:47:34 +0000
@@ -1,10 +1,13 @@
1==================1===========================
2Development2 IPython Developer's Guide
3==================3===========================
44
5.. toctree::5.. toctree::
6 :maxdepth: 26 :maxdepth: 2
77
8 development.txt8 overview.txt
9 coding_guide.txt
10 doc_guide.txt
9 roadmap.txt11 roadmap.txt
12
10 notification_blueprint.txt13 notification_blueprint.txt
1114
=== renamed file 'docs/source/development/development.txt' => 'docs/source/development/overview.txt'
--- docs/source/development/development.txt 2008-09-15 03:37:13 +0000
+++ docs/source/development/overview.txt 2008-10-04 07:47:34 +0000
@@ -1,32 +1,35 @@
1.. This file has a lot of bash but little python, set default role
2
3.. highlight:: bash
4
1.. _development:5.. _development:
26
3==============================7==============================
4IPython development guidelines8 IPython development overview
5==============================9==============================
610
711Currently, IPython's development tree contains all of the code that used to be
8Overview12part of IPython since the project's inception in 2001, plus all of the effort
9========13that was known for a while (roughly 2004-2008) as ``IPython1``. The IPyhton1
1014development was meant to be an effort to:
11IPython is the next generation of IPython. It is named such for two reasons:
12
13- Eventually, IPython will become IPython version 1.0.
14- This new code base needs to be able to co-exist with the existing IPython until
15 it is a full replacement for it. Thus we needed a different name. We couldn't
16 use ``ipython`` (lowercase) as some files systems are case insensitive.
17
18There are two, no three, main goals of the IPython effort:
1915
201. Clean up the existing codebase and write lots of tests.161. Clean up the existing codebase and write lots of tests.
212. Separate the core functionality of IPython from the terminal to enable IPython17
22 to be used from within a variety of GUI applications.182. Separate the core functionality of IPython from the terminal to enable
19 IPython to be used from within a variety of GUI applications.
20
233. Implement a system for interactive parallel computing.213. Implement a system for interactive parallel computing.
2422
25While the third goal may seem a bit unrelated to the main focus of IPython, it23While the third goal may seem a bit unrelated to the main focus of IPython, it
26turns out that the technologies required for this goal are nearly identical24turns out that the technologies required for this goal are nearly identical
27with those required for goal two. This is the main reason the interactive25with those required for goal two. This is the main reason the interactive
28parallel computing capabilities are being put into IPython proper. Currently26parallel computing capabilities are being put into IPython proper.
29the third of these goals is furthest along.27
28In the summer of 2008, the IPython1 code was merged back into the mainline, and
29now there is a unified codebase. While the above goals aren't completely
30implemented for the older code, we do have a proper :ref:`testing system
31<devel-testing>` in place (though this is still evolving), unified
32documentation and partial implementations of the more separated components.
3033
31This document describes IPython from the perspective of developers. 34This document describes IPython from the perspective of developers.
3235
@@ -46,16 +49,19 @@
46 49
47- **Tests**. Each subpackage shoud have its own ``tests`` subdirectory that50- **Tests**. Each subpackage shoud have its own ``tests`` subdirectory that
48 contains all of the tests for that package. For information about writing51 contains all of the tests for that package. For information about writing
49 tests for IPython, see the `Testing System`_ section of this document.52 tests for IPython, see the :ref:`Testing System <devel-testing>` section of
53 this document.
50 54
51- **Configuration**. Each subpackage should have its own ``config``55- **Configuration**. Each subpackage should have its own ``config``
52 subdirectory that contains the configuration information for the components56 subdirectory that contains the configuration information for the components
53 of the subpackage. For information about how the IPython configuration57 of the subpackage. For information about how the IPython configuration
54 system works, see the `Configuration System`_ section of this document.58 system works, see the :ref:`Configuration System <devel-config>` section of
59 this document.
55 60
56- **Scripts**. Each subpackage should have its own ``scripts`` subdirectory61- **Scripts**. Each subpackage should have its own ``scripts`` subdirectory
57 that contains all of the command line scripts associated with the subpackage.62 that contains all of the command line scripts associated with the subpackage.
5863
64
59Installation and dependencies65Installation and dependencies
60-----------------------------66-----------------------------
61 67
@@ -117,266 +123,132 @@
117 today 's IPython. Other frontends will likely be more powerful and based123 today 's IPython. Other frontends will likely be more powerful and based
118 on GUI toolkits.124 on GUI toolkits.
119125
120``notebook``
121 An application that allows users to work with IPython notebooks.
122
123``tools``126``tools``
124 This is where general utilities go.127 This is where general utilities go.
125128
126129
127Version control130Version control workflow
128===============131========================
129132
130In the past, IPython development has been done using `Subversion`__. Recently,133All IPython development today is done using the `Bazaar`__ system for
131we made the transition to using `Bazaar`__ and `Launchpad`__. This makes it134distributed version control and the `Launchpad`__ site for code hosting and bug
132much easier for people to contribute code to IPython. Here is a sketch of how135tracking. This makes it very easy for anyone to contribute code to IPython.
133to use Bazaar for IPython development. First, you should install Bazaar.136
134After you have done that, make sure that it is working by getting the latest137.. __: http://bazaar-vcs.org
135main branch of IPython::138.. __: http://launchpad.net/ipython
136139
137 $ bzr branch lp:ipython140If you are interested in contributing to IPython, you should familiarize a bit
138141with how to use bazaar, but this document gives you a concise set of steps to
139Now you can create a new branch for you to do your work in::142get started. If you are going to become heavily involved with creating code
140143for IPython you'll eventually want to have a Launchpad account (free) so you
141 $ bzr branch ipython ipython-mybranch144can publish your own code on the site for review and merging, but small
142145contributions can be simply sent via email to the IPython list as patches.
143The typical work cycle in this branch will be to make changes in146
144``ipython-mybranch`` and then commit those changes using the commit command::147Start by creating what Bazaar calls a `shared repository`_::
145148
146 $ ...do work in ipython-mybranch...149 # You can choose any name you want instead of "ipython-repo"
147 $ bzr ci -m "the commit message goes here"150 bzr init-repo ipython-repo
151
152.. _shared repository: http://bazaar-vcs.org/SharedRepositoryTutorial
153
154This creates an empty repository where a lot of related branches can be kept,
155and they all reuse common storage. This way, many operations are very fast and
156take up less space. Now, go to the newly created repository and make a local
157branch of the public trunk::
158
159 cd ipython-repo
160 # This makes a local copy of the public trunk called "trunk-lp"
161 bzr branch lp:ipython trunk-lp
162
163The ``trunk-lp`` branch is meant to always be a pristine copy of the public
164trunk. From here, make a personal development copy of the public trunk, where
165you'll make your changes::
166
167 bzr branch trunk-lp trunk-dev
168
169Now, your working area looks like this::
170
171 maqroll[ipython-repo]> ls -a
172 ./ ../ .bzr/ trunk-dev/ trunk-lp/
173
174The ``.bzr`` directory is the Bazaar storage area, and you now have both the
175reference copy of the public trunk and one working copy for your own
176development. You can later make further branches as needed (a common workflow
177is to make branches to contain specific feature implementations until they are
178ready to be merged).
179
180The typical work cycle will be to make changes in ``trunk-dev`` and then commit
181those changes as often as needed::
182
183 cd trunk-dev
184 # ... implement cool new feature...
185 bzr commit -m "Commit message goes here."
148186
149Please note that since we now don't use an old-style linear ChangeLog (that187Please note that since we now don't use an old-style linear ChangeLog (that
150tends to cause problems with distributed version control systems), you should188tends to cause problems with distributed version control systems), you should
151ensure that your log messages are reasonably detailed. Use a docstring-like189ensure that your log messages are reasonably detailed. For non-trivial
152approach in the commit messages (including the second line being left190changes, use a docstring-like approach in the commit messages (including the
153*blank*)::191second line being left *blank*). Type ``bzr commit`` *without* the ``-m``
154192switch, and Bazaar will open an editor where you can type a more detailed
155 Single line summary of changes being committed.193message::
156194
157 - more details when warranted ...195 Single line summary of changes being committed.
158 - including crediting outside contributors if they sent the196
159 code/bug/idea!197 - more details when warranted ...
198 - including crediting outside contributors if they sent the
199 code/bug/idea!
160200
161If we couple this with a policy of making single commits for each reasonably201If we couple this with a policy of making single commits for each reasonably
162atomic change, the bzr log should give an excellent view of the project, and202atomic change, the bzr log should give an excellent view of the project, and
163the `--short` log option becomes a nice summary.203the ``--short`` log option becomes a nice summary.
164204
165While working with this branch, it is a good idea to merge in changes that have205As you work on the branch, it's a good idea to frequently keep your copy of the
166been made upstream in the parent branch. This can be done by doing::206trunk updated with respect to Launchpad. This is done via::
167207
168 $ bzr pull208 cd trunk-lp
209 bzr pull
210
211Bazaar can then merge any changes that were done to the public trunk into your
212local branch via::
213
214 cd trunk-dev
215 bzr merge ../trunk-lp
216 bzr commit -m"Merged upstream changes"
217
218This workflow ensures that a local copy stays in sync with the public trunk,
219while allowing for local development to be pushed back for public review.
220
221Once your changes are ready for review, you can push them to Launchpad where
222the IPython team can review them and give you feedback. The first time, use::
223
224 bzr push --remember \
225 bzr+ssh://<you>@bazaar.launchpad.net/~<you>/ipython/trunk-dev
226
227where ``<you>`` is your Launchpad user name. This will make this branch
228publicly visible to all. In subsequent uses you can simply run in the branch::
229
230 bzr push
231
232.. note::
233
234 Before you can push your code to Launchpad, you need to configure your SSH
235 keys. You can do this by clicking on ``Change details`` for your profile
236 and then clicking on the ``SSH Keys`` tab. This should take you to a URL
237 of the form ``https://launchpad.net/~<you>/+editsshkeys`` with instructions
238 on how to upload your keys.
169 239
170If this command shows that the branches have diverged, then you should do a240Once the branch is publicly visible, using the launchpad interface it can be
171merge instead::241marked for merging with the link marked *"Propose for merging into another
172242branch"*, leaving the default choice of trunk as its target. This way,
173 $ bzr merge lp:ipython243Launchpad tracks what changes of this branch are new with respect to the trunk,
174244others in the team can review it, and merge the changes into the trunk.
175If you want others to be able to see your branch, you can create an account245
176with launchpad and push the branch to your own workspace::246The IPython team has a policy of reviewing all code (both from core members of
177247the team and from external contributors) before merging it. Code should be
178 $ bzr push bzr+ssh://<me>@bazaar.launchpad.net/~<me>/+junk/ipython-mybranch248clearly documented (as explained further in this guide), clear and well tested.
179249We will be happy to provide you with feedback for your code to be a great
180Finally, once the work in your branch is done, you can merge your changes back250contribution to the project, and we've found that peer review of code is an
181into the `ipython` branch by using merge::251excellent way to improve the quality of everyone's work.
182
183 $ cd ipython
184 $ merge ../ipython-mybranch
185 [resolve any conflicts]
186 $ bzr ci -m "Fixing that bug"
187 $ bzr push
188
189But this will require you to have write permissions to the `ipython` branch.
190It you don't you can tell one of the IPython devs about your branch and they
191can do the merge for you.
192
193More information about Bazaar workflows can be found `here`__.
194
195.. __: http://subversion.tigris.org/
196.. __: http://bazaar-vcs.org/
197.. __: http://www.launchpad.net/ipython
198.. __: http://doc.bazaar-vcs.org/bzr.dev/en/user-guide/index.html
199
200Documentation
201=============
202
203Standalone documentation
204------------------------
205
206All standalone documentation should be written in plain text (``.txt``) files
207using `reStructuredText`_ for markup and formatting. All such documentation
208should be placed in the top level directory ``docs`` of the IPython source
209tree. Or, when appropriate, a suitably named subdirectory should be used. The
210documentation in this location will serve as the main source for IPython
211documentation and all existing documentation should be converted to this
212format.
213
214In the future, the text files in the ``docs`` directory will be used to
215generate all forms of documentation for IPython. This include documentation on
216the IPython website as well as *pdf* documentation.
217
218.. _reStructuredText: http://docutils.sourceforge.net/rst.html
219
220Docstring format
221----------------
222
223Good docstrings are very important. All new code will use `Epydoc`_ for
224generating API docs, so we will follow the `Epydoc`_ conventions. More
225specifically, we will use `reStructuredText`_ for markup and formatting, since
226it is understood by a wide variety of tools. This means that if in the future
227we have any reason to change from `Epydoc`_ to something else, we'll have fewer
228transition pains.
229
230Details about using `reStructuredText`_ for docstrings can be found `here
231<http://epydoc.sourceforge.net/manual-othermarkup.html>`_.
232
233.. _Epydoc: http://epydoc.sourceforge.net/
234
235Additional PEPs of interest regarding documentation of code:
236
237- `Docstring Conventions <http://www.python.org/peps/pep-0257.html>`_
238- `Docstring Processing System Framework <http://www.python.org/peps/pep-0256.html>`_
239- `Docutils Design Specification <http://www.python.org/peps/pep-0258.html>`_
240
241
242Coding conventions
243==================
244
245General
246-------
247
248In general, we'll try to follow the standard Python style conventions as
249described here:
250
251- `Style Guide for Python Code <http://www.python.org/peps/pep-0008.html>`_
252
253
254Other comments:
255
256- In a large file, top level classes and functions should be
257 separated by 2-3 lines to make it easier to separate them visually.
258- Use 4 spaces for indentation.
259- Keep the ordering of methods the same in classes that have the same
260 methods. This is particularly true for classes that implement
261 similar interfaces and for interfaces that are similar.
262
263Naming conventions
264------------------
265
266In terms of naming conventions, we'll follow the guidelines from the `Style
267Guide for Python Code`_.
268
269For all new IPython code (and much existing code is being refactored), we'll use:
270
271- All ``lowercase`` module names.
272
273- ``CamelCase`` for class names.
274
275- ``lowercase_with_underscores`` for methods, functions, variables and
276 attributes.
277
278This may be confusing as most of the existing IPython codebase uses a different
279convention (``lowerCamelCase`` for methods and attributes). Slowly, we will
280move IPython over to the new convention, providing shadow names for backward
281compatibility in public interfaces.
282
283There are, however, some important exceptions to these rules. In some cases,
284IPython code will interface with packages (Twisted, Wx, Qt) that use other
285conventions. At some level this makes it impossible to adhere to our own
286standards at all times. In particular, when subclassing classes that use other
287naming conventions, you must follow their naming conventions. To deal with
288cases like this, we propose the following policy:
289
290- If you are subclassing a class that uses different conventions, use its
291 naming conventions throughout your subclass. Thus, if you are creating a
292 Twisted Protocol class, used Twisted's
293 ``namingSchemeForMethodsAndAttributes.``
294
295- All IPython's official interfaces should use our conventions. In some cases
296 this will mean that you need to provide shadow names (first implement
297 ``fooBar`` and then ``foo_bar = fooBar``). We want to avoid this at all
298 costs, but it will probably be necessary at times. But, please use this
299 sparingly!
300
301Implementation-specific *private* methods will use
302``_single_underscore_prefix``. Names with a leading double underscore will
303*only* be used in special cases, as they makes subclassing difficult (such
304names are not easily seen by child classes).
305
306Occasionally some run-in lowercase names are used, but mostly for very short
307names or where we are implementing methods very similar to existing ones in a
308base class (like ``runlines()`` where ``runsource()`` and ``runcode()`` had
309established precedent).
310
311The old IPython codebase has a big mix of classes and modules prefixed with an
312explicit ``IP``. In Python this is mostly unnecessary, redundant and frowned
313upon, as namespaces offer cleaner prefixing. The only case where this approach
314is justified is for classes which are expected to be imported into external
315namespaces and a very generic name (like Shell) is too likely to clash with
316something else. We'll need to revisit this issue as we clean up and refactor
317the code, but in general we should remove as many unnecessary ``IP``/``ip``
318prefixes as possible. However, if a prefix seems absolutely necessary the more
319specific ``IPY`` or ``ipy`` are preferred.
320
321.. _devel_testing:
322
323Testing system
324==============
325
326It is extremely important that all code contributed to IPython has tests. Tests
327should be written as unittests, doctests or as entities that the `Nose`_
328testing package will find. Regardless of how the tests are written, we will use
329`Nose`_ for discovering and running the tests. `Nose`_ will be required to run
330the IPython test suite, but will not be required to simply use IPython.
331
332.. _Nose: http://code.google.com/p/python-nose/
333
334Tests of `Twisted`__ using code should be written by subclassing the
335``TestCase`` class that comes with ``twisted.trial.unittest``. When this is
336done, `Nose`_ will be able to run the tests and the twisted reactor will be
337handled correctly.
338
339.. __: http://www.twistedmatrix.com
340
341Each subpackage in IPython should have its own ``tests`` directory that
342contains all of the tests for that subpackage. This allows each subpackage to
343be self-contained. If a subpackage has any dependencies beyond the Python
344standard library, the tests for that subpackage should be skipped if the
345dependencies are not found. This is very important so users don't get tests
346failing simply because they don't have dependencies.
347
348We also need to look into use Noses ability to tag tests to allow a more
349modular approach of running tests.
350
351.. _devel_config:
352
353Configuration system
354====================
355
356IPython uses `.ini`_ files for configuration purposes. This represents a huge
357improvement over the configuration system used in IPython. IPython works with
358these files using the `ConfigObj`_ package, which IPython includes as
359``ipython1/external/configobj.py``.
360
361Currently, we are using raw `ConfigObj`_ objects themselves. Each subpackage of
362IPython should contain a ``config`` subdirectory that contains all of the
363configuration information for the subpackage. To see how configuration
364information is defined (along with defaults) see at the examples in
365``ipython1/kernel/config`` and ``ipython1/core/config``. Likewise, to see how
366the configuration information is used, see examples in
367``ipython1/kernel/scripts/ipengine.py``.
368
369Eventually, we will add a new layer on top of the raw `ConfigObj`_ objects. We
370are calling this new layer, ``tconfig``, as it will use a `Traits`_-like
371validation model. We won't actually use `Traits`_, but will implement
372something similar in pure Python. But, even in this new system, we will still
373use `ConfigObj`_ and `.ini`_ files underneath the hood. Talk to Fernando if you
374are interested in working on this part of IPython. The current prototype of
375``tconfig`` is located in the IPython sandbox.
376
377.. _.ini: http://docs.python.org/lib/module-ConfigParser.html
378.. _ConfigObj: http://www.voidspace.org.uk/python/configobj.html
379.. _Traits: http://code.enthought.com/traits/
380252
381253
382Installation and testing scenarios254Installation and testing scenarios
@@ -386,43 +258,54 @@
386release an IPython version. These scenarios represent different ways of258release an IPython version. These scenarios represent different ways of
387installing IPython and its dependencies.259installing IPython and its dependencies.
388260
261
389Installation scenarios under Linux and OS X262Installation scenarios under Linux and OS X
390-------------------------------------------263-------------------------------------------
391264
392 1. Install from tarball using ``python setup.py install``.2651. Install from tarball using ``python setup.py install``.
393 a. With only readline+nose dependencies installed.266
394 b. With all dependencies installed (readline, zope.interface, Twisted,267 * With only readline+nose dependencies installed.
395 foolscap, Sphinx, nose, pyOpenSSL).268
396 269 * With all dependencies installed (readline, zope.interface, Twisted,
397 2. Install using easy_install.270 foolscap, Sphinx, nose, pyOpenSSL).
398271
399 a. With only readline+nose dependencies installed.2722. Install using easy_install.
400 i. Default dependencies: ``easy_install ipython-0.9.beta3-py2.5.egg``273
401 ii. Optional dependency sets: ``easy_install -f ipython-0.9.beta3-py2.5.egg IPython[kernel,doc,test,security]``274 * With only readline+nose dependencies installed.
402275
403 b. With all dependencies already installed.276 * Default dependencies: ``easy_install ipython-0.9.beta3-py2.5.egg``
277
278 * Optional dependency sets:
279 ``easy_install -f ipython-0.9.beta3-py2.5.egg IPython[kernel,doc,test,security]``
280
281 * With all dependencies already installed.
404 282
405283
406Installation scenarios under Win32284Installation scenarios under Win32
407----------------------------------285----------------------------------
408286
409 1. Install everything from .exe installers287#. Install everything from .exe installers
410 2. easy_install?288#. easy_install?
411289
412290
413Tests to run for these scenarios291Tests to run for these scenarios
414--------------------------------292--------------------------------
415293
416 1. Run the full test suite.294#. Run the full test suite.
417 2. Start a controller and engines and try a few things by hand.295
418 a. Using ipcluster.296#. Start a controller and engines and try a few things by hand.
419 b. Using ipcontroller/ipengine by hand.297
420298 * Using ipcluster.
421 3. Run a few of the parallel examples.299 * Using ipcontroller/ipengine by hand.
422 4. Try the kernel with and without security with and without PyOpenSSL300
423 installed.301#. Run a few of the parallel examples.
424 5. Beat on the IPython terminal a bunch.302
425 6. Make sure that furl files are being put in proper locations.303#. Try the kernel with and without security with and without PyOpenSSL
304 installed.
305
306#. Beat on the IPython terminal a bunch.
307
308#. Make sure that furl files are being put in proper locations.
426309
427310
428Release checklist311Release checklist
429312
=== modified file 'docs/source/index.txt'
--- docs/source/index.txt 2008-09-15 03:37:13 +0000
+++ docs/source/index.txt 2009-03-11 01:24:53 +0000
@@ -17,10 +17,11 @@
17 interactive/index.txt17 interactive/index.txt
18 parallel/index.txt18 parallel/index.txt
19 config/index.txt19 config/index.txt
20 faq.txt
21 history.txt
20 changes.txt22 changes.txt
21 development/index.txt23 development/index.txt
22 faq.txt24 api/index.txt
23 history.txt
24 license_and_copyright.txt25 license_and_copyright.txt
25 credits.txt26 credits.txt
2627
2728
=== modified file 'docs/source/install/index.txt'
--- docs/source/install/index.txt 2008-09-11 23:49:58 +0000
+++ docs/source/install/index.txt 2008-10-04 05:37:23 +0000
@@ -1,8 +1,8 @@
1.. _install_index:1.. _install_index:
22
3==================3============
4Installation4Installation
5==================5============
66
7.. toctree::7.. toctree::
8 :maxdepth: 28 :maxdepth: 2
99
=== modified file 'docs/source/install/install.txt'
--- docs/source/install/install.txt 2008-09-13 15:14:14 +0000
+++ docs/source/install/install.txt 2008-10-04 07:47:34 +0000
@@ -1,77 +1,126 @@
1.. There's little Python in this file, so make the default language bash.
2
3.. highlight:: bash
4
1Overview5Overview
2========6========
37
4This document describes the steps required to install IPython. IPython is organized into a number of subpackages, each of which has its own dependencies. All of the subpackages come with IPython, so you don't need to download and install them separately. However, to use a given subpackage, you will need to install all of its dependencies. 8This document describes the steps required to install IPython. IPython is
9organized into a number of subpackages, each of which has its own dependencies.
10All of the subpackages come with IPython, so you don't need to download and
11install them separately. However, to use a given subpackage, you will need to
12install all of its dependencies.
513
614
7Please let us know if you have problems installing IPython or any of its15Please let us know if you have problems installing IPython or any of its
8dependencies. IPython requires Python version 2.4 or greater. We have not tested16dependencies. IPython requires Python version 2.4 or greater. We have not
9IPython with the upcoming 2.6 or 3.0 versions.17tested IPython with the upcoming 2.6 or 3.0 versions, though preliminary
18reports of 2.6 usage are encouraging. 3.0 porting will take longer, however.
1019
11.. warning::20.. warning::
1221
13 IPython will not work with Python 2.3 or below.22 IPython will not work with Python 2.3 or below.
1423
15Some of the installation approaches use the :mod:`setuptools` package and its :command:`easy_install` command line program. In many scenarios, this provides the most simple method of installing IPython and its dependencies. It is not required though. More information about :mod:`setuptools` can be found on its website.24Some of the installation approaches use the :mod:`setuptools` package and its
1625:command:`easy_install` command line program. In many scenarios, this provides
17More general information about installing Python packages can be found in Python's documentation at http://www.python.org/doc/.26the most simple method of installing IPython and its dependencies. It is not
27required though. More information about :mod:`setuptools` can be found on its
28website.
29
30More general information about installing Python packages can be found in
31Python's documentation at http://www.python.org/doc/.
32
1833
19Installing IPython itself34Installing IPython itself
20=========================35=========================
2136
22Given a properly built Python, the basic interactive IPython shell will work with no external dependencies. However, some Python distributions (particularly on Windows and OS X), don't come with a working :mod:`readline` module. The IPython shell will work without :mod:`readline`, but will lack many features that users depend on, such as tab completion and command line editing. See below for details of how to make sure you have a working :mod:`readline`.37Given a properly built Python, the basic interactive IPython shell will work
38with no external dependencies. However, some Python distributions
39(particularly on Windows and OS X), don't come with a working :mod:`readline`
40module. The IPython shell will work without :mod:`readline`, but will lack
41many features that users depend on, such as tab completion and command line
42editing. See below for details of how to make sure you have a working
43:mod:`readline`.
2344
24Installation using easy_install45Installation using easy_install
25-------------------------------46-------------------------------
2647
27If you have :mod:`setuptools` installed, the easiest way of getting IPython is to simple use :command:`easy_install`::48If you have :mod:`setuptools` installed, the easiest way of getting IPython is
2849to use :command:`easy_install`::
29 $ easy_install IPython50
3051 easy_install IPython
31That's it.52
53Unless you've written a custom distutils script as explained `here`__, that will
54try to install either in a default system-wide location, which may require
55administrator access. If that is the case, you can either run the command with
56root privileges::
57
58 sudo easy_install IPython
59
60or you can specify an alternate location, for example::
61
62 easy_install --prefix=~/usr/local IPython
63
64where this assumes that ``~/usr/local`` is a valid prefix for you to install
65packages to in your user account.
66
67.. __: http://docs.python.org/install/index.html#inst-config-files
68
3269
33Installation from source70Installation from source
34------------------------71------------------------
3572
36If you don't want to use :command:`easy_install`, or don't have it installed, just grab the latest stable build of IPython from `here <http://ipython.scipy.org/dist/>`_. Then do the following::73If you don't want to use :command:`easy_install`, or don't have it installed,
3774just grab the latest stable build of IPython from `here
38 $ tar -xzf ipython.tar.gz75<http://ipython.scipy.org/dist/>`_. Then do the following (using the
39 $ cd ipython76appropriate version number)::
40 $ python setup.py install77
4178 tar -xzf ipython.tar.gz
42If you are installing to a location (like ``/usr/local``) that requires higher permissions, you may need to run the last command with :command:`sudo`.79 cd ipython
80 python setup.py install
81
82If you are installing to a location (like ``/usr/local``) that requires higher
83permissions, you may need to run the last command with :command:`sudo`.
4384
44Windows85Windows
45-------86-------
4687
47There are a few caveats for Windows users. The main issue is that a basic ``python setup.py install`` approach won't create ``.bat`` file or Start Menu shortcuts, which most users want. To get an installation with these, there are two choices:88There are a few caveats for Windows users. The main issue is that a basic ``python setup.py install`` approach won't create ``.bat`` file or Start Menu shortcuts, which most users want. To get an installation with these, there are two choices:
4889
491. Install using :command:`easy_install`.90#. Install using :command:`easy_install`.
5091
512. Install using our binary ``.exe`` Windows installer, which can be found at `here <http://ipython.scipy.org/dist/>`_92#. Install using our binary ``.exe`` Windows installer, which can be found at
5293`here <http://ipython.scipy.org/dist/>`_
533. Install from source, but using :mod:`setuptools` (``python setupegg.py install``).94
95#. Install from source, but using :mod:`setuptools` (``python setupegg.py
96 install``).
5497
55Installing the development version98Installing the development version
56----------------------------------99----------------------------------
57100
58It is also possible to install the development version of IPython from our `Bazaar <http://bazaar-vcs.org/>`_ source code101It is also possible to install the development version of IPython from our
59repository. To do this you will need to have Bazaar installed on your system. Then just do::102`Bazaar <http://bazaar-vcs.org/>`_ source code repository. To do this you will
103need to have Bazaar installed on your system. Then just do::
60104
61 $ bzr branch lp:ipython105 bzr branch lp:ipython
62 $ cd ipython106 cd ipython
63 $ python setup.py install107 python setup.py install
64108
65Again, this last step on Windows won't create ``.bat`` files or Start Menu shortcuts, so you will have to use one of the other approaches listed above.109Again, this last step on Windows won't create ``.bat`` files or Start Menu shortcuts, so you will have to use one of the other approaches listed above.
66110
67Some users want to be able to follow the development branch as it changes. If you have :mod:`setuptools` installed, this is easy. Simply replace the last step by::111Some users want to be able to follow the development branch as it changes. If
68112you have :mod:`setuptools` installed, this is easy. Simply replace the last
69 $ python setupegg.py develop113step by::
70114
71This creates links in the right places and installs the command line script to the appropriate places. Then, if you want to update your IPython at any time, just do::115 python setupegg.py develop
72116
73 $ bzr pull117This creates links in the right places and installs the command line script to
74118the appropriate places. Then, if you want to update your IPython at any time,
119just do::
120
121 bzr pull
122
123
75Basic optional dependencies124Basic optional dependencies
76===========================125===========================
77126
@@ -86,17 +135,24 @@
86readline135readline
87--------136--------
88137
89In principle, all Python distributions should come with a working :mod:`readline` module. But, reality is not quite that simple. There are two common situations where you won't have a working :mod:`readline` module:138In principle, all Python distributions should come with a working
139:mod:`readline` module. But, reality is not quite that simple. There are two
140common situations where you won't have a working :mod:`readline` module:
90141
91* If you are using the built-in Python on Mac OS X.142* If you are using the built-in Python on Mac OS X.
92143
93* If you are running Windows, which doesn't have a :mod:`readline` module.144* If you are running Windows, which doesn't have a :mod:`readline` module.
94145
95On OS X, the built-in Python doesn't not have :mod:`readline` because of license issues. Starting with OS X 10.5 (Leopard), Apple's built-in Python has a BSD-licensed not-quite-compatible readline replacement. As of IPython 0.9, many of the issues related to the differences between readline and libedit have been resolved. For many users, libedit may be sufficient.146On OS X, the built-in Python doesn't not have :mod:`readline` because of
96147license issues. Starting with OS X 10.5 (Leopard), Apple's built-in Python has
97Most users on OS X will want to get the full :mod:`readline` module. To get a working :mod:`readline` module, just do (with :mod:`setuptools` installed)::148a BSD-licensed not-quite-compatible readline replacement. As of IPython 0.9,
98149many of the issues related to the differences between readline and libedit have
99 $ easy_install readline150been resolved. For many users, libedit may be sufficient.
151
152Most users on OS X will want to get the full :mod:`readline` module. To get a
153working :mod:`readline` module, just do (with :mod:`setuptools` installed)::
154
155 easy_install readline
100156
101.. note:157.. note:
102158
@@ -104,83 +160,112 @@
104 official python.org binaries) already have readline installed so 160 official python.org binaries) already have readline installed so
105 you don't have to do this step.161 you don't have to do this step.
106162
107If needed, the readline egg can be build and installed from source (see the wiki page at http://ipython.scipy.org/moin/InstallationOSXLeopard).163If needed, the readline egg can be build and installed from source (see the
164wiki page at http://ipython.scipy.org/moin/InstallationOSXLeopard).
108165
109On Windows, you will need the PyReadline module. PyReadline is a separate, Windows only implementation of readline that uses native Windows calls through :mod:`ctypes`. The easiest way of installing PyReadline is you use the binary installer available `here <http://ipython.scipy.org/dist/>`_. The :mod:`ctypes` module, which comes with Python 2.5 and greater, is required by PyReadline. It is available for Python 2.4 at http://python.net/crew/theller/ctypes.166On Windows, you will need the PyReadline module. PyReadline is a separate,
167Windows only implementation of readline that uses native Windows calls through
168:mod:`ctypes`. The easiest way of installing PyReadline is you use the binary
169installer available `here <http://ipython.scipy.org/dist/>`_. The
170:mod:`ctypes` module, which comes with Python 2.5 and greater, is required by
171PyReadline. It is available for Python 2.4 at
172http://python.net/crew/theller/ctypes.
110173
111nose174nose
112----175----
113176
114To run the IPython test suite you will need the :mod:`nose` package. Nose provides a great way of sniffing out and running all of the IPython tests. The simplest way of getting nose, is to use :command:`easy_install`::177To run the IPython test suite you will need the :mod:`nose` package. Nose
178provides a great way of sniffing out and running all of the IPython tests. The
179simplest way of getting nose, is to use :command:`easy_install`::
115180
116 $ easy_install nose181 easy_install nose
117182
118Another way of getting this is to do::183Another way of getting this is to do::
119184
120 $ easy_install IPython[test]185 easy_install IPython[test]
121186
122For more installation options, see the `nose website <http://somethingaboutorange.com/mrl/projects/nose/>`_. Once you have nose installed, you can run IPython's test suite using the iptest command::187For more installation options, see the `nose website
123188<http://somethingaboutorange.com/mrl/projects/nose/>`_. Once you have nose
124 $ iptest189installed, you can run IPython's test suite using the iptest command::
190
191 iptest
125192
126193
127pexpect194pexpect
128-------195-------
129196
130The `pexpect <http://www.noah.org/wiki/Pexpect>`_ package is used in IPython's :command:`irunner` script. On Unix platforms (including OS X), just do::197The `pexpect <http://www.noah.org/wiki/Pexpect>`_ package is used in IPython's
198:command:`irunner` script. On Unix platforms (including OS X), just do::
131199
132 $ easy_install pexpect200 easy_install pexpect
133201
134Windows users are out of luck as pexpect does not run there.202Windows users are out of luck as pexpect does not run there.
135203
136Dependencies for IPython.kernel (parallel computing)204Dependencies for IPython.kernel (parallel computing)
137====================================================205====================================================
138206
139The IPython kernel provides a nice architecture for parallel computing. The main focus of this architecture is on interactive parallel computing. These features require a number of additional packages:207The IPython kernel provides a nice architecture for parallel computing. The
208main focus of this architecture is on interactive parallel computing. These
209features require a number of additional packages:
140210
141* zope.interface (yep, we use interfaces)211* zope.interface (yep, we use interfaces)
142* Twisted (asynchronous networking framework)212* Twisted (asynchronous networking framework)
143* Foolscap (a nice, secure network protocol)213* Foolscap (a nice, secure network protocol)
144* pyOpenSSL (security for network connections)214* pyOpenSSL (security for network connections)
145215
146On a Unix style platform (including OS X), if you want to use :mod:`setuptools`, you can just do::216On a Unix style platform (including OS X), if you want to use
217:mod:`setuptools`, you can just do::
147218
148 $ easy_install IPython[kernel] # the first three219 easy_install IPython[kernel] # the first three
149 $ easy_install IPython[security] # pyOpenSSL220 easy_install IPython[security] # pyOpenSSL
150221
151zope.interface and Twisted222zope.interface and Twisted
152--------------------------223--------------------------
153224
154On Unix style platforms (including OS X), the simplest way of getting the these is to use :command:`easy_install`::225On Unix style platforms (including OS X), the simplest way of getting the these
155226is to use :command:`easy_install`::
156 $ easy_install zope.interface227
157 $ easy_install Twisted228 easy_install zope.interface
158229 easy_install Twisted
159Of course, you can also download the source tarballs from the `Twisted website <twistedmatrix.org>`_ and the `zope.interface page at PyPI <http://pypi.python.org/pypi/zope.interface>`_ and do the usual ``python setup.py install`` if you prefer.230
160231Of course, you can also download the source tarballs from the `Twisted website
161Windows is a bit different. For zope.interface and Twisted, simply get the latest binary ``.exe`` installer from the Twisted website. This installer includes both zope.interface and Twisted and should just work.232<twistedmatrix.org>`_ and the `zope.interface page at PyPI
233<http://pypi.python.org/pypi/zope.interface>`_ and do the usual ``python
234setup.py install`` if you prefer.
235
236Windows is a bit different. For zope.interface and Twisted, simply get the
237latest binary ``.exe`` installer from the Twisted website. This installer
238includes both zope.interface and Twisted and should just work.
162239
163Foolscap240Foolscap
164--------241--------
165242
166Foolscap uses Twisted to provide a very nice secure RPC protocol that we use to implement our parallel computing features.243Foolscap uses Twisted to provide a very nice secure RPC protocol that we use to
244implement our parallel computing features.
167245
168On all platforms a simple::246On all platforms a simple::
169247
170 $ easy_install foolscap248 easy_install foolscap
171249
172should work. You can also download the source tarballs from the `Foolscap website <http://foolscap.lothar.com/trac>`_ and do ``python setup.py install`` if you prefer.250should work. You can also download the source tarballs from the `Foolscap
251website <http://foolscap.lothar.com/trac>`_ and do ``python setup.py install``
252if you prefer.
173253
174pyOpenSSL254pyOpenSSL
175---------255---------
176256
177IPython requires an older version of pyOpenSSL (0.6 rather than the current 0.7). There are a couple of options for getting this:257IPython requires an older version of pyOpenSSL (0.6 rather than the current
1782580.7). There are a couple of options for getting this:
1791. Most Linux distributions have packages for pyOpenSSL.259
1802. The built-in Python 2.5 on OS X 10.5 already has it installed.2601. Most Linux distributions have packages for pyOpenSSL.
1813. There are source tarballs on the pyOpenSSL website. On Unix-like261
182 platforms, these can be built using ``python seutp.py install``.2622. The built-in Python 2.5 on OS X 10.5 already has it installed.
1834. There is also a binary ``.exe`` Windows installer on the `pyOpenSSL website <http://pyopenssl.sourceforge.net/>`_.263
2643. There are source tarballs on the pyOpenSSL website. On Unix-like
265 platforms, these can be built using ``python seutp.py install``.
266
2674. There is also a binary ``.exe`` Windows installer on the `pyOpenSSL website
268 <http://pyopenssl.sourceforge.net/>`_.
184269
185Dependencies for IPython.frontend (the IPython GUI)270Dependencies for IPython.frontend (the IPython GUI)
186===================================================271===================================================
@@ -188,4 +273,9 @@
188wxPython273wxPython
189--------274--------
190275
191Starting with IPython 0.9, IPython has a new IPython.frontend package that has a nice wxPython based IPython GUI. As you would expect, this GUI requires wxPython. Most Linux distributions have wxPython packages available and the built-in Python on OS X comes with wxPython preinstalled. For Windows, a binary installer is available on the `wxPython website <http://www.wxpython.org/>`_.
192\ No newline at end of file276\ No newline at end of file
277Starting with IPython 0.9, IPython has a new IPython.frontend package that has
278a nice wxPython based IPython GUI. As you would expect, this GUI requires
279wxPython. Most Linux distributions have wxPython packages available and the
280built-in Python on OS X comes with wxPython preinstalled. For Windows, a
281binary installer is available on the `wxPython website
282<http://www.wxpython.org/>`_.
193283
=== modified file 'docs/source/interactive/reference.txt'
--- docs/source/interactive/reference.txt 2008-09-13 22:39:42 +0000
+++ docs/source/interactive/reference.txt 2009-03-11 01:24:53 +0000
@@ -496,9 +496,9 @@
496 ip.expose_magic('impall', doimp)496 ip.expose_magic('impall', doimp)
497497
498You can also define your own aliased names for magic functions. In your498You can also define your own aliased names for magic functions. In your
499ipythonrc file, placing a line like:499ipythonrc file, placing a line like::
500500
501execute __IP.magic_cl = __IP.magic_clear501 execute __IP.magic_cl = __IP.magic_clear
502502
503will define %cl as a new name for %clear.503will define %cl as a new name for %clear.
504504
@@ -508,1572 +508,9 @@
508information on the '?' system) to get information about any particular508information on the '?' system) to get information about any particular
509magic function you are interested in.509magic function you are interested in.
510510
511
512Magic commands
513--------------
514
515The rest of this section is automatically generated for each release
516from the docstrings in the IPython code. Therefore the formatting is
517somewhat minimal, but this method has the advantage of having
518information always in sync with the code.
519
520A list of all the magic commands available in IPython's default
521installation follows. This is similar to what you'll see by simply
522typing %magic at the prompt, but that will also give you information
523about magic commands you may have added as part of your personal
524customizations.
525
526.. magic_start
527
528**%Exit**::
529
530 Exit IPython without confirmation.
531
532**%Pprint**::
533
534 Toggle pretty printing on/off.
535
536**%alias**::
537
538 Define an alias for a system command.
539
540 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
541
542 Then, typing 'alias_name params' will execute the system command 'cmd
543 params' (from your underlying operating system).
544
545 Aliases have lower precedence than magic functions and Python normal
546 variables, so if 'foo' is both a Python variable and an alias, the
547 alias can not be executed until 'del foo' removes the Python variable.
548
549 You can use the %l specifier in an alias definition to represent the
550 whole line when the alias is called. For example:
551
552 In [2]: alias all echo "Input in brackets: <%l>"\
553 In [3]: all hello world\
554 Input in brackets: <hello world>
555
556 You can also define aliases with parameters using %s specifiers (one
557 per parameter):
558
559 In [1]: alias parts echo first %s second %s\
560 In [2]: %parts A B\
561 first A second B\
562 In [3]: %parts A\
563 Incorrect number of arguments: 2 expected.\
564 parts is an alias to: 'echo first %s second %s'
565
566 Note that %l and %s are mutually exclusive. You can only use one or
567 the other in your aliases.
568
569 Aliases expand Python variables just like system calls using ! or !!
570 do: all expressions prefixed with '$' get expanded. For details of
571 the semantic rules, see PEP-215:
572 http://www.python.org/peps/pep-0215.html. This is the library used by
573 IPython for variable expansion. If you want to access a true shell
574 variable, an extra $ is necessary to prevent its expansion by IPython:
575
576 In [6]: alias show echo\
577 In [7]: PATH='A Python string'\
578 In [8]: show $PATH\
579 A Python string\
580 In [9]: show $$PATH\
581 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
582
583 You can use the alias facility to acess all of $PATH. See the %rehash
584 and %rehashx functions, which automatically create aliases for the
585 contents of your $PATH.
586
587 If called with no parameters, %alias prints the current alias table.
588
589**%autocall**::
590
591 Make functions callable without having to type parentheses.
592
593 Usage:
594
595 %autocall [mode]
596
597 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
598 value is toggled on and off (remembering the previous state).
599
600 In more detail, these values mean:
601
602 0 -> fully disabled
603
604 1 -> active, but do not apply if there are no arguments on the line.
605
606 In this mode, you get:
607
608 In [1]: callable
609 Out[1]: <built-in function callable>
610
611 In [2]: callable 'hello'
612 ------> callable('hello')
613 Out[2]: False
614
615 2 -> Active always. Even if no arguments are present, the callable
616 object is called:
617
618 In [4]: callable
619 ------> callable()
620
621 Note that even with autocall off, you can still use '/' at the start of
622 a line to treat the first argument on the command line as a function
623 and add parentheses to it:
624
625 In [8]: /str 43
626 ------> str(43)
627 Out[8]: '43'
628
629**%autoindent**::
630
631 Toggle autoindent on/off (if available).
632
633**%automagic**::
634
635 Make magic functions callable without having to type the initial %.
636
637 Without argumentsl toggles on/off (when off, you must call it as
638 %automagic, of course). With arguments it sets the value, and you can
639 use any of (case insensitive):
640
641 - on,1,True: to activate
642
643 - off,0,False: to deactivate.
644
645 Note that magic functions have lowest priority, so if there's a
646 variable whose name collides with that of a magic fn, automagic won't
647 work for that function (you get the variable instead). However, if you
648 delete the variable (del var), the previously shadowed magic function
649 becomes visible to automagic again.
650
651**%bg**::
652
653 Run a job in the background, in a separate thread.
654
655 For example,
656
657 %bg myfunc(x,y,z=1)
658
659 will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the
660 execution starts, a message will be printed indicating the job
661 number. If your job number is 5, you can use
662
663 myvar = jobs.result(5) or myvar = jobs[5].result
664
665 to assign this result to variable 'myvar'.
666
667 IPython has a job manager, accessible via the 'jobs' object. You can
668 type jobs? to get more information about it, and use jobs.<TAB> to see
669 its attributes. All attributes not starting with an underscore are
670 meant for public use.
671
672 In particular, look at the jobs.new() method, which is used to create
673 new jobs. This magic %bg function is just a convenience wrapper
674 around jobs.new(), for expression-based jobs. If you want to create a
675 new job with an explicit function object and arguments, you must call
676 jobs.new() directly.
677
678 The jobs.new docstring also describes in detail several important
679 caveats associated with a thread-based model for background job
680 execution. Type jobs.new? for details.
681
682 You can check the status of all jobs with jobs.status().
683
684 The jobs variable is set by IPython into the Python builtin namespace.
685 If you ever declare a variable named 'jobs', you will shadow this
686 name. You can either delete your global jobs variable to regain
687 access to the job manager, or make a new name and assign it manually
688 to the manager (stored in IPython's namespace). For example, to
689 assign the job manager to the Jobs name, use:
690
691 Jobs = __builtins__.jobs
692
693**%bookmark**::
694
695 Manage IPython's bookmark system.
696
697 %bookmark <name> - set bookmark to current dir
698 %bookmark <name> <dir> - set bookmark to <dir>
699 %bookmark -l - list all bookmarks
700 %bookmark -d <name> - remove bookmark
701 %bookmark -r - remove all bookmarks
702
703 You can later on access a bookmarked folder with:
704 %cd -b <name>
705 or simply '%cd <name>' if there is no directory called <name> AND
706 there is such a bookmark defined.
707
708 Your bookmarks persist through IPython sessions, but they are
709 associated with each profile.
710
711**%cd**::
712
713 Change the current working directory.
714
715 This command automatically maintains an internal list of directories
716 you visit during your IPython session, in the variable _dh. The
717 command %dhist shows this history nicely formatted. You can also
718 do 'cd -<tab>' to see directory history conveniently.
719
720 Usage:
721
722 cd 'dir': changes to directory 'dir'.
723
724 cd -: changes to the last visited directory.
725
726 cd -<n>: changes to the n-th directory in the directory history.
727
728 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
729 (note: cd <bookmark_name> is enough if there is no
730 directory <bookmark_name>, but a bookmark with the name exists.)
731 'cd -b <tab>' allows you to tab-complete bookmark names.
732
733 Options:
734
735 -q: quiet. Do not print the working directory after the cd command is
736 executed. By default IPython's cd command does print this directory,
737 since the default prompts do not display path information.
738
739 Note that !cd doesn't work for this purpose because the shell where
740 !command runs is immediately discarded after executing 'command'.
741
742**%clear**::
743
744 Clear various data (e.g. stored history data)
745
746 %clear out - clear output history
747 %clear in - clear input history
748 %clear shadow_compress - Compresses shadow history (to speed up ipython)
749 %clear shadow_nuke - permanently erase all entries in shadow history
750 %clear dhist - clear dir history
751
752**%color_info**::
753
754 Toggle color_info.
755
756 The color_info configuration parameter controls whether colors are
757 used for displaying object details (by things like %psource, %pfile or
758 the '?' system). This function toggles this value with each call.
759
760 Note that unless you have a fairly recent pager (less works better
761 than more) in your system, using colored object information displays
762 will not work properly. Test it and see.
763
764**%colors**::
765
766 Switch color scheme for prompts, info system and exception handlers.
767
768 Currently implemented schemes: NoColor, Linux, LightBG.
769
770 Color scheme names are not case-sensitive.
771
772**%cpaste**::
773
774 Allows you to paste & execute a pre-formatted code block from clipboard
775
776 You must terminate the block with '--' (two minus-signs) alone on the
777 line. You can also provide your own sentinel with '%paste -s %%' ('%%'
778 is the new sentinel for this operation)
779
780 The block is dedented prior to execution to enable execution of method
781 definitions. '>' and '+' characters at the beginning of a line are
782 ignored, to allow pasting directly from e-mails or diff files. The
783 executed block is also assigned to variable named 'pasted_block' for
784 later editing with '%edit pasted_block'.
785
786 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
787 This assigns the pasted block to variable 'foo' as string, without
788 dedenting or executing it.
789
790 Do not be alarmed by garbled output on Windows (it's a readline bug).
791 Just press enter and type -- (and press enter again) and the block
792 will be what was just pasted.
793
794 IPython statements (magics, shell escapes) are not supported (yet).
795
796**%debug**::
797
798 Activate the interactive debugger in post-mortem mode.
799
800 If an exception has just occurred, this lets you inspect its stack
801 frames interactively. Note that this will always work only on the last
802 traceback that occurred, so you must call this quickly after an
803 exception that you wish to inspect has fired, because if another one
804 occurs, it clobbers the previous one.
805
806 If you want IPython to automatically do this on every exception, see
807 the %pdb magic for more details.
808
809**%dhist**::
810
811 Print your history of visited directories.
812
813 %dhist -> print full history\
814 %dhist n -> print last n entries only\
815 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\
816
817 This history is automatically maintained by the %cd command, and
818 always available as the global list variable _dh. You can use %cd -<n>
819 to go to directory number <n>.
820
821 Note that most of time, you should view directory history by entering
822 cd -<TAB>.
823
824**%dirs**::
825
826 Return the current directory stack.
827
828**%doctest_mode**::
829
830 Toggle doctest mode on and off.
831
832 This mode allows you to toggle the prompt behavior between normal
833 IPython prompts and ones that are as similar to the default IPython
834 interpreter as possible.
835
836 It also supports the pasting of code snippets that have leading '>>>'
837 and '...' prompts in them. This means that you can paste doctests from
838 files or docstrings (even if they have leading whitespace), and the
839 code will execute correctly. You can then use '%history -tn' to see
840 the translated history without line numbers; this will give you the
841 input after removal of all the leading prompts and whitespace, which
842 can be pasted back into an editor.
843
844 With these features, you can switch into this mode easily whenever you
845 need to do testing and changes to doctests, without having to leave
846 your existing IPython session.
847
848**%ed**::
849
850 Alias to %edit.
851
852**%edit**::
853
854 Bring up an editor and execute the resulting code.
855
856 Usage:
857 %edit [options] [args]
858
859 %edit runs IPython's editor hook. The default version of this hook is
860 set to call the __IPYTHON__.rc.editor command. This is read from your
861 environment variable $EDITOR. If this isn't found, it will default to
862 vi under Linux/Unix and to notepad under Windows. See the end of this
863 docstring for how to change the editor hook.
864
865 You can also set the value of this editor via the command line option
866 '-editor' or in your ipythonrc file. This is useful if you wish to use
867 specifically for IPython an editor different from your typical default
868 (and for Windows users who typically don't set environment variables).
869
870 This command allows you to conveniently edit multi-line code right in
871 your IPython session.
872
873 If called without arguments, %edit opens up an empty editor with a
874 temporary file and will execute the contents of this file when you
875 close it (don't forget to save it!).
876
877
878 Options:
879
880 -n <number>: open the editor at a specified line number. By default,
881 the IPython editor hook uses the unix syntax 'editor +N filename', but
882 you can configure this by providing your own modified hook if your
883 favorite editor supports line-number specifications with a different
884 syntax.
885
886 -p: this will call the editor with the same data as the previous time
887 it was used, regardless of how long ago (in your current session) it
888 was.
889
890 -r: use 'raw' input. This option only applies to input taken from the
891 user's history. By default, the 'processed' history is used, so that
892 magics are loaded in their transformed version to valid Python. If
893 this option is given, the raw input as typed as the command line is
894 used instead. When you exit the editor, it will be executed by
895 IPython's own processor.
896
897 -x: do not execute the edited code immediately upon exit. This is
898 mainly useful if you are editing programs which need to be called with
899 command line arguments, which you can then do using %run.
900
901
902 Arguments:
903
904 If arguments are given, the following possibilites exist:
905
906 - The arguments are numbers or pairs of colon-separated numbers (like
907 1 4:8 9). These are interpreted as lines of previous input to be
908 loaded into the editor. The syntax is the same of the %macro command.
909
910 - If the argument doesn't start with a number, it is evaluated as a
911 variable and its contents loaded into the editor. You can thus edit
912 any string which contains python code (including the result of
913 previous edits).
914
915 - If the argument is the name of an object (other than a string),
916 IPython will try to locate the file where it was defined and open the
917 editor at the point where it is defined. You can use `%edit function`
918 to load an editor exactly at the point where 'function' is defined,
919 edit it and have the file be executed automatically.
920
921 If the object is a macro (see %macro for details), this opens up your
922 specified editor with a temporary file containing the macro's data.
923 Upon exit, the macro is reloaded with the contents of the file.
924
925 Note: opening at an exact line is only supported under Unix, and some
926 editors (like kedit and gedit up to Gnome 2.8) do not understand the
927 '+NUMBER' parameter necessary for this feature. Good editors like
928 (X)Emacs, vi, jed, pico and joe all do.
929
930 - If the argument is not found as a variable, IPython will look for a
931 file with that name (adding .py if necessary) and load it into the
932 editor. It will execute its contents with execfile() when you exit,
933 loading any code in the file into your interactive namespace.
934
935 After executing your code, %edit will return as output the code you
936 typed in the editor (except when it was an existing file). This way
937 you can reload the code in further invocations of %edit as a variable,
938 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
939 the output.
940
941 Note that %edit is also available through the alias %ed.
942
943 This is an example of creating a simple function inside the editor and
944 then modifying it. First, start up the editor:
945
946 In [1]: ed\
947 Editing... done. Executing edited code...\
948 Out[1]: 'def foo():\n print "foo() was defined in an editing session"\n'
949
950 We can then call the function foo():
951
952 In [2]: foo()\
953 foo() was defined in an editing session
954
955 Now we edit foo. IPython automatically loads the editor with the
956 (temporary) file where foo() was previously defined:
957
958 In [3]: ed foo\
959 Editing... done. Executing edited code...
960
961 And if we call foo() again we get the modified version:
962
963 In [4]: foo()\
964 foo() has now been changed!
965
966 Here is an example of how to edit a code snippet successive
967 times. First we call the editor:
968
969 In [8]: ed\
970 Editing... done. Executing edited code...\
971 hello\
972 Out[8]: "print 'hello'\n"
973
974 Now we call it again with the previous output (stored in _):
975
976 In [9]: ed _\
977 Editing... done. Executing edited code...\
978 hello world\
979 Out[9]: "print 'hello world'\n"
980
981 Now we call it with the output #8 (stored in _8, also as Out[8]):
982
983 In [10]: ed _8\
984 Editing... done. Executing edited code...\
985 hello again\
986 Out[10]: "print 'hello again'\n"
987
988
989 Changing the default editor hook:
990
991 If you wish to write your own editor hook, you can put it in a
992 configuration file which you load at startup time. The default hook
993 is defined in the IPython.hooks module, and you can use that as a
994 starting example for further modifications. That file also has
995 general instructions on how to set a new hook for use once you've
996 defined it.
997
998**%env**::
999
1000 List environment variables.
1001
1002**%exit**::
1003
1004 Exit IPython, confirming if configured to do so.
1005
1006 You can configure whether IPython asks for confirmation upon exit by
1007 setting the confirm_exit flag in the ipythonrc file.
1008
1009**%hist**::
1010
1011 Alternate name for %history.
1012
1013**%history**::
1014
1015 Print input history (_i<n> variables), with most recent last.
1016
1017 %history -> print at most 40 inputs (some may be multi-line)\
1018 %history n -> print at most n inputs\
1019 %history n1 n2 -> print inputs between n1 and n2 (n2 not included)\
1020
1021 Each input's number <n> is shown, and is accessible as the
1022 automatically generated variable _i<n>. Multi-line statements are
1023 printed starting at a new line for easy copy/paste.
1024
1025
1026 Options:
1027
1028 -n: do NOT print line numbers. This is useful if you want to get a
1029 printout of many lines which can be directly pasted into a text
1030 editor.
1031
1032 This feature is only available if numbered prompts are in use.
1033
1034 -t: (default) print the 'translated' history, as IPython understands it.
1035 IPython filters your input and converts it all into valid Python source
1036 before executing it (things like magics or aliases are turned into
1037 function calls, for example). With this option, you'll see the native
1038 history instead of the user-entered version: '%cd /' will be seen as
1039 '_ip.magic("%cd /")' instead of '%cd /'.
1040
1041 -r: print the 'raw' history, i.e. the actual commands you typed.
1042
1043 -g: treat the arg as a pattern to grep for in (full) history.
1044 This includes the "shadow history" (almost all commands ever written).
1045 Use '%hist -g' to show full shadow history (may be very long).
1046 In shadow history, every index nuwber starts with 0.
1047
1048 -f FILENAME: instead of printing the output to the screen, redirect it to
1049 the given file. The file is always overwritten, though IPython asks for
1050 confirmation first if it already exists.
1051
1052**%logoff**::
1053
1054 Temporarily stop logging.
1055
1056 You must have previously started logging.
1057
1058**%logon**::
1059
1060 Restart logging.
1061
1062 This function is for restarting logging which you've temporarily
1063 stopped with %logoff. For starting logging for the first time, you
1064 must use the %logstart function, which allows you to specify an
1065 optional log filename.
1066
1067**%logstart**::
1068
1069 Start logging anywhere in a session.
1070
1071 %logstart [-o|-r|-t] [log_name [log_mode]]
1072
1073 If no name is given, it defaults to a file named 'ipython_log.py' in your
1074 current directory, in 'rotate' mode (see below).
1075
1076 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
1077 history up to that point and then continues logging.
1078
1079 %logstart takes a second optional parameter: logging mode. This can be one
1080 of (note that the modes are given unquoted):\
1081 append: well, that says it.\
1082 backup: rename (if exists) to name~ and start name.\
1083 global: single logfile in your home dir, appended to.\
1084 over : overwrite existing log.\
1085 rotate: create rotating logs name.1~, name.2~, etc.
1086
1087 Options:
1088
1089 -o: log also IPython's output. In this mode, all commands which
1090 generate an Out[NN] prompt are recorded to the logfile, right after
1091 their corresponding input line. The output lines are always
1092 prepended with a '#[Out]# ' marker, so that the log remains valid
1093 Python code.
1094
1095 Since this marker is always the same, filtering only the output from
1096 a log is very easy, using for example a simple awk call:
1097
1098 awk -F'#\[Out\]# ' '{if($2) {print $2}}' ipython_log.py
1099
1100 -r: log 'raw' input. Normally, IPython's logs contain the processed
1101 input, so that user lines are logged in their final form, converted
1102 into valid Python. For example, %Exit is logged as
1103 '_ip.magic("Exit"). If the -r flag is given, all input is logged
1104 exactly as typed, with no transformations applied.
1105
1106 -t: put timestamps before each input line logged (these are put in
1107 comments).
1108
1109**%logstate**::
1110
1111 Print the status of the logging system.
1112
1113**%logstop**::
1114
1115 Fully stop logging and close log file.
1116
1117 In order to start logging again, a new %logstart call needs to be made,
1118 possibly (though not necessarily) with a new filename, mode and other
1119 options.
1120
1121**%lsmagic**::
1122
1123 List currently available magic functions.
1124
1125**%macro**::
1126
1127 Define a set of input lines as a macro for future re-execution.
1128
1129 Usage:\
1130 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1131
1132 Options:
1133
1134 -r: use 'raw' input. By default, the 'processed' history is used,
1135 so that magics are loaded in their transformed version to valid
1136 Python. If this option is given, the raw input as typed as the
1137 command line is used instead.
1138
1139 This will define a global variable called `name` which is a string
1140 made of joining the slices and lines you specify (n1,n2,... numbers
1141 above) from your input history into a single string. This variable
1142 acts like an automatic function which re-executes those lines as if
1143 you had typed them. You just type 'name' at the prompt and the code
1144 executes.
1145
1146 The notation for indicating number ranges is: n1-n2 means 'use line
1147 numbers n1,...n2' (the endpoint is included). That is, '5-7' means
1148 using the lines numbered 5,6 and 7.
1149
1150 Note: as a 'hidden' feature, you can also use traditional python slice
1151 notation, where N:M means numbers N through M-1.
1152
1153 For example, if your history contains (%hist prints it):
1154
1155 44: x=1\
1156 45: y=3\
1157 46: z=x+y\
1158 47: print x\
1159 48: a=5\
1160 49: print 'x',x,'y',y\
1161
1162 you can create a macro with lines 44 through 47 (included) and line 49
1163 called my_macro with:
1164
1165 In [51]: %macro my_macro 44-47 49
1166
1167 Now, typing `my_macro` (without quotes) will re-execute all this code
1168 in one pass.
1169
1170 You don't need to give the line-numbers in order, and any given line
1171 number can appear multiple times. You can assemble macros with any
1172 lines from your input history in any order.
1173
1174 The macro is a simple object which holds its value in an attribute,
1175 but IPython's display system checks for macros and executes them as
1176 code instead of printing them when you type their name.
1177
1178 You can view a macro's contents by explicitly printing it with:
1179
1180 'print macro_name'.
1181
1182 For one-off cases which DON'T contain magic function calls in them you
1183 can obtain similar results by explicitly executing slices from your
1184 input history with:
1185
1186 In [60]: exec In[44:48]+In[49]
1187
1188**%magic**::
1189
1190 Print information about the magic function system.
1191
1192**%mglob**::
1193
1194 This program allows specifying filenames with "mglob" mechanism.
1195 Supported syntax in globs (wilcard matching patterns)::
1196
1197 *.cpp ?ellowo*
1198 - obvious. Differs from normal glob in that dirs are not included.
1199 Unix users might want to write this as: "*.cpp" "?ellowo*"
1200 rec:/usr/share=*.txt,*.doc
1201 - get all *.txt and *.doc under /usr/share,
1202 recursively
1203 rec:/usr/share
1204 - All files under /usr/share, recursively
1205 rec:*.py
1206 - All .py files under current working dir, recursively
1207 foo
1208 - File or dir foo
1209 !*.bak readme*
1210 - readme*, exclude files ending with .bak
1211 !.svn/ !.hg/ !*_Data/ rec:.
1212 - Skip .svn, .hg, foo_Data dirs (and their subdirs) in recurse.
1213 Trailing / is the key, \ does not work!
1214 dir:foo
1215 - the directory foo if it exists (not files in foo)
1216 dir:*
1217 - all directories in current folder
1218 foo.py bar.* !h* rec:*.py
1219 - Obvious. !h* exclusion only applies for rec:*.py.
1220 foo.py is *not* included twice.
1221 @filelist.txt
1222 - All files listed in 'filelist.txt' file, on separate lines.
1223
1224**%page**::
1225
1226 Pretty print the object and display it through a pager.
1227
1228 %page [options] OBJECT
1229
1230 If no object is given, use _ (last output).
1231
1232 Options:
1233
1234 -r: page str(object), don't pretty-print it.
1235
1236**%pdb**::
1237
1238 Control the automatic calling of the pdb interactive debugger.
1239
1240 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1241 argument it works as a toggle.
1242
1243 When an exception is triggered, IPython can optionally call the
1244 interactive pdb debugger after the traceback printout. %pdb toggles
1245 this feature on and off.
1246
1247 The initial state of this feature is set in your ipythonrc
1248 configuration file (the variable is called 'pdb').
1249
1250 If you want to just activate the debugger AFTER an exception has fired,
1251 without having to type '%pdb on' and rerunning your code, you can use
1252 the %debug magic.
1253
1254**%pdef**::
1255
1256 Print the definition header for any callable object.
1257
1258 If the object is a class, print the constructor information.
1259
1260**%pdoc**::
1261
1262 Print the docstring for an object.
1263
1264 If the given object is a class, it will print both the class and the
1265 constructor docstrings.
1266
1267**%pfile**::
1268
1269 Print (or run through pager) the file where an object is defined.
1270
1271 The file opens at the line where the object definition begins. IPython
1272 will honor the environment variable PAGER if set, and otherwise will
1273 do its best to print the file in a convenient form.
1274
1275 If the given argument is not an object currently defined, IPython will
1276 try to interpret it as a filename (automatically adding a .py extension
1277 if needed). You can thus use %pfile as a syntax highlighting code
1278 viewer.
1279
1280**%pinfo**::
1281
1282 Provide detailed information about an object.
1283
1284 '%pinfo object' is just a synonym for object? or ?object.
1285
1286**%popd**::
1287
1288 Change to directory popped off the top of the stack.
1289
1290**%profile**::
1291
1292 Print your currently active IPyhton profile.
1293
1294**%prun**::
1295
1296 Run a statement through the python code profiler.
1297
1298 Usage:\
1299 %prun [options] statement
1300
1301 The given statement (which doesn't require quote marks) is run via the
1302 python profiler in a manner similar to the profile.run() function.
1303 Namespaces are internally managed to work correctly; profile.run
1304 cannot be used in IPython because it makes certain assumptions about
1305 namespaces which do not hold under IPython.
1306
1307 Options:
1308
1309 -l <limit>: you can place restrictions on what or how much of the
1310 profile gets printed. The limit value can be:
1311
1312 * A string: only information for function names containing this string
1313 is printed.
1314
1315 * An integer: only these many lines are printed.
1316
1317 * A float (between 0 and 1): this fraction of the report is printed
1318 (for example, use a limit of 0.4 to see the topmost 40% only).
1319
1320 You can combine several limits with repeated use of the option. For
1321 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1322 information about class constructors.
1323
1324 -r: return the pstats.Stats object generated by the profiling. This
1325 object has all the information about the profile in it, and you can
1326 later use it for further analysis or in other functions.
1327
1328 -s <key>: sort profile by given key. You can provide more than one key
1329 by using the option several times: '-s key1 -s key2 -s key3...'. The
1330 default sorting key is 'time'.
1331
1332 The following is copied verbatim from the profile documentation
1333 referenced below:
1334
1335 When more than one key is provided, additional keys are used as
1336 secondary criteria when the there is equality in all keys selected
1337 before them.
1338
1339 Abbreviations can be used for any key names, as long as the
1340 abbreviation is unambiguous. The following are the keys currently
1341 defined:
1342
1343 Valid Arg Meaning\
1344 "calls" call count\
The diff has been truncated for viewing.

Subscribers

People subscribed via source and target branches