Show More
@@ -1,73 +1,73 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 | """ |
|
2 | """ | |
3 | IPython -- An enhanced Interactive Python |
|
3 | IPython -- An enhanced Interactive Python | |
4 |
|
4 | |||
5 | One of Python's nicest features is its interactive interpreter. This allows |
|
5 | One of Python's nicest features is its interactive interpreter. This allows | |
6 | very fast testing of ideas without the overhead of creating test files as is |
|
6 | very fast testing of ideas without the overhead of creating test files as is | |
7 | typical in most programming languages. However, the interpreter supplied with |
|
7 | typical in most programming languages. However, the interpreter supplied with | |
8 | the standard Python distribution is fairly primitive (and IDLE isn't really |
|
8 | the standard Python distribution is fairly primitive (and IDLE isn't really | |
9 | much better). |
|
9 | much better). | |
10 |
|
10 | |||
11 | IPython tries to: |
|
11 | IPython tries to: | |
12 |
|
12 | |||
13 | i - provide an efficient environment for interactive work in Python |
|
13 | i - provide an efficient environment for interactive work in Python | |
14 | programming. It tries to address what we see as shortcomings of the standard |
|
14 | programming. It tries to address what we see as shortcomings of the standard | |
15 | Python prompt, and adds many features to make interactive work much more |
|
15 | Python prompt, and adds many features to make interactive work much more | |
16 | efficient. |
|
16 | efficient. | |
17 |
|
17 | |||
18 | ii - offer a flexible framework so that it can be used as the base |
|
18 | ii - offer a flexible framework so that it can be used as the base | |
19 | environment for other projects and problems where Python can be the |
|
19 | environment for other projects and problems where Python can be the | |
20 | underlying language. Specifically scientific environments like Mathematica, |
|
20 | underlying language. Specifically scientific environments like Mathematica, | |
21 | IDL and Mathcad inspired its design, but similar ideas can be useful in many |
|
21 | IDL and Mathcad inspired its design, but similar ideas can be useful in many | |
22 | fields. Python is a fabulous language for implementing this kind of system |
|
22 | fields. Python is a fabulous language for implementing this kind of system | |
23 | (due to its dynamic and introspective features), and with suitable libraries |
|
23 | (due to its dynamic and introspective features), and with suitable libraries | |
24 | entire systems could be built leveraging Python's power. |
|
24 | entire systems could be built leveraging Python's power. | |
25 |
|
25 | |||
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. | |
27 |
|
27 | |||
28 | IPython requires Python 2.4 or newer. |
|
28 | IPython requires Python 2.4 or newer. | |
29 | """ |
|
29 | """ | |
30 |
|
30 | |||
31 | #***************************************************************************** |
|
31 | #***************************************************************************** | |
32 | # Copyright (C) 2008-2009 The IPython Development Team |
|
32 | # Copyright (C) 2008-2009 The IPython Development Team | |
33 | # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu> |
|
33 | # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu> | |
34 | # |
|
34 | # | |
35 | # Distributed under the terms of the BSD License. The full license is in |
|
35 | # Distributed under the terms of the BSD License. The full license is in | |
36 | # the file COPYING, distributed as part of this software. |
|
36 | # the file COPYING, distributed as part of this software. | |
37 | #***************************************************************************** |
|
37 | #***************************************************************************** | |
38 |
|
38 | |||
39 | # Enforce proper version requirements |
|
39 | # Enforce proper version requirements | |
40 | import sys |
|
40 | import sys | |
41 |
|
41 | |||
42 | if sys.version[0:3] < '2.4': |
|
42 | if sys.version[0:3] < '2.4': | |
43 | raise ImportError('Python Version 2.4 or above is required for IPython.') |
|
43 | raise ImportError('Python Version 2.4 or above is required for IPython.') | |
44 |
|
44 | |||
45 | # Make it easy to import extensions - they are always directly on pythonpath. |
|
45 | # Make it easy to import extensions - they are always directly on pythonpath. | |
46 | # Therefore, non-IPython modules can be added to Extensions directory |
|
46 | # Therefore, non-IPython modules can be added to Extensions directory | |
47 | import os |
|
47 | import os | |
48 | sys.path.append(os.path.dirname(__file__) + "/Extensions") |
|
48 | sys.path.append(os.path.dirname(__file__) + "/Extensions") | |
49 |
|
49 | |||
50 | # Define what gets imported with a 'from IPython import *' |
|
50 | # Define what gets imported with a 'from IPython import *' | |
51 | __all__ = ['IPython.core.ipapi','utils.generics','utils.ipstruct', |
|
51 | __all__ = ['IPython.core.ipapi','utils.generics','utils.ipstruct', | |
52 |
'core.release',' |
|
52 | 'core.release','core.shell'] | |
53 |
|
53 | |||
54 | # Load __all__ in IPython namespace so that a simple 'import IPython' gives |
|
54 | # Load __all__ in IPython namespace so that a simple 'import IPython' gives | |
55 | # access to them via IPython.<name> |
|
55 | # access to them via IPython.<name> | |
56 | glob,loc = globals(),locals() |
|
56 | glob,loc = globals(),locals() | |
57 | for name in __all__: |
|
57 | for name in __all__: | |
58 | #print 'Importing: ',name # dbg |
|
58 | #print 'Importing: ',name # dbg | |
59 | __import__(name,glob,loc,[]) |
|
59 | __import__(name,glob,loc,[]) | |
60 |
|
60 | |||
61 | import Shell |
|
61 | from IPython.core import shell | |
62 |
|
62 | |||
63 | # Release data |
|
63 | # Release data | |
64 | from IPython.core import release # do it explicitly so pydoc can see it - pydoc bug |
|
64 | from IPython.core import release # do it explicitly so pydoc can see it - pydoc bug | |
65 | __author__ = '%s <%s>\n%s <%s>\n%s <%s>' % \ |
|
65 | __author__ = '%s <%s>\n%s <%s>\n%s <%s>' % \ | |
66 | ( release.authors['Fernando'] + release.authors['Janko'] + \ |
|
66 | ( release.authors['Fernando'] + release.authors['Janko'] + \ | |
67 | release.authors['Nathan'] ) |
|
67 | release.authors['Nathan'] ) | |
68 | __license__ = release.license |
|
68 | __license__ = release.license | |
69 | __version__ = release.version |
|
69 | __version__ = release.version | |
70 | __revision__ = release.revision |
|
70 | __revision__ = release.revision | |
71 |
|
71 | |||
72 | # Namespace cleanup |
|
72 | # Namespace cleanup | |
73 | del name,glob,loc |
|
73 | del name,glob,loc |
@@ -1,685 +1,685 b'' | |||||
1 | """IPython customization API |
|
1 | """IPython customization API | |
2 |
|
2 | |||
3 | Your one-stop module for configuring & extending ipython |
|
3 | Your one-stop module for configuring & extending ipython | |
4 |
|
4 | |||
5 | The API will probably break when ipython 1.0 is released, but so |
|
5 | The API will probably break when ipython 1.0 is released, but so | |
6 | will the other configuration method (rc files). |
|
6 | will the other configuration method (rc files). | |
7 |
|
7 | |||
8 | All names prefixed by underscores are for internal use, not part |
|
8 | All names prefixed by underscores are for internal use, not part | |
9 | of the public api. |
|
9 | of the public api. | |
10 |
|
10 | |||
11 | Below is an example that you can just put to a module and import from ipython. |
|
11 | Below is an example that you can just put to a module and import from ipython. | |
12 |
|
12 | |||
13 | A good practice is to install the config script below as e.g. |
|
13 | A good practice is to install the config script below as e.g. | |
14 |
|
14 | |||
15 | ~/.ipython/my_private_conf.py |
|
15 | ~/.ipython/my_private_conf.py | |
16 |
|
16 | |||
17 | And do |
|
17 | And do | |
18 |
|
18 | |||
19 | import_mod my_private_conf |
|
19 | import_mod my_private_conf | |
20 |
|
20 | |||
21 | in ~/.ipython/ipythonrc |
|
21 | in ~/.ipython/ipythonrc | |
22 |
|
22 | |||
23 | That way the module is imported at startup and you can have all your |
|
23 | That way the module is imported at startup and you can have all your | |
24 | personal configuration (as opposed to boilerplate ipythonrc-PROFILENAME |
|
24 | personal configuration (as opposed to boilerplate ipythonrc-PROFILENAME | |
25 | stuff) in there. |
|
25 | stuff) in there. | |
26 |
|
26 | |||
27 | from IPython.core import ipapi |
|
27 | from IPython.core import ipapi | |
28 | ip = ipapi.get() |
|
28 | ip = ipapi.get() | |
29 |
|
29 | |||
30 | def ankka_f(self, arg): |
|
30 | def ankka_f(self, arg): | |
31 | print 'Ankka',self,'says uppercase:',arg.upper() |
|
31 | print 'Ankka',self,'says uppercase:',arg.upper() | |
32 |
|
32 | |||
33 | ip.expose_magic('ankka',ankka_f) |
|
33 | ip.expose_magic('ankka',ankka_f) | |
34 |
|
34 | |||
35 | ip.magic('alias sayhi echo "Testing, hi ok"') |
|
35 | ip.magic('alias sayhi echo "Testing, hi ok"') | |
36 | ip.magic('alias helloworld echo "Hello world"') |
|
36 | ip.magic('alias helloworld echo "Hello world"') | |
37 | ip.system('pwd') |
|
37 | ip.system('pwd') | |
38 |
|
38 | |||
39 | ip.ex('import re') |
|
39 | ip.ex('import re') | |
40 | ip.ex(''' |
|
40 | ip.ex(''' | |
41 | def funcci(a,b): |
|
41 | def funcci(a,b): | |
42 | print a+b |
|
42 | print a+b | |
43 | print funcci(3,4) |
|
43 | print funcci(3,4) | |
44 | ''') |
|
44 | ''') | |
45 | ip.ex('funcci(348,9)') |
|
45 | ip.ex('funcci(348,9)') | |
46 |
|
46 | |||
47 | def jed_editor(self,filename, linenum=None): |
|
47 | def jed_editor(self,filename, linenum=None): | |
48 | print 'Calling my own editor, jed ... via hook!' |
|
48 | print 'Calling my own editor, jed ... via hook!' | |
49 | import os |
|
49 | import os | |
50 | if linenum is None: linenum = 0 |
|
50 | if linenum is None: linenum = 0 | |
51 | os.system('jed +%d %s' % (linenum, filename)) |
|
51 | os.system('jed +%d %s' % (linenum, filename)) | |
52 | print 'exiting jed' |
|
52 | print 'exiting jed' | |
53 |
|
53 | |||
54 | ip.set_hook('editor',jed_editor) |
|
54 | ip.set_hook('editor',jed_editor) | |
55 |
|
55 | |||
56 | o = ip.options |
|
56 | o = ip.options | |
57 | o.autocall = 2 # FULL autocall mode |
|
57 | o.autocall = 2 # FULL autocall mode | |
58 |
|
58 | |||
59 | print 'done!' |
|
59 | print 'done!' | |
60 | """ |
|
60 | """ | |
61 |
|
61 | |||
62 | #----------------------------------------------------------------------------- |
|
62 | #----------------------------------------------------------------------------- | |
63 | # Modules and globals |
|
63 | # Modules and globals | |
64 |
|
64 | |||
65 | # stdlib imports |
|
65 | # stdlib imports | |
66 | import __builtin__ |
|
66 | import __builtin__ | |
67 | import sys |
|
67 | import sys | |
68 |
|
68 | |||
69 | # contains the most recently instantiated IPApi |
|
69 | # contains the most recently instantiated IPApi | |
70 | _RECENT_IP = None |
|
70 | _RECENT_IP = None | |
71 |
|
71 | |||
72 | #----------------------------------------------------------------------------- |
|
72 | #----------------------------------------------------------------------------- | |
73 | # Code begins |
|
73 | # Code begins | |
74 |
|
74 | |||
75 | class TryNext(Exception): |
|
75 | class TryNext(Exception): | |
76 | """Try next hook exception. |
|
76 | """Try next hook exception. | |
77 |
|
77 | |||
78 | Raise this in your hook function to indicate that the next hook handler |
|
78 | Raise this in your hook function to indicate that the next hook handler | |
79 | should be used to handle the operation. If you pass arguments to the |
|
79 | should be used to handle the operation. If you pass arguments to the | |
80 | constructor those arguments will be used by the next hook instead of the |
|
80 | constructor those arguments will be used by the next hook instead of the | |
81 | original ones. |
|
81 | original ones. | |
82 | """ |
|
82 | """ | |
83 |
|
83 | |||
84 | def __init__(self, *args, **kwargs): |
|
84 | def __init__(self, *args, **kwargs): | |
85 | self.args = args |
|
85 | self.args = args | |
86 | self.kwargs = kwargs |
|
86 | self.kwargs = kwargs | |
87 |
|
87 | |||
88 |
|
88 | |||
89 | class UsageError(Exception): |
|
89 | class UsageError(Exception): | |
90 | """ Error in magic function arguments, etc. |
|
90 | """ Error in magic function arguments, etc. | |
91 |
|
91 | |||
92 | Something that probably won't warrant a full traceback, but should |
|
92 | Something that probably won't warrant a full traceback, but should | |
93 | nevertheless interrupt a macro / batch file. |
|
93 | nevertheless interrupt a macro / batch file. | |
94 | """ |
|
94 | """ | |
95 |
|
95 | |||
96 |
|
96 | |||
97 | class IPyAutocall: |
|
97 | class IPyAutocall: | |
98 | """ Instances of this class are always autocalled |
|
98 | """ Instances of this class are always autocalled | |
99 |
|
99 | |||
100 | This happens regardless of 'autocall' variable state. Use this to |
|
100 | This happens regardless of 'autocall' variable state. Use this to | |
101 | develop macro-like mechanisms. |
|
101 | develop macro-like mechanisms. | |
102 | """ |
|
102 | """ | |
103 |
|
103 | |||
104 | def set_ip(self,ip): |
|
104 | def set_ip(self,ip): | |
105 | """ Will be used to set _ip point to current ipython instance b/f call |
|
105 | """ Will be used to set _ip point to current ipython instance b/f call | |
106 |
|
106 | |||
107 | Override this method if you don't want this to happen. |
|
107 | Override this method if you don't want this to happen. | |
108 |
|
108 | |||
109 | """ |
|
109 | """ | |
110 | self._ip = ip |
|
110 | self._ip = ip | |
111 |
|
111 | |||
112 |
|
112 | |||
113 | class IPythonNotRunning: |
|
113 | class IPythonNotRunning: | |
114 | """Dummy do-nothing class. |
|
114 | """Dummy do-nothing class. | |
115 |
|
115 | |||
116 | Instances of this class return a dummy attribute on all accesses, which |
|
116 | Instances of this class return a dummy attribute on all accesses, which | |
117 | can be called and warns. This makes it easier to write scripts which use |
|
117 | can be called and warns. This makes it easier to write scripts which use | |
118 | the ipapi.get() object for informational purposes to operate both with and |
|
118 | the ipapi.get() object for informational purposes to operate both with and | |
119 | without ipython. Obviously code which uses the ipython object for |
|
119 | without ipython. Obviously code which uses the ipython object for | |
120 | computations will not work, but this allows a wider range of code to |
|
120 | computations will not work, but this allows a wider range of code to | |
121 | transparently work whether ipython is being used or not.""" |
|
121 | transparently work whether ipython is being used or not.""" | |
122 |
|
122 | |||
123 | def __init__(self,warn=True): |
|
123 | def __init__(self,warn=True): | |
124 | if warn: |
|
124 | if warn: | |
125 | self.dummy = self._dummy_warn |
|
125 | self.dummy = self._dummy_warn | |
126 | else: |
|
126 | else: | |
127 | self.dummy = self._dummy_silent |
|
127 | self.dummy = self._dummy_silent | |
128 |
|
128 | |||
129 | def __str__(self): |
|
129 | def __str__(self): | |
130 | return "<IPythonNotRunning>" |
|
130 | return "<IPythonNotRunning>" | |
131 |
|
131 | |||
132 | __repr__ = __str__ |
|
132 | __repr__ = __str__ | |
133 |
|
133 | |||
134 | def __getattr__(self,name): |
|
134 | def __getattr__(self,name): | |
135 | return self.dummy |
|
135 | return self.dummy | |
136 |
|
136 | |||
137 | def _dummy_warn(self,*args,**kw): |
|
137 | def _dummy_warn(self,*args,**kw): | |
138 | """Dummy function, which doesn't do anything but warn.""" |
|
138 | """Dummy function, which doesn't do anything but warn.""" | |
139 |
|
139 | |||
140 | print ("IPython is not running, this is a dummy no-op function") |
|
140 | print ("IPython is not running, this is a dummy no-op function") | |
141 |
|
141 | |||
142 | def _dummy_silent(self,*args,**kw): |
|
142 | def _dummy_silent(self,*args,**kw): | |
143 | """Dummy function, which doesn't do anything and emits no warnings.""" |
|
143 | """Dummy function, which doesn't do anything and emits no warnings.""" | |
144 | pass |
|
144 | pass | |
145 |
|
145 | |||
146 |
|
146 | |||
147 | def get(allow_dummy=False,dummy_warn=True): |
|
147 | def get(allow_dummy=False,dummy_warn=True): | |
148 | """Get an IPApi object. |
|
148 | """Get an IPApi object. | |
149 |
|
149 | |||
150 | If allow_dummy is true, returns an instance of IPythonNotRunning |
|
150 | If allow_dummy is true, returns an instance of IPythonNotRunning | |
151 | instead of None if not running under IPython. |
|
151 | instead of None if not running under IPython. | |
152 |
|
152 | |||
153 | If dummy_warn is false, the dummy instance will be completely silent. |
|
153 | If dummy_warn is false, the dummy instance will be completely silent. | |
154 |
|
154 | |||
155 | Running this should be the first thing you do when writing extensions that |
|
155 | Running this should be the first thing you do when writing extensions that | |
156 | can be imported as normal modules. You can then direct all the |
|
156 | can be imported as normal modules. You can then direct all the | |
157 | configuration operations against the returned object. |
|
157 | configuration operations against the returned object. | |
158 | """ |
|
158 | """ | |
159 | global _RECENT_IP |
|
159 | global _RECENT_IP | |
160 | if allow_dummy and not _RECENT_IP: |
|
160 | if allow_dummy and not _RECENT_IP: | |
161 | _RECENT_IP = IPythonNotRunning(dummy_warn) |
|
161 | _RECENT_IP = IPythonNotRunning(dummy_warn) | |
162 | return _RECENT_IP |
|
162 | return _RECENT_IP | |
163 |
|
163 | |||
164 |
|
164 | |||
165 | class IPApi(object): |
|
165 | class IPApi(object): | |
166 | """ The actual API class for configuring IPython |
|
166 | """ The actual API class for configuring IPython | |
167 |
|
167 | |||
168 | You should do all of the IPython configuration by getting an IPApi object |
|
168 | You should do all of the IPython configuration by getting an IPApi object | |
169 | with IPython.ipapi.get() and using the attributes and methods of the |
|
169 | with IPython.ipapi.get() and using the attributes and methods of the | |
170 | returned object.""" |
|
170 | returned object.""" | |
171 |
|
171 | |||
172 | def __init__(self,ip): |
|
172 | def __init__(self,ip): | |
173 |
|
173 | |||
174 | global _RECENT_IP |
|
174 | global _RECENT_IP | |
175 |
|
175 | |||
176 | # All attributes exposed here are considered to be the public API of |
|
176 | # All attributes exposed here are considered to be the public API of | |
177 | # IPython. As needs dictate, some of these may be wrapped as |
|
177 | # IPython. As needs dictate, some of these may be wrapped as | |
178 | # properties. |
|
178 | # properties. | |
179 |
|
179 | |||
180 | self.magic = ip.ipmagic |
|
180 | self.magic = ip.ipmagic | |
181 |
|
181 | |||
182 | self.system = ip.system |
|
182 | self.system = ip.system | |
183 |
|
183 | |||
184 | self.set_hook = ip.set_hook |
|
184 | self.set_hook = ip.set_hook | |
185 |
|
185 | |||
186 | self.set_custom_exc = ip.set_custom_exc |
|
186 | self.set_custom_exc = ip.set_custom_exc | |
187 |
|
187 | |||
188 | self.user_ns = ip.user_ns |
|
188 | self.user_ns = ip.user_ns | |
189 |
|
189 | |||
190 | self.set_crash_handler = ip.set_crash_handler |
|
190 | self.set_crash_handler = ip.set_crash_handler | |
191 |
|
191 | |||
192 | # Session-specific data store, which can be used to store |
|
192 | # Session-specific data store, which can be used to store | |
193 | # data that should persist through the ipython session. |
|
193 | # data that should persist through the ipython session. | |
194 | self.meta = ip.meta |
|
194 | self.meta = ip.meta | |
195 |
|
195 | |||
196 | # The ipython instance provided |
|
196 | # The ipython instance provided | |
197 | self.IP = ip |
|
197 | self.IP = ip | |
198 |
|
198 | |||
199 | self.extensions = {} |
|
199 | self.extensions = {} | |
200 |
|
200 | |||
201 | self.dbg = DebugTools(self) |
|
201 | self.dbg = DebugTools(self) | |
202 |
|
202 | |||
203 | _RECENT_IP = self |
|
203 | _RECENT_IP = self | |
204 |
|
204 | |||
205 | # Use a property for some things which are added to the instance very |
|
205 | # Use a property for some things which are added to the instance very | |
206 | # late. I don't have time right now to disentangle the initialization |
|
206 | # late. I don't have time right now to disentangle the initialization | |
207 | # order issues, so a property lets us delay item extraction while |
|
207 | # order issues, so a property lets us delay item extraction while | |
208 | # providing a normal attribute API. |
|
208 | # providing a normal attribute API. | |
209 | def get_db(self): |
|
209 | def get_db(self): | |
210 | """A handle to persistent dict-like database (a PickleShareDB object)""" |
|
210 | """A handle to persistent dict-like database (a PickleShareDB object)""" | |
211 | return self.IP.db |
|
211 | return self.IP.db | |
212 |
|
212 | |||
213 | db = property(get_db,None,None,get_db.__doc__) |
|
213 | db = property(get_db,None,None,get_db.__doc__) | |
214 |
|
214 | |||
215 | def get_options(self): |
|
215 | def get_options(self): | |
216 | """All configurable variables.""" |
|
216 | """All configurable variables.""" | |
217 |
|
217 | |||
218 | # catch typos by disabling new attribute creation. If new attr creation |
|
218 | # catch typos by disabling new attribute creation. If new attr creation | |
219 | # is in fact wanted (e.g. when exposing new options), do |
|
219 | # is in fact wanted (e.g. when exposing new options), do | |
220 | # allow_new_attr(True) for the received rc struct. |
|
220 | # allow_new_attr(True) for the received rc struct. | |
221 |
|
221 | |||
222 | self.IP.rc.allow_new_attr(False) |
|
222 | self.IP.rc.allow_new_attr(False) | |
223 | return self.IP.rc |
|
223 | return self.IP.rc | |
224 |
|
224 | |||
225 | options = property(get_options,None,None,get_options.__doc__) |
|
225 | options = property(get_options,None,None,get_options.__doc__) | |
226 |
|
226 | |||
227 | def expose_magic(self,magicname, func): |
|
227 | def expose_magic(self,magicname, func): | |
228 | """Expose own function as magic function for ipython |
|
228 | """Expose own function as magic function for ipython | |
229 |
|
229 | |||
230 | def foo_impl(self,parameter_s=''): |
|
230 | def foo_impl(self,parameter_s=''): | |
231 | 'My very own magic!. (Use docstrings, IPython reads them).' |
|
231 | 'My very own magic!. (Use docstrings, IPython reads them).' | |
232 | print 'Magic function. Passed parameter is between < >:' |
|
232 | print 'Magic function. Passed parameter is between < >:' | |
233 | print '<%s>' % parameter_s |
|
233 | print '<%s>' % parameter_s | |
234 | print 'The self object is:',self |
|
234 | print 'The self object is:',self | |
235 |
|
235 | |||
236 | ipapi.expose_magic('foo',foo_impl) |
|
236 | ipapi.expose_magic('foo',foo_impl) | |
237 | """ |
|
237 | """ | |
238 |
|
238 | |||
239 | import new |
|
239 | import new | |
240 | im = new.instancemethod(func,self.IP, self.IP.__class__) |
|
240 | im = new.instancemethod(func,self.IP, self.IP.__class__) | |
241 | old = getattr(self.IP, "magic_" + magicname, None) |
|
241 | old = getattr(self.IP, "magic_" + magicname, None) | |
242 | if old: |
|
242 | if old: | |
243 | self.dbg.debug_stack("Magic redefinition '%s', old %s" % |
|
243 | self.dbg.debug_stack("Magic redefinition '%s', old %s" % | |
244 | (magicname,old) ) |
|
244 | (magicname,old) ) | |
245 |
|
245 | |||
246 | setattr(self.IP, "magic_" + magicname, im) |
|
246 | setattr(self.IP, "magic_" + magicname, im) | |
247 |
|
247 | |||
248 | def ex(self,cmd): |
|
248 | def ex(self,cmd): | |
249 | """ Execute a normal python statement in user namespace """ |
|
249 | """ Execute a normal python statement in user namespace """ | |
250 | exec cmd in self.user_ns |
|
250 | exec cmd in self.user_ns | |
251 |
|
251 | |||
252 | def ev(self,expr): |
|
252 | def ev(self,expr): | |
253 | """ Evaluate python expression expr in user namespace |
|
253 | """ Evaluate python expression expr in user namespace | |
254 |
|
254 | |||
255 | Returns the result of evaluation""" |
|
255 | Returns the result of evaluation""" | |
256 | return eval(expr,self.user_ns) |
|
256 | return eval(expr,self.user_ns) | |
257 |
|
257 | |||
258 | def runlines(self,lines): |
|
258 | def runlines(self,lines): | |
259 | """ Run the specified lines in interpreter, honoring ipython directives. |
|
259 | """ Run the specified lines in interpreter, honoring ipython directives. | |
260 |
|
260 | |||
261 | This allows %magic and !shell escape notations. |
|
261 | This allows %magic and !shell escape notations. | |
262 |
|
262 | |||
263 | Takes either all lines in one string or list of lines. |
|
263 | Takes either all lines in one string or list of lines. | |
264 | """ |
|
264 | """ | |
265 |
|
265 | |||
266 | def cleanup_ipy_script(script): |
|
266 | def cleanup_ipy_script(script): | |
267 | """ Make a script safe for _ip.runlines() |
|
267 | """ Make a script safe for _ip.runlines() | |
268 |
|
268 | |||
269 | - Removes empty lines Suffixes all indented blocks that end with |
|
269 | - Removes empty lines Suffixes all indented blocks that end with | |
270 | - unindented lines with empty lines |
|
270 | - unindented lines with empty lines | |
271 | """ |
|
271 | """ | |
272 |
|
272 | |||
273 | res = [] |
|
273 | res = [] | |
274 | lines = script.splitlines() |
|
274 | lines = script.splitlines() | |
275 |
|
275 | |||
276 | level = 0 |
|
276 | level = 0 | |
277 | for l in lines: |
|
277 | for l in lines: | |
278 | lstripped = l.lstrip() |
|
278 | lstripped = l.lstrip() | |
279 | stripped = l.strip() |
|
279 | stripped = l.strip() | |
280 | if not stripped: |
|
280 | if not stripped: | |
281 | continue |
|
281 | continue | |
282 | newlevel = len(l) - len(lstripped) |
|
282 | newlevel = len(l) - len(lstripped) | |
283 | def is_secondary_block_start(s): |
|
283 | def is_secondary_block_start(s): | |
284 | if not s.endswith(':'): |
|
284 | if not s.endswith(':'): | |
285 | return False |
|
285 | return False | |
286 | if (s.startswith('elif') or |
|
286 | if (s.startswith('elif') or | |
287 | s.startswith('else') or |
|
287 | s.startswith('else') or | |
288 | s.startswith('except') or |
|
288 | s.startswith('except') or | |
289 | s.startswith('finally')): |
|
289 | s.startswith('finally')): | |
290 | return True |
|
290 | return True | |
291 |
|
291 | |||
292 | if level > 0 and newlevel == 0 and \ |
|
292 | if level > 0 and newlevel == 0 and \ | |
293 | not is_secondary_block_start(stripped): |
|
293 | not is_secondary_block_start(stripped): | |
294 | # add empty line |
|
294 | # add empty line | |
295 | res.append('') |
|
295 | res.append('') | |
296 |
|
296 | |||
297 | res.append(l) |
|
297 | res.append(l) | |
298 | level = newlevel |
|
298 | level = newlevel | |
299 | return '\n'.join(res) + '\n' |
|
299 | return '\n'.join(res) + '\n' | |
300 |
|
300 | |||
301 | if isinstance(lines,basestring): |
|
301 | if isinstance(lines,basestring): | |
302 | script = lines |
|
302 | script = lines | |
303 | else: |
|
303 | else: | |
304 | script = '\n'.join(lines) |
|
304 | script = '\n'.join(lines) | |
305 | clean=cleanup_ipy_script(script) |
|
305 | clean=cleanup_ipy_script(script) | |
306 | # print "_ip.runlines() script:\n",clean # dbg |
|
306 | # print "_ip.runlines() script:\n",clean # dbg | |
307 | self.IP.runlines(clean) |
|
307 | self.IP.runlines(clean) | |
308 |
|
308 | |||
309 | def to_user_ns(self,vars, interactive = True): |
|
309 | def to_user_ns(self,vars, interactive = True): | |
310 | """Inject a group of variables into the IPython user namespace. |
|
310 | """Inject a group of variables into the IPython user namespace. | |
311 |
|
311 | |||
312 | Inputs: |
|
312 | Inputs: | |
313 |
|
313 | |||
314 | - vars: string with variable names separated by whitespace, or a |
|
314 | - vars: string with variable names separated by whitespace, or a | |
315 | dict with name/value pairs. |
|
315 | dict with name/value pairs. | |
316 |
|
316 | |||
317 | - interactive: if True (default), the var will be listed with |
|
317 | - interactive: if True (default), the var will be listed with | |
318 | %whos et. al. |
|
318 | %whos et. al. | |
319 |
|
319 | |||
320 | This utility routine is meant to ease interactive debugging work, |
|
320 | This utility routine is meant to ease interactive debugging work, | |
321 | where you want to easily propagate some internal variable in your code |
|
321 | where you want to easily propagate some internal variable in your code | |
322 | up to the interactive namespace for further exploration. |
|
322 | up to the interactive namespace for further exploration. | |
323 |
|
323 | |||
324 | When you run code via %run, globals in your script become visible at |
|
324 | When you run code via %run, globals in your script become visible at | |
325 | the interactive prompt, but this doesn't happen for locals inside your |
|
325 | the interactive prompt, but this doesn't happen for locals inside your | |
326 | own functions and methods. Yet when debugging, it is common to want |
|
326 | own functions and methods. Yet when debugging, it is common to want | |
327 | to explore some internal variables further at the interactive propmt. |
|
327 | to explore some internal variables further at the interactive propmt. | |
328 |
|
328 | |||
329 | Examples: |
|
329 | Examples: | |
330 |
|
330 | |||
331 | To use this, you first must obtain a handle on the ipython object as |
|
331 | To use this, you first must obtain a handle on the ipython object as | |
332 | indicated above, via: |
|
332 | indicated above, via: | |
333 |
|
333 | |||
334 | from IPython.core import ipapi |
|
334 | from IPython.core import ipapi | |
335 | ip = ipapi.get() |
|
335 | ip = ipapi.get() | |
336 |
|
336 | |||
337 | Once this is done, inside a routine foo() where you want to expose |
|
337 | Once this is done, inside a routine foo() where you want to expose | |
338 | variables x and y, you do the following: |
|
338 | variables x and y, you do the following: | |
339 |
|
339 | |||
340 | def foo(): |
|
340 | def foo(): | |
341 | ... |
|
341 | ... | |
342 | x = your_computation() |
|
342 | x = your_computation() | |
343 | y = something_else() |
|
343 | y = something_else() | |
344 |
|
344 | |||
345 | # This pushes x and y to the interactive prompt immediately, even |
|
345 | # This pushes x and y to the interactive prompt immediately, even | |
346 | # if this routine crashes on the next line after: |
|
346 | # if this routine crashes on the next line after: | |
347 | ip.to_user_ns('x y') |
|
347 | ip.to_user_ns('x y') | |
348 | ... |
|
348 | ... | |
349 |
|
349 | |||
350 | # To expose *ALL* the local variables from the function, use: |
|
350 | # To expose *ALL* the local variables from the function, use: | |
351 | ip.to_user_ns(locals()) |
|
351 | ip.to_user_ns(locals()) | |
352 |
|
352 | |||
353 | ... |
|
353 | ... | |
354 | # return |
|
354 | # return | |
355 |
|
355 | |||
356 |
|
356 | |||
357 | If you need to rename variables, the dict input makes it easy. For |
|
357 | If you need to rename variables, the dict input makes it easy. For | |
358 | example, this call exposes variables 'foo' as 'x' and 'bar' as 'y' |
|
358 | example, this call exposes variables 'foo' as 'x' and 'bar' as 'y' | |
359 | in IPython user namespace: |
|
359 | in IPython user namespace: | |
360 |
|
360 | |||
361 | ip.to_user_ns(dict(x=foo,y=bar)) |
|
361 | ip.to_user_ns(dict(x=foo,y=bar)) | |
362 | """ |
|
362 | """ | |
363 |
|
363 | |||
364 | # print 'vars given:',vars # dbg |
|
364 | # print 'vars given:',vars # dbg | |
365 |
|
365 | |||
366 | # We need a dict of name/value pairs to do namespace updates. |
|
366 | # We need a dict of name/value pairs to do namespace updates. | |
367 | if isinstance(vars,dict): |
|
367 | if isinstance(vars,dict): | |
368 | # If a dict was given, no need to change anything. |
|
368 | # If a dict was given, no need to change anything. | |
369 | vdict = vars |
|
369 | vdict = vars | |
370 | elif isinstance(vars,basestring): |
|
370 | elif isinstance(vars,basestring): | |
371 | # If a string with names was given, get the caller's frame to |
|
371 | # If a string with names was given, get the caller's frame to | |
372 | # evaluate the given names in |
|
372 | # evaluate the given names in | |
373 | cf = sys._getframe(1) |
|
373 | cf = sys._getframe(1) | |
374 | vdict = {} |
|
374 | vdict = {} | |
375 | for name in vars.split(): |
|
375 | for name in vars.split(): | |
376 | try: |
|
376 | try: | |
377 | vdict[name] = eval(name,cf.f_globals,cf.f_locals) |
|
377 | vdict[name] = eval(name,cf.f_globals,cf.f_locals) | |
378 | except: |
|
378 | except: | |
379 | print ('could not get var. %s from %s' % |
|
379 | print ('could not get var. %s from %s' % | |
380 | (name,cf.f_code.co_name)) |
|
380 | (name,cf.f_code.co_name)) | |
381 | else: |
|
381 | else: | |
382 | raise ValueError('vars must be a string or a dict') |
|
382 | raise ValueError('vars must be a string or a dict') | |
383 |
|
383 | |||
384 | # Propagate variables to user namespace |
|
384 | # Propagate variables to user namespace | |
385 | self.user_ns.update(vdict) |
|
385 | self.user_ns.update(vdict) | |
386 |
|
386 | |||
387 | # And configure interactive visibility |
|
387 | # And configure interactive visibility | |
388 | config_ns = self.IP.user_config_ns |
|
388 | config_ns = self.IP.user_config_ns | |
389 | if interactive: |
|
389 | if interactive: | |
390 | for name,val in vdict.iteritems(): |
|
390 | for name,val in vdict.iteritems(): | |
391 | config_ns.pop(name,None) |
|
391 | config_ns.pop(name,None) | |
392 | else: |
|
392 | else: | |
393 | for name,val in vdict.iteritems(): |
|
393 | for name,val in vdict.iteritems(): | |
394 | config_ns[name] = val |
|
394 | config_ns[name] = val | |
395 |
|
395 | |||
396 | def expand_alias(self,line): |
|
396 | def expand_alias(self,line): | |
397 | """ Expand an alias in the command line |
|
397 | """ Expand an alias in the command line | |
398 |
|
398 | |||
399 | Returns the provided command line, possibly with the first word |
|
399 | Returns the provided command line, possibly with the first word | |
400 | (command) translated according to alias expansion rules. |
|
400 | (command) translated according to alias expansion rules. | |
401 |
|
401 | |||
402 | [ipython]|16> _ip.expand_aliases("np myfile.txt") |
|
402 | [ipython]|16> _ip.expand_aliases("np myfile.txt") | |
403 | <16> 'q:/opt/np/notepad++.exe myfile.txt' |
|
403 | <16> 'q:/opt/np/notepad++.exe myfile.txt' | |
404 | """ |
|
404 | """ | |
405 |
|
405 | |||
406 | pre,fn,rest = self.IP.split_user_input(line) |
|
406 | pre,fn,rest = self.IP.split_user_input(line) | |
407 | res = pre + self.IP.expand_aliases(fn,rest) |
|
407 | res = pre + self.IP.expand_aliases(fn,rest) | |
408 | return res |
|
408 | return res | |
409 |
|
409 | |||
410 | def itpl(self, s, depth = 1): |
|
410 | def itpl(self, s, depth = 1): | |
411 | """ Expand Itpl format string s. |
|
411 | """ Expand Itpl format string s. | |
412 |
|
412 | |||
413 | Only callable from command line (i.e. prefilter results); |
|
413 | Only callable from command line (i.e. prefilter results); | |
414 | If you use in your scripts, you need to use a bigger depth! |
|
414 | If you use in your scripts, you need to use a bigger depth! | |
415 | """ |
|
415 | """ | |
416 | return self.IP.var_expand(s, depth) |
|
416 | return self.IP.var_expand(s, depth) | |
417 |
|
417 | |||
418 | def defalias(self, name, cmd): |
|
418 | def defalias(self, name, cmd): | |
419 | """ Define a new alias |
|
419 | """ Define a new alias | |
420 |
|
420 | |||
421 | _ip.defalias('bb','bldmake bldfiles') |
|
421 | _ip.defalias('bb','bldmake bldfiles') | |
422 |
|
422 | |||
423 | Creates a new alias named 'bb' in ipython user namespace |
|
423 | Creates a new alias named 'bb' in ipython user namespace | |
424 | """ |
|
424 | """ | |
425 |
|
425 | |||
426 | self.dbg.check_hotname(name) |
|
426 | self.dbg.check_hotname(name) | |
427 |
|
427 | |||
428 | if name in self.IP.alias_table: |
|
428 | if name in self.IP.alias_table: | |
429 | self.dbg.debug_stack("Alias redefinition: '%s' => '%s' (old '%s')" |
|
429 | self.dbg.debug_stack("Alias redefinition: '%s' => '%s' (old '%s')" | |
430 | % (name, cmd, self.IP.alias_table[name])) |
|
430 | % (name, cmd, self.IP.alias_table[name])) | |
431 |
|
431 | |||
432 | if callable(cmd): |
|
432 | if callable(cmd): | |
433 | self.IP.alias_table[name] = cmd |
|
433 | self.IP.alias_table[name] = cmd | |
434 | from IPython.core import shadowns |
|
434 | from IPython.core import shadowns | |
435 | setattr(shadowns, name,cmd) |
|
435 | setattr(shadowns, name,cmd) | |
436 | return |
|
436 | return | |
437 |
|
437 | |||
438 | if isinstance(cmd,basestring): |
|
438 | if isinstance(cmd,basestring): | |
439 | nargs = cmd.count('%s') |
|
439 | nargs = cmd.count('%s') | |
440 | if nargs>0 and cmd.find('%l')>=0: |
|
440 | if nargs>0 and cmd.find('%l')>=0: | |
441 | raise Exception('The %s and %l specifiers are mutually ' |
|
441 | raise Exception('The %s and %l specifiers are mutually ' | |
442 | 'exclusive in alias definitions.') |
|
442 | 'exclusive in alias definitions.') | |
443 |
|
443 | |||
444 | self.IP.alias_table[name] = (nargs,cmd) |
|
444 | self.IP.alias_table[name] = (nargs,cmd) | |
445 | return |
|
445 | return | |
446 |
|
446 | |||
447 | # just put it in - it's probably (0,'foo') |
|
447 | # just put it in - it's probably (0,'foo') | |
448 | self.IP.alias_table[name] = cmd |
|
448 | self.IP.alias_table[name] = cmd | |
449 |
|
449 | |||
450 | def defmacro(self, *args): |
|
450 | def defmacro(self, *args): | |
451 | """ Define a new macro |
|
451 | """ Define a new macro | |
452 |
|
452 | |||
453 | 2 forms of calling: |
|
453 | 2 forms of calling: | |
454 |
|
454 | |||
455 | mac = _ip.defmacro('print "hello"\nprint "world"') |
|
455 | mac = _ip.defmacro('print "hello"\nprint "world"') | |
456 |
|
456 | |||
457 | (doesn't put the created macro on user namespace) |
|
457 | (doesn't put the created macro on user namespace) | |
458 |
|
458 | |||
459 | _ip.defmacro('build', 'bldmake bldfiles\nabld build winscw udeb') |
|
459 | _ip.defmacro('build', 'bldmake bldfiles\nabld build winscw udeb') | |
460 |
|
460 | |||
461 | (creates a macro named 'build' in user namespace) |
|
461 | (creates a macro named 'build' in user namespace) | |
462 | """ |
|
462 | """ | |
463 |
|
463 | |||
464 | from IPython.core import macro |
|
464 | from IPython.core import macro | |
465 |
|
465 | |||
466 | if len(args) == 1: |
|
466 | if len(args) == 1: | |
467 | return macro.Macro(args[0]) |
|
467 | return macro.Macro(args[0]) | |
468 | elif len(args) == 2: |
|
468 | elif len(args) == 2: | |
469 | self.user_ns[args[0]] = macro.Macro(args[1]) |
|
469 | self.user_ns[args[0]] = macro.Macro(args[1]) | |
470 | else: |
|
470 | else: | |
471 | return Exception("_ip.defmacro must be called with 1 or 2 arguments") |
|
471 | return Exception("_ip.defmacro must be called with 1 or 2 arguments") | |
472 |
|
472 | |||
473 | def set_next_input(self, s): |
|
473 | def set_next_input(self, s): | |
474 | """ Sets the 'default' input string for the next command line. |
|
474 | """ Sets the 'default' input string for the next command line. | |
475 |
|
475 | |||
476 | Requires readline. |
|
476 | Requires readline. | |
477 |
|
477 | |||
478 | Example: |
|
478 | Example: | |
479 |
|
479 | |||
480 | [D:\ipython]|1> _ip.set_next_input("Hello Word") |
|
480 | [D:\ipython]|1> _ip.set_next_input("Hello Word") | |
481 | [D:\ipython]|2> Hello Word_ # cursor is here |
|
481 | [D:\ipython]|2> Hello Word_ # cursor is here | |
482 | """ |
|
482 | """ | |
483 |
|
483 | |||
484 | self.IP.rl_next_input = s |
|
484 | self.IP.rl_next_input = s | |
485 |
|
485 | |||
486 | def load(self, mod): |
|
486 | def load(self, mod): | |
487 | """ Load an extension. |
|
487 | """ Load an extension. | |
488 |
|
488 | |||
489 | Some modules should (or must) be 'load()':ed, rather than just imported. |
|
489 | Some modules should (or must) be 'load()':ed, rather than just imported. | |
490 |
|
490 | |||
491 | Loading will do: |
|
491 | Loading will do: | |
492 |
|
492 | |||
493 | - run init_ipython(ip) |
|
493 | - run init_ipython(ip) | |
494 | - run ipython_firstrun(ip) |
|
494 | - run ipython_firstrun(ip) | |
495 | """ |
|
495 | """ | |
496 |
|
496 | |||
497 | if mod in self.extensions: |
|
497 | if mod in self.extensions: | |
498 | # just to make sure we don't init it twice |
|
498 | # just to make sure we don't init it twice | |
499 | # note that if you 'load' a module that has already been |
|
499 | # note that if you 'load' a module that has already been | |
500 | # imported, init_ipython gets run anyway |
|
500 | # imported, init_ipython gets run anyway | |
501 |
|
501 | |||
502 | return self.extensions[mod] |
|
502 | return self.extensions[mod] | |
503 | __import__(mod) |
|
503 | __import__(mod) | |
504 | m = sys.modules[mod] |
|
504 | m = sys.modules[mod] | |
505 | if hasattr(m,'init_ipython'): |
|
505 | if hasattr(m,'init_ipython'): | |
506 | m.init_ipython(self) |
|
506 | m.init_ipython(self) | |
507 |
|
507 | |||
508 | if hasattr(m,'ipython_firstrun'): |
|
508 | if hasattr(m,'ipython_firstrun'): | |
509 | already_loaded = self.db.get('firstrun_done', set()) |
|
509 | already_loaded = self.db.get('firstrun_done', set()) | |
510 | if mod not in already_loaded: |
|
510 | if mod not in already_loaded: | |
511 | m.ipython_firstrun(self) |
|
511 | m.ipython_firstrun(self) | |
512 | already_loaded.add(mod) |
|
512 | already_loaded.add(mod) | |
513 | self.db['firstrun_done'] = already_loaded |
|
513 | self.db['firstrun_done'] = already_loaded | |
514 |
|
514 | |||
515 | self.extensions[mod] = m |
|
515 | self.extensions[mod] = m | |
516 | return m |
|
516 | return m | |
517 |
|
517 | |||
518 |
|
518 | |||
519 | class DebugTools: |
|
519 | class DebugTools: | |
520 | """ Used for debugging mishaps in api usage |
|
520 | """ Used for debugging mishaps in api usage | |
521 |
|
521 | |||
522 | So far, tracing redefinitions is supported. |
|
522 | So far, tracing redefinitions is supported. | |
523 | """ |
|
523 | """ | |
524 |
|
524 | |||
525 | def __init__(self, ip): |
|
525 | def __init__(self, ip): | |
526 | self.ip = ip |
|
526 | self.ip = ip | |
527 | self.debugmode = False |
|
527 | self.debugmode = False | |
528 | self.hotnames = set() |
|
528 | self.hotnames = set() | |
529 |
|
529 | |||
530 | def hotname(self, name_to_catch): |
|
530 | def hotname(self, name_to_catch): | |
531 | self.hotnames.add(name_to_catch) |
|
531 | self.hotnames.add(name_to_catch) | |
532 |
|
532 | |||
533 | def debug_stack(self, msg = None): |
|
533 | def debug_stack(self, msg = None): | |
534 | if not self.debugmode: |
|
534 | if not self.debugmode: | |
535 | return |
|
535 | return | |
536 |
|
536 | |||
537 | import traceback |
|
537 | import traceback | |
538 | if msg is not None: |
|
538 | if msg is not None: | |
539 | print '====== %s ========' % msg |
|
539 | print '====== %s ========' % msg | |
540 | traceback.print_stack() |
|
540 | traceback.print_stack() | |
541 |
|
541 | |||
542 | def check_hotname(self,name): |
|
542 | def check_hotname(self,name): | |
543 | if name in self.hotnames: |
|
543 | if name in self.hotnames: | |
544 | self.debug_stack( "HotName '%s' caught" % name) |
|
544 | self.debug_stack( "HotName '%s' caught" % name) | |
545 |
|
545 | |||
546 |
|
546 | |||
547 | def launch_new_instance(user_ns = None,shellclass = None): |
|
547 | def launch_new_instance(user_ns = None,shellclass = None): | |
548 | """ Make and start a new ipython instance. |
|
548 | """ Make and start a new ipython instance. | |
549 |
|
549 | |||
550 | This can be called even without having an already initialized |
|
550 | This can be called even without having an already initialized | |
551 | ipython session running. |
|
551 | ipython session running. | |
552 |
|
552 | |||
553 | This is also used as the egg entry point for the 'ipython' script. |
|
553 | This is also used as the egg entry point for the 'ipython' script. | |
554 |
|
554 | |||
555 | """ |
|
555 | """ | |
556 | ses = make_session(user_ns,shellclass) |
|
556 | ses = make_session(user_ns,shellclass) | |
557 | ses.mainloop() |
|
557 | ses.mainloop() | |
558 |
|
558 | |||
559 |
|
559 | |||
560 | def make_user_ns(user_ns = None): |
|
560 | def make_user_ns(user_ns = None): | |
561 | """Return a valid user interactive namespace. |
|
561 | """Return a valid user interactive namespace. | |
562 |
|
562 | |||
563 | This builds a dict with the minimal information needed to operate as a |
|
563 | This builds a dict with the minimal information needed to operate as a | |
564 | valid IPython user namespace, which you can pass to the various embedding |
|
564 | valid IPython user namespace, which you can pass to the various embedding | |
565 | classes in ipython. |
|
565 | classes in ipython. | |
566 |
|
566 | |||
567 | This API is currently deprecated. Use ipapi.make_user_namespaces() instead |
|
567 | This API is currently deprecated. Use ipapi.make_user_namespaces() instead | |
568 | to make both the local and global namespace objects simultaneously. |
|
568 | to make both the local and global namespace objects simultaneously. | |
569 |
|
569 | |||
570 | :Parameters: |
|
570 | :Parameters: | |
571 | user_ns : dict-like, optional |
|
571 | user_ns : dict-like, optional | |
572 | The current user namespace. The items in this namespace should be |
|
572 | The current user namespace. The items in this namespace should be | |
573 | included in the output. If None, an appropriate blank namespace |
|
573 | included in the output. If None, an appropriate blank namespace | |
574 | should be created. |
|
574 | should be created. | |
575 |
|
575 | |||
576 | :Returns: |
|
576 | :Returns: | |
577 | A dictionary-like object to be used as the local namespace of the |
|
577 | A dictionary-like object to be used as the local namespace of the | |
578 | interpreter. |
|
578 | interpreter. | |
579 | """ |
|
579 | """ | |
580 |
|
580 | |||
581 | raise NotImplementedError |
|
581 | raise NotImplementedError | |
582 |
|
582 | |||
583 |
|
583 | |||
584 | def make_user_global_ns(ns = None): |
|
584 | def make_user_global_ns(ns = None): | |
585 | """Return a valid user global namespace. |
|
585 | """Return a valid user global namespace. | |
586 |
|
586 | |||
587 | Similar to make_user_ns(), but global namespaces are really only needed in |
|
587 | Similar to make_user_ns(), but global namespaces are really only needed in | |
588 | embedded applications, where there is a distinction between the user's |
|
588 | embedded applications, where there is a distinction between the user's | |
589 | interactive namespace and the global one where ipython is running. |
|
589 | interactive namespace and the global one where ipython is running. | |
590 |
|
590 | |||
591 | This API is currently deprecated. Use ipapi.make_user_namespaces() instead |
|
591 | This API is currently deprecated. Use ipapi.make_user_namespaces() instead | |
592 | to make both the local and global namespace objects simultaneously. |
|
592 | to make both the local and global namespace objects simultaneously. | |
593 |
|
593 | |||
594 | :Parameters: |
|
594 | :Parameters: | |
595 | ns : dict, optional |
|
595 | ns : dict, optional | |
596 | The current user global namespace. The items in this namespace |
|
596 | The current user global namespace. The items in this namespace | |
597 | should be included in the output. If None, an appropriate blank |
|
597 | should be included in the output. If None, an appropriate blank | |
598 | namespace should be created. |
|
598 | namespace should be created. | |
599 |
|
599 | |||
600 | :Returns: |
|
600 | :Returns: | |
601 | A true dict to be used as the global namespace of the interpreter. |
|
601 | A true dict to be used as the global namespace of the interpreter. | |
602 | """ |
|
602 | """ | |
603 |
|
603 | |||
604 | raise NotImplementedError |
|
604 | raise NotImplementedError | |
605 |
|
605 | |||
606 | # Record the true objects in order to be able to test if the user has overridden |
|
606 | # Record the true objects in order to be able to test if the user has overridden | |
607 | # these API functions. |
|
607 | # these API functions. | |
608 | _make_user_ns = make_user_ns |
|
608 | _make_user_ns = make_user_ns | |
609 | _make_user_global_ns = make_user_global_ns |
|
609 | _make_user_global_ns = make_user_global_ns | |
610 |
|
610 | |||
611 |
|
611 | |||
612 | def make_user_namespaces(user_ns = None,user_global_ns = None): |
|
612 | def make_user_namespaces(user_ns = None,user_global_ns = None): | |
613 | """Return a valid local and global user interactive namespaces. |
|
613 | """Return a valid local and global user interactive namespaces. | |
614 |
|
614 | |||
615 | This builds a dict with the minimal information needed to operate as a |
|
615 | This builds a dict with the minimal information needed to operate as a | |
616 | valid IPython user namespace, which you can pass to the various embedding |
|
616 | valid IPython user namespace, which you can pass to the various embedding | |
617 | classes in ipython. The default implementation returns the same dict for |
|
617 | classes in ipython. The default implementation returns the same dict for | |
618 | both the locals and the globals to allow functions to refer to variables in |
|
618 | both the locals and the globals to allow functions to refer to variables in | |
619 | the namespace. Customized implementations can return different dicts. The |
|
619 | the namespace. Customized implementations can return different dicts. The | |
620 | locals dictionary can actually be anything following the basic mapping |
|
620 | locals dictionary can actually be anything following the basic mapping | |
621 | protocol of a dict, but the globals dict must be a true dict, not even |
|
621 | protocol of a dict, but the globals dict must be a true dict, not even | |
622 | a subclass. It is recommended that any custom object for the locals |
|
622 | a subclass. It is recommended that any custom object for the locals | |
623 | namespace synchronize with the globals dict somehow. |
|
623 | namespace synchronize with the globals dict somehow. | |
624 |
|
624 | |||
625 | Raises TypeError if the provided globals namespace is not a true dict. |
|
625 | Raises TypeError if the provided globals namespace is not a true dict. | |
626 |
|
626 | |||
627 | :Parameters: |
|
627 | :Parameters: | |
628 | user_ns : dict-like, optional |
|
628 | user_ns : dict-like, optional | |
629 | The current user namespace. The items in this namespace should be |
|
629 | The current user namespace. The items in this namespace should be | |
630 | included in the output. If None, an appropriate blank namespace |
|
630 | included in the output. If None, an appropriate blank namespace | |
631 | should be created. |
|
631 | should be created. | |
632 | user_global_ns : dict, optional |
|
632 | user_global_ns : dict, optional | |
633 | The current user global namespace. The items in this namespace |
|
633 | The current user global namespace. The items in this namespace | |
634 | should be included in the output. If None, an appropriate blank |
|
634 | should be included in the output. If None, an appropriate blank | |
635 | namespace should be created. |
|
635 | namespace should be created. | |
636 |
|
636 | |||
637 | :Returns: |
|
637 | :Returns: | |
638 | A tuple pair of dictionary-like object to be used as the local namespace |
|
638 | A tuple pair of dictionary-like object to be used as the local namespace | |
639 | of the interpreter and a dict to be used as the global namespace. |
|
639 | of the interpreter and a dict to be used as the global namespace. | |
640 | """ |
|
640 | """ | |
641 |
|
641 | |||
642 | if user_ns is None: |
|
642 | if user_ns is None: | |
643 | if make_user_ns is not _make_user_ns: |
|
643 | if make_user_ns is not _make_user_ns: | |
644 | # Old API overridden. |
|
644 | # Old API overridden. | |
645 | # FIXME: Issue DeprecationWarning, or just let the old API live on? |
|
645 | # FIXME: Issue DeprecationWarning, or just let the old API live on? | |
646 | user_ns = make_user_ns(user_ns) |
|
646 | user_ns = make_user_ns(user_ns) | |
647 | else: |
|
647 | else: | |
648 | # Set __name__ to __main__ to better match the behavior of the |
|
648 | # Set __name__ to __main__ to better match the behavior of the | |
649 | # normal interpreter. |
|
649 | # normal interpreter. | |
650 | user_ns = {'__name__' :'__main__', |
|
650 | user_ns = {'__name__' :'__main__', | |
651 | '__builtins__' : __builtin__, |
|
651 | '__builtins__' : __builtin__, | |
652 | } |
|
652 | } | |
653 | else: |
|
653 | else: | |
654 | user_ns.setdefault('__name__','__main__') |
|
654 | user_ns.setdefault('__name__','__main__') | |
655 | user_ns.setdefault('__builtins__',__builtin__) |
|
655 | user_ns.setdefault('__builtins__',__builtin__) | |
656 |
|
656 | |||
657 | if user_global_ns is None: |
|
657 | if user_global_ns is None: | |
658 | if make_user_global_ns is not _make_user_global_ns: |
|
658 | if make_user_global_ns is not _make_user_global_ns: | |
659 | # Old API overridden. |
|
659 | # Old API overridden. | |
660 | user_global_ns = make_user_global_ns(user_global_ns) |
|
660 | user_global_ns = make_user_global_ns(user_global_ns) | |
661 | else: |
|
661 | else: | |
662 | user_global_ns = user_ns |
|
662 | user_global_ns = user_ns | |
663 | if type(user_global_ns) is not dict: |
|
663 | if type(user_global_ns) is not dict: | |
664 | raise TypeError("user_global_ns must be a true dict; got %r" |
|
664 | raise TypeError("user_global_ns must be a true dict; got %r" | |
665 | % type(user_global_ns)) |
|
665 | % type(user_global_ns)) | |
666 |
|
666 | |||
667 | return user_ns, user_global_ns |
|
667 | return user_ns, user_global_ns | |
668 |
|
668 | |||
669 |
|
669 | |||
670 | def make_session(user_ns = None, shellclass = None): |
|
670 | def make_session(user_ns = None, shellclass = None): | |
671 | """Makes, but does not launch an IPython session. |
|
671 | """Makes, but does not launch an IPython session. | |
672 |
|
672 | |||
673 | Later on you can call obj.mainloop() on the returned object. |
|
673 | Later on you can call obj.mainloop() on the returned object. | |
674 |
|
674 | |||
675 | Inputs: |
|
675 | Inputs: | |
676 |
|
676 | |||
677 | - user_ns(None): a dict to be used as the user's namespace with initial |
|
677 | - user_ns(None): a dict to be used as the user's namespace with initial | |
678 | data. |
|
678 | data. | |
679 |
|
679 | |||
680 | WARNING: This should *not* be run when a session exists already.""" |
|
680 | WARNING: This should *not* be run when a session exists already.""" | |
681 |
|
681 | |||
682 |
import IPython. |
|
682 | import IPython.core.shell | |
683 | if shellclass is None: |
|
683 | if shellclass is None: | |
684 |
return IPython. |
|
684 | return IPython.core.shell.start(user_ns) | |
685 | return shellclass(user_ns = user_ns) |
|
685 | return shellclass(user_ns = user_ns) |
1 | NO CONTENT: file renamed from IPython/Shell.py to IPython/core/shell.py |
|
NO CONTENT: file renamed from IPython/Shell.py to IPython/core/shell.py |
@@ -1,59 +1,62 b'' | |||||
1 | #!/usr/bin/env python |
|
1 | #!/usr/bin/env python | |
2 | # encoding: utf-8 |
|
2 | # encoding: utf-8 | |
3 |
|
3 | |||
4 | def test_import_completer(): |
|
4 | def test_import_completer(): | |
5 | from IPython.core import completer |
|
5 | from IPython.core import completer | |
6 |
|
6 | |||
7 | def test_import_crashhandler(): |
|
7 | def test_import_crashhandler(): | |
8 | from IPython.core import crashhandler |
|
8 | from IPython.core import crashhandler | |
9 |
|
9 | |||
10 | def test_import_debugger(): |
|
10 | def test_import_debugger(): | |
11 | from IPython.core import debugger |
|
11 | from IPython.core import debugger | |
12 |
|
12 | |||
13 | def test_import_fakemodule(): |
|
13 | def test_import_fakemodule(): | |
14 | from IPython.core import fakemodule |
|
14 | from IPython.core import fakemodule | |
15 |
|
15 | |||
16 | def test_import_excolors(): |
|
16 | def test_import_excolors(): | |
17 | from IPython.core import excolors |
|
17 | from IPython.core import excolors | |
18 |
|
18 | |||
19 | def test_import_history(): |
|
19 | def test_import_history(): | |
20 | from IPython.core import history |
|
20 | from IPython.core import history | |
21 |
|
21 | |||
22 | def test_import_hooks(): |
|
22 | def test_import_hooks(): | |
23 | from IPython.core import hooks |
|
23 | from IPython.core import hooks | |
24 |
|
24 | |||
25 | def test_import_ipapi(): |
|
25 | def test_import_ipapi(): | |
26 | from IPython.core import ipapi |
|
26 | from IPython.core import ipapi | |
27 |
|
27 | |||
28 | def test_import_iplib(): |
|
28 | def test_import_iplib(): | |
29 | from IPython.core import iplib |
|
29 | from IPython.core import iplib | |
30 |
|
30 | |||
31 | def test_import_ipmaker(): |
|
31 | def test_import_ipmaker(): | |
32 | from IPython.core import ipmaker |
|
32 | from IPython.core import ipmaker | |
33 |
|
33 | |||
34 | def test_import_logger(): |
|
34 | def test_import_logger(): | |
35 | from IPython.core import logger |
|
35 | from IPython.core import logger | |
36 |
|
36 | |||
37 | def test_import_macro(): |
|
37 | def test_import_macro(): | |
38 | from IPython.core import macro |
|
38 | from IPython.core import macro | |
39 |
|
39 | |||
40 | def test_import_magic(): |
|
40 | def test_import_magic(): | |
41 | from IPython.core import magic |
|
41 | from IPython.core import magic | |
42 |
|
42 | |||
43 | def test_import_oinspect(): |
|
43 | def test_import_oinspect(): | |
44 | from IPython.core import oinspect |
|
44 | from IPython.core import oinspect | |
45 |
|
45 | |||
46 | def test_import_outputtrap(): |
|
46 | def test_import_outputtrap(): | |
47 | from IPython.core import outputtrap |
|
47 | from IPython.core import outputtrap | |
48 |
|
48 | |||
49 | def test_import_prefilter(): |
|
49 | def test_import_prefilter(): | |
50 | from IPython.core import prefilter |
|
50 | from IPython.core import prefilter | |
51 |
|
51 | |||
52 | def test_import_prompts(): |
|
52 | def test_import_prompts(): | |
53 | from IPython.core import prompts |
|
53 | from IPython.core import prompts | |
54 |
|
54 | |||
55 | def test_import_release(): |
|
55 | def test_import_release(): | |
56 | from IPython.core import release |
|
56 | from IPython.core import release | |
57 |
|
57 | |||
58 | def test_import_shadowns(): |
|
58 | def test_import_shadowns(): | |
59 | from IPython.core import shadowns |
|
59 | from IPython.core import shadowns | |
|
60 | ||||
|
61 | def test_import_shell(): | |||
|
62 | from IPython.core import shell |
@@ -1,527 +1,527 b'' | |||||
1 | #!/usr/bin/python |
|
1 | #!/usr/bin/python | |
2 | # -*- coding: iso-8859-15 -*- |
|
2 | # -*- coding: iso-8859-15 -*- | |
3 | ''' |
|
3 | ''' | |
4 | Provides IPython remote instance. |
|
4 | Provides IPython remote instance. | |
5 |
|
5 | |||
6 | @author: Laurent Dufrechou |
|
6 | @author: Laurent Dufrechou | |
7 | laurent.dufrechou _at_ gmail.com |
|
7 | laurent.dufrechou _at_ gmail.com | |
8 | @license: BSD |
|
8 | @license: BSD | |
9 |
|
9 | |||
10 | All rights reserved. This program and the accompanying materials are made |
|
10 | All rights reserved. This program and the accompanying materials are made | |
11 | available under the terms of the BSD which accompanies this distribution, and |
|
11 | available under the terms of the BSD which accompanies this distribution, and | |
12 | is available at U{http://www.opensource.org/licenses/bsd-license.php} |
|
12 | is available at U{http://www.opensource.org/licenses/bsd-license.php} | |
13 | ''' |
|
13 | ''' | |
14 |
|
14 | |||
15 | __version__ = 0.9 |
|
15 | __version__ = 0.9 | |
16 | __author__ = "Laurent Dufrechou" |
|
16 | __author__ = "Laurent Dufrechou" | |
17 | __email__ = "laurent.dufrechou _at_ gmail.com" |
|
17 | __email__ = "laurent.dufrechou _at_ gmail.com" | |
18 | __license__ = "BSD" |
|
18 | __license__ = "BSD" | |
19 |
|
19 | |||
20 | import re |
|
20 | import re | |
21 | import sys |
|
21 | import sys | |
22 | import os |
|
22 | import os | |
23 | import locale |
|
23 | import locale | |
24 | from thread_ex import ThreadEx |
|
24 | from thread_ex import ThreadEx | |
25 |
|
25 | |||
26 | try: |
|
26 | try: | |
27 | import IPython |
|
27 | import IPython | |
28 | from IPython.utils import genutils |
|
28 | from IPython.utils import genutils | |
29 | from IPython.core import iplib |
|
29 | from IPython.core import iplib | |
30 | except Exception,e: |
|
30 | except Exception,e: | |
31 | print "Error importing IPython (%s)" % str(e) |
|
31 | print "Error importing IPython (%s)" % str(e) | |
32 | raise Exception, e |
|
32 | raise Exception, e | |
33 |
|
33 | |||
34 | ############################################################################## |
|
34 | ############################################################################## | |
35 | class _Helper(object): |
|
35 | class _Helper(object): | |
36 | """Redefine the built-in 'help'. |
|
36 | """Redefine the built-in 'help'. | |
37 | This is a wrapper around pydoc.help (with a twist). |
|
37 | This is a wrapper around pydoc.help (with a twist). | |
38 | """ |
|
38 | """ | |
39 |
|
39 | |||
40 | def __init__(self, pager): |
|
40 | def __init__(self, pager): | |
41 | self._pager = pager |
|
41 | self._pager = pager | |
42 |
|
42 | |||
43 | def __repr__(self): |
|
43 | def __repr__(self): | |
44 | return "Type help() for interactive help, " \ |
|
44 | return "Type help() for interactive help, " \ | |
45 | "or help(object) for help about object." |
|
45 | "or help(object) for help about object." | |
46 |
|
46 | |||
47 | def __call__(self, *args, **kwds): |
|
47 | def __call__(self, *args, **kwds): | |
48 | class DummyWriter(object): |
|
48 | class DummyWriter(object): | |
49 | '''Dumy class to handle help output''' |
|
49 | '''Dumy class to handle help output''' | |
50 | def __init__(self, pager): |
|
50 | def __init__(self, pager): | |
51 | self._pager = pager |
|
51 | self._pager = pager | |
52 |
|
52 | |||
53 | def write(self, data): |
|
53 | def write(self, data): | |
54 | '''hook to fill self._pager''' |
|
54 | '''hook to fill self._pager''' | |
55 | self._pager(data) |
|
55 | self._pager(data) | |
56 |
|
56 | |||
57 | import pydoc |
|
57 | import pydoc | |
58 | pydoc.help.output = DummyWriter(self._pager) |
|
58 | pydoc.help.output = DummyWriter(self._pager) | |
59 | pydoc.help.interact = lambda :1 |
|
59 | pydoc.help.interact = lambda :1 | |
60 |
|
60 | |||
61 | return pydoc.help(*args, **kwds) |
|
61 | return pydoc.help(*args, **kwds) | |
62 |
|
62 | |||
63 |
|
63 | |||
64 | ############################################################################## |
|
64 | ############################################################################## | |
65 | class _CodeExecutor(ThreadEx): |
|
65 | class _CodeExecutor(ThreadEx): | |
66 | ''' Thread that execute ipython code ''' |
|
66 | ''' Thread that execute ipython code ''' | |
67 | def __init__(self, instance): |
|
67 | def __init__(self, instance): | |
68 | ThreadEx.__init__(self) |
|
68 | ThreadEx.__init__(self) | |
69 | self.instance = instance |
|
69 | self.instance = instance | |
70 |
|
70 | |||
71 | def run(self): |
|
71 | def run(self): | |
72 | '''Thread main loop''' |
|
72 | '''Thread main loop''' | |
73 | try: |
|
73 | try: | |
74 | self.instance._doc_text = None |
|
74 | self.instance._doc_text = None | |
75 | self.instance._help_text = None |
|
75 | self.instance._help_text = None | |
76 | self.instance._execute() |
|
76 | self.instance._execute() | |
77 | # used for uper class to generate event after execution |
|
77 | # used for uper class to generate event after execution | |
78 | self.instance._after_execute() |
|
78 | self.instance._after_execute() | |
79 |
|
79 | |||
80 | except KeyboardInterrupt: |
|
80 | except KeyboardInterrupt: | |
81 | pass |
|
81 | pass | |
82 |
|
82 | |||
83 |
|
83 | |||
84 | ############################################################################## |
|
84 | ############################################################################## | |
85 | class NonBlockingIPShell(object): |
|
85 | class NonBlockingIPShell(object): | |
86 | ''' |
|
86 | ''' | |
87 | Create an IPython instance, running the commands in a separate, |
|
87 | Create an IPython instance, running the commands in a separate, | |
88 | non-blocking thread. |
|
88 | non-blocking thread. | |
89 | This allows embedding in any GUI without blockage. |
|
89 | This allows embedding in any GUI without blockage. | |
90 |
|
90 | |||
91 | Note: The ThreadEx class supports asynchroneous function call |
|
91 | Note: The ThreadEx class supports asynchroneous function call | |
92 | via raise_exc() |
|
92 | via raise_exc() | |
93 | ''' |
|
93 | ''' | |
94 |
|
94 | |||
95 | def __init__(self, argv=[], user_ns={}, user_global_ns=None, |
|
95 | def __init__(self, argv=[], user_ns={}, user_global_ns=None, | |
96 | cin=None, cout=None, cerr=None, |
|
96 | cin=None, cout=None, cerr=None, | |
97 | ask_exit_handler=None): |
|
97 | ask_exit_handler=None): | |
98 | ''' |
|
98 | ''' | |
99 | @param argv: Command line options for IPython |
|
99 | @param argv: Command line options for IPython | |
100 | @type argv: list |
|
100 | @type argv: list | |
101 | @param user_ns: User namespace. |
|
101 | @param user_ns: User namespace. | |
102 | @type user_ns: dictionary |
|
102 | @type user_ns: dictionary | |
103 | @param user_global_ns: User global namespace. |
|
103 | @param user_global_ns: User global namespace. | |
104 | @type user_global_ns: dictionary. |
|
104 | @type user_global_ns: dictionary. | |
105 | @param cin: Console standard input. |
|
105 | @param cin: Console standard input. | |
106 | @type cin: IO stream |
|
106 | @type cin: IO stream | |
107 | @param cout: Console standard output. |
|
107 | @param cout: Console standard output. | |
108 | @type cout: IO stream |
|
108 | @type cout: IO stream | |
109 | @param cerr: Console standard error. |
|
109 | @param cerr: Console standard error. | |
110 | @type cerr: IO stream |
|
110 | @type cerr: IO stream | |
111 | @param exit_handler: Replacement for builtin exit() function |
|
111 | @param exit_handler: Replacement for builtin exit() function | |
112 | @type exit_handler: function |
|
112 | @type exit_handler: function | |
113 | @param time_loop: Define the sleep time between two thread's loop |
|
113 | @param time_loop: Define the sleep time between two thread's loop | |
114 | @type int |
|
114 | @type int | |
115 | ''' |
|
115 | ''' | |
116 | #ipython0 initialisation |
|
116 | #ipython0 initialisation | |
117 | self._IP = None |
|
117 | self._IP = None | |
118 | self.init_ipython0(argv, user_ns, user_global_ns, |
|
118 | self.init_ipython0(argv, user_ns, user_global_ns, | |
119 | cin, cout, cerr, |
|
119 | cin, cout, cerr, | |
120 | ask_exit_handler) |
|
120 | ask_exit_handler) | |
121 |
|
121 | |||
122 | #vars used by _execute |
|
122 | #vars used by _execute | |
123 | self._iter_more = 0 |
|
123 | self._iter_more = 0 | |
124 | self._history_level = 0 |
|
124 | self._history_level = 0 | |
125 | self._complete_sep = re.compile('[\s\{\}\[\]\(\)\=]') |
|
125 | self._complete_sep = re.compile('[\s\{\}\[\]\(\)\=]') | |
126 | self._prompt = str(self._IP.outputcache.prompt1).strip() |
|
126 | self._prompt = str(self._IP.outputcache.prompt1).strip() | |
127 |
|
127 | |||
128 | #thread working vars |
|
128 | #thread working vars | |
129 | self._line_to_execute = '' |
|
129 | self._line_to_execute = '' | |
130 | self._threading = True |
|
130 | self._threading = True | |
131 |
|
131 | |||
132 | #vars that will be checked by GUI loop to handle thread states... |
|
132 | #vars that will be checked by GUI loop to handle thread states... | |
133 | #will be replaced later by PostEvent GUI funtions... |
|
133 | #will be replaced later by PostEvent GUI funtions... | |
134 | self._doc_text = None |
|
134 | self._doc_text = None | |
135 | self._help_text = None |
|
135 | self._help_text = None | |
136 | self._add_button = None |
|
136 | self._add_button = None | |
137 |
|
137 | |||
138 | def init_ipython0(self, argv=[], user_ns={}, user_global_ns=None, |
|
138 | def init_ipython0(self, argv=[], user_ns={}, user_global_ns=None, | |
139 | cin=None, cout=None, cerr=None, |
|
139 | cin=None, cout=None, cerr=None, | |
140 | ask_exit_handler=None): |
|
140 | ask_exit_handler=None): | |
141 | ''' Initialize an ipython0 instance ''' |
|
141 | ''' Initialize an ipython0 instance ''' | |
142 |
|
142 | |||
143 | #first we redefine in/out/error functions of IPython |
|
143 | #first we redefine in/out/error functions of IPython | |
144 | #BUG: we've got a limitation form ipython0 there |
|
144 | #BUG: we've got a limitation form ipython0 there | |
145 | #only one instance can be instanciated else tehre will be |
|
145 | #only one instance can be instanciated else tehre will be | |
146 | #cin/cout/cerr clash... |
|
146 | #cin/cout/cerr clash... | |
147 | if cin: |
|
147 | if cin: | |
148 | genutils.Term.cin = cin |
|
148 | genutils.Term.cin = cin | |
149 | if cout: |
|
149 | if cout: | |
150 | genutils.Term.cout = cout |
|
150 | genutils.Term.cout = cout | |
151 | if cerr: |
|
151 | if cerr: | |
152 | genutils.Term.cerr = cerr |
|
152 | genutils.Term.cerr = cerr | |
153 |
|
153 | |||
154 | excepthook = sys.excepthook |
|
154 | excepthook = sys.excepthook | |
155 |
|
155 | |||
156 | #Hack to save sys.displayhook, because ipython seems to overwrite it... |
|
156 | #Hack to save sys.displayhook, because ipython seems to overwrite it... | |
157 | self.sys_displayhook_ori = sys.displayhook |
|
157 | self.sys_displayhook_ori = sys.displayhook | |
158 |
|
158 | |||
159 |
self._IP = IPython. |
|
159 | self._IP = IPython.shell.make_IPython( | |
160 | argv,user_ns=user_ns, |
|
160 | argv,user_ns=user_ns, | |
161 | user_global_ns=user_global_ns, |
|
161 | user_global_ns=user_global_ns, | |
162 | embedded=True, |
|
162 | embedded=True, | |
163 |
shell_class=IPython. |
|
163 | shell_class=IPython.shell.InteractiveShell) | |
164 |
|
164 | |||
165 | #we save ipython0 displayhook and we restore sys.displayhook |
|
165 | #we save ipython0 displayhook and we restore sys.displayhook | |
166 | self.displayhook = sys.displayhook |
|
166 | self.displayhook = sys.displayhook | |
167 | sys.displayhook = self.sys_displayhook_ori |
|
167 | sys.displayhook = self.sys_displayhook_ori | |
168 |
|
168 | |||
169 | #we replace IPython default encoding by wx locale encoding |
|
169 | #we replace IPython default encoding by wx locale encoding | |
170 | loc = locale.getpreferredencoding() |
|
170 | loc = locale.getpreferredencoding() | |
171 | if loc: |
|
171 | if loc: | |
172 | self._IP.stdin_encoding = loc |
|
172 | self._IP.stdin_encoding = loc | |
173 | #we replace the ipython default pager by our pager |
|
173 | #we replace the ipython default pager by our pager | |
174 | self._IP.set_hook('show_in_pager', self._pager) |
|
174 | self._IP.set_hook('show_in_pager', self._pager) | |
175 |
|
175 | |||
176 | #we replace the ipython default shell command caller |
|
176 | #we replace the ipython default shell command caller | |
177 | #by our shell handler |
|
177 | #by our shell handler | |
178 | self._IP.set_hook('shell_hook', self._shell) |
|
178 | self._IP.set_hook('shell_hook', self._shell) | |
179 |
|
179 | |||
180 | #we replace the ipython default input command caller by our method |
|
180 | #we replace the ipython default input command caller by our method | |
181 | iplib.raw_input_original = self._raw_input_original |
|
181 | iplib.raw_input_original = self._raw_input_original | |
182 | #we replace the ipython default exit command by our method |
|
182 | #we replace the ipython default exit command by our method | |
183 | self._IP.exit = ask_exit_handler |
|
183 | self._IP.exit = ask_exit_handler | |
184 | #we replace the help command |
|
184 | #we replace the help command | |
185 | self._IP.user_ns['help'] = _Helper(self._pager_help) |
|
185 | self._IP.user_ns['help'] = _Helper(self._pager_help) | |
186 |
|
186 | |||
187 | #we disable cpase magic... until we found a way to use it properly. |
|
187 | #we disable cpase magic... until we found a way to use it properly. | |
188 | from IPython.core import ipapi |
|
188 | from IPython.core import ipapi | |
189 | ip = ipapi.get() |
|
189 | ip = ipapi.get() | |
190 | def bypass_magic(self, arg): |
|
190 | def bypass_magic(self, arg): | |
191 | print '%this magic is currently disabled.' |
|
191 | print '%this magic is currently disabled.' | |
192 | ip.expose_magic('cpaste', bypass_magic) |
|
192 | ip.expose_magic('cpaste', bypass_magic) | |
193 |
|
193 | |||
194 | import __builtin__ |
|
194 | import __builtin__ | |
195 | __builtin__.raw_input = self._raw_input |
|
195 | __builtin__.raw_input = self._raw_input | |
196 |
|
196 | |||
197 | sys.excepthook = excepthook |
|
197 | sys.excepthook = excepthook | |
198 |
|
198 | |||
199 | #----------------------- Thread management section ---------------------- |
|
199 | #----------------------- Thread management section ---------------------- | |
200 | def do_execute(self, line): |
|
200 | def do_execute(self, line): | |
201 | """ |
|
201 | """ | |
202 | Tell the thread to process the 'line' command |
|
202 | Tell the thread to process the 'line' command | |
203 | """ |
|
203 | """ | |
204 |
|
204 | |||
205 | self._line_to_execute = line |
|
205 | self._line_to_execute = line | |
206 |
|
206 | |||
207 | if self._threading: |
|
207 | if self._threading: | |
208 | #we launch the ipython line execution in a thread to make it |
|
208 | #we launch the ipython line execution in a thread to make it | |
209 | #interruptible with include it in self namespace to be able |
|
209 | #interruptible with include it in self namespace to be able | |
210 | #to call ce.raise_exc(KeyboardInterrupt) |
|
210 | #to call ce.raise_exc(KeyboardInterrupt) | |
211 | self.ce = _CodeExecutor(self) |
|
211 | self.ce = _CodeExecutor(self) | |
212 | self.ce.start() |
|
212 | self.ce.start() | |
213 | else: |
|
213 | else: | |
214 | try: |
|
214 | try: | |
215 | self._doc_text = None |
|
215 | self._doc_text = None | |
216 | self._help_text = None |
|
216 | self._help_text = None | |
217 | self._execute() |
|
217 | self._execute() | |
218 | # used for uper class to generate event after execution |
|
218 | # used for uper class to generate event after execution | |
219 | self._after_execute() |
|
219 | self._after_execute() | |
220 |
|
220 | |||
221 | except KeyboardInterrupt: |
|
221 | except KeyboardInterrupt: | |
222 | pass |
|
222 | pass | |
223 |
|
223 | |||
224 | #----------------------- IPython management section ---------------------- |
|
224 | #----------------------- IPython management section ---------------------- | |
225 | def get_threading(self): |
|
225 | def get_threading(self): | |
226 | """ |
|
226 | """ | |
227 | Returns threading status, is set to True, then each command sent to |
|
227 | Returns threading status, is set to True, then each command sent to | |
228 | the interpreter will be executed in a separated thread allowing, |
|
228 | the interpreter will be executed in a separated thread allowing, | |
229 | for example, breaking a long running commands. |
|
229 | for example, breaking a long running commands. | |
230 | Disallowing it, permits better compatibilty with instance that is embedding |
|
230 | Disallowing it, permits better compatibilty with instance that is embedding | |
231 | IPython instance. |
|
231 | IPython instance. | |
232 |
|
232 | |||
233 | @return: Execution method |
|
233 | @return: Execution method | |
234 | @rtype: bool |
|
234 | @rtype: bool | |
235 | """ |
|
235 | """ | |
236 | return self._threading |
|
236 | return self._threading | |
237 |
|
237 | |||
238 | def set_threading(self, state): |
|
238 | def set_threading(self, state): | |
239 | """ |
|
239 | """ | |
240 | Sets threading state, if set to True, then each command sent to |
|
240 | Sets threading state, if set to True, then each command sent to | |
241 | the interpreter will be executed in a separated thread allowing, |
|
241 | the interpreter will be executed in a separated thread allowing, | |
242 | for example, breaking a long running commands. |
|
242 | for example, breaking a long running commands. | |
243 | Disallowing it, permits better compatibilty with instance that is embedding |
|
243 | Disallowing it, permits better compatibilty with instance that is embedding | |
244 | IPython instance. |
|
244 | IPython instance. | |
245 |
|
245 | |||
246 | @param state: Sets threading state |
|
246 | @param state: Sets threading state | |
247 | @type bool |
|
247 | @type bool | |
248 | """ |
|
248 | """ | |
249 | self._threading = state |
|
249 | self._threading = state | |
250 |
|
250 | |||
251 | def get_doc_text(self): |
|
251 | def get_doc_text(self): | |
252 | """ |
|
252 | """ | |
253 | Returns the output of the processing that need to be paged (if any) |
|
253 | Returns the output of the processing that need to be paged (if any) | |
254 |
|
254 | |||
255 | @return: The std output string. |
|
255 | @return: The std output string. | |
256 | @rtype: string |
|
256 | @rtype: string | |
257 | """ |
|
257 | """ | |
258 | return self._doc_text |
|
258 | return self._doc_text | |
259 |
|
259 | |||
260 | def get_help_text(self): |
|
260 | def get_help_text(self): | |
261 | """ |
|
261 | """ | |
262 | Returns the output of the processing that need to be paged via help pager(if any) |
|
262 | Returns the output of the processing that need to be paged via help pager(if any) | |
263 |
|
263 | |||
264 | @return: The std output string. |
|
264 | @return: The std output string. | |
265 | @rtype: string |
|
265 | @rtype: string | |
266 | """ |
|
266 | """ | |
267 | return self._help_text |
|
267 | return self._help_text | |
268 |
|
268 | |||
269 | def get_banner(self): |
|
269 | def get_banner(self): | |
270 | """ |
|
270 | """ | |
271 | Returns the IPython banner for useful info on IPython instance |
|
271 | Returns the IPython banner for useful info on IPython instance | |
272 |
|
272 | |||
273 | @return: The banner string. |
|
273 | @return: The banner string. | |
274 | @rtype: string |
|
274 | @rtype: string | |
275 | """ |
|
275 | """ | |
276 | return self._IP.BANNER |
|
276 | return self._IP.BANNER | |
277 |
|
277 | |||
278 | def get_prompt_count(self): |
|
278 | def get_prompt_count(self): | |
279 | """ |
|
279 | """ | |
280 | Returns the prompt number. |
|
280 | Returns the prompt number. | |
281 | Each time a user execute a line in the IPython shell the prompt count is increased |
|
281 | Each time a user execute a line in the IPython shell the prompt count is increased | |
282 |
|
282 | |||
283 | @return: The prompt number |
|
283 | @return: The prompt number | |
284 | @rtype: int |
|
284 | @rtype: int | |
285 | """ |
|
285 | """ | |
286 | return self._IP.outputcache.prompt_count |
|
286 | return self._IP.outputcache.prompt_count | |
287 |
|
287 | |||
288 | def get_prompt(self): |
|
288 | def get_prompt(self): | |
289 | """ |
|
289 | """ | |
290 | Returns current prompt inside IPython instance |
|
290 | Returns current prompt inside IPython instance | |
291 | (Can be In [...]: ot ...:) |
|
291 | (Can be In [...]: ot ...:) | |
292 |
|
292 | |||
293 | @return: The current prompt. |
|
293 | @return: The current prompt. | |
294 | @rtype: string |
|
294 | @rtype: string | |
295 | """ |
|
295 | """ | |
296 | return self._prompt |
|
296 | return self._prompt | |
297 |
|
297 | |||
298 | def get_indentation(self): |
|
298 | def get_indentation(self): | |
299 | """ |
|
299 | """ | |
300 | Returns the current indentation level |
|
300 | Returns the current indentation level | |
301 | Usefull to put the caret at the good start position if we want to do autoindentation. |
|
301 | Usefull to put the caret at the good start position if we want to do autoindentation. | |
302 |
|
302 | |||
303 | @return: The indentation level. |
|
303 | @return: The indentation level. | |
304 | @rtype: int |
|
304 | @rtype: int | |
305 | """ |
|
305 | """ | |
306 | return self._IP.indent_current_nsp |
|
306 | return self._IP.indent_current_nsp | |
307 |
|
307 | |||
308 | def update_namespace(self, ns_dict): |
|
308 | def update_namespace(self, ns_dict): | |
309 | ''' |
|
309 | ''' | |
310 | Add the current dictionary to the shell namespace. |
|
310 | Add the current dictionary to the shell namespace. | |
311 |
|
311 | |||
312 | @param ns_dict: A dictionary of symbol-values. |
|
312 | @param ns_dict: A dictionary of symbol-values. | |
313 | @type ns_dict: dictionary |
|
313 | @type ns_dict: dictionary | |
314 | ''' |
|
314 | ''' | |
315 | self._IP.user_ns.update(ns_dict) |
|
315 | self._IP.user_ns.update(ns_dict) | |
316 |
|
316 | |||
317 | def complete(self, line): |
|
317 | def complete(self, line): | |
318 | ''' |
|
318 | ''' | |
319 | Returns an auto completed line and/or posibilities for completion. |
|
319 | Returns an auto completed line and/or posibilities for completion. | |
320 |
|
320 | |||
321 | @param line: Given line so far. |
|
321 | @param line: Given line so far. | |
322 | @type line: string |
|
322 | @type line: string | |
323 |
|
323 | |||
324 | @return: Line completed as for as possible, |
|
324 | @return: Line completed as for as possible, | |
325 | and possible further completions. |
|
325 | and possible further completions. | |
326 | @rtype: tuple |
|
326 | @rtype: tuple | |
327 | ''' |
|
327 | ''' | |
328 | split_line = self._complete_sep.split(line) |
|
328 | split_line = self._complete_sep.split(line) | |
329 | possibilities = self._IP.complete(split_line[-1]) |
|
329 | possibilities = self._IP.complete(split_line[-1]) | |
330 | if possibilities: |
|
330 | if possibilities: | |
331 |
|
331 | |||
332 | def _common_prefix(str1, str2): |
|
332 | def _common_prefix(str1, str2): | |
333 | ''' |
|
333 | ''' | |
334 | Reduction function. returns common prefix of two given strings. |
|
334 | Reduction function. returns common prefix of two given strings. | |
335 |
|
335 | |||
336 | @param str1: First string. |
|
336 | @param str1: First string. | |
337 | @type str1: string |
|
337 | @type str1: string | |
338 | @param str2: Second string |
|
338 | @param str2: Second string | |
339 | @type str2: string |
|
339 | @type str2: string | |
340 |
|
340 | |||
341 | @return: Common prefix to both strings. |
|
341 | @return: Common prefix to both strings. | |
342 | @rtype: string |
|
342 | @rtype: string | |
343 | ''' |
|
343 | ''' | |
344 | for i in range(len(str1)): |
|
344 | for i in range(len(str1)): | |
345 | if not str2.startswith(str1[:i+1]): |
|
345 | if not str2.startswith(str1[:i+1]): | |
346 | return str1[:i] |
|
346 | return str1[:i] | |
347 | return str1 |
|
347 | return str1 | |
348 | common_prefix = reduce(_common_prefix, possibilities) |
|
348 | common_prefix = reduce(_common_prefix, possibilities) | |
349 | completed = line[:-len(split_line[-1])]+common_prefix |
|
349 | completed = line[:-len(split_line[-1])]+common_prefix | |
350 | else: |
|
350 | else: | |
351 | completed = line |
|
351 | completed = line | |
352 | return completed, possibilities |
|
352 | return completed, possibilities | |
353 |
|
353 | |||
354 | def history_back(self): |
|
354 | def history_back(self): | |
355 | ''' |
|
355 | ''' | |
356 | Provides one history command back. |
|
356 | Provides one history command back. | |
357 |
|
357 | |||
358 | @return: The command string. |
|
358 | @return: The command string. | |
359 | @rtype: string |
|
359 | @rtype: string | |
360 | ''' |
|
360 | ''' | |
361 | history = '' |
|
361 | history = '' | |
362 | #the below while loop is used to suppress empty history lines |
|
362 | #the below while loop is used to suppress empty history lines | |
363 | while((history == '' or history == '\n') and self._history_level >0): |
|
363 | while((history == '' or history == '\n') and self._history_level >0): | |
364 | if self._history_level >= 1: |
|
364 | if self._history_level >= 1: | |
365 | self._history_level -= 1 |
|
365 | self._history_level -= 1 | |
366 | history = self._get_history() |
|
366 | history = self._get_history() | |
367 | return history |
|
367 | return history | |
368 |
|
368 | |||
369 | def history_forward(self): |
|
369 | def history_forward(self): | |
370 | ''' |
|
370 | ''' | |
371 | Provides one history command forward. |
|
371 | Provides one history command forward. | |
372 |
|
372 | |||
373 | @return: The command string. |
|
373 | @return: The command string. | |
374 | @rtype: string |
|
374 | @rtype: string | |
375 | ''' |
|
375 | ''' | |
376 | history = '' |
|
376 | history = '' | |
377 | #the below while loop is used to suppress empty history lines |
|
377 | #the below while loop is used to suppress empty history lines | |
378 | while((history == '' or history == '\n') \ |
|
378 | while((history == '' or history == '\n') \ | |
379 | and self._history_level <= self._get_history_max_index()): |
|
379 | and self._history_level <= self._get_history_max_index()): | |
380 | if self._history_level < self._get_history_max_index(): |
|
380 | if self._history_level < self._get_history_max_index(): | |
381 | self._history_level += 1 |
|
381 | self._history_level += 1 | |
382 | history = self._get_history() |
|
382 | history = self._get_history() | |
383 | else: |
|
383 | else: | |
384 | if self._history_level == self._get_history_max_index(): |
|
384 | if self._history_level == self._get_history_max_index(): | |
385 | history = self._get_history() |
|
385 | history = self._get_history() | |
386 | self._history_level += 1 |
|
386 | self._history_level += 1 | |
387 | else: |
|
387 | else: | |
388 | history = '' |
|
388 | history = '' | |
389 | return history |
|
389 | return history | |
390 |
|
390 | |||
391 | def init_history_index(self): |
|
391 | def init_history_index(self): | |
392 | ''' |
|
392 | ''' | |
393 | set history to last command entered |
|
393 | set history to last command entered | |
394 | ''' |
|
394 | ''' | |
395 | self._history_level = self._get_history_max_index()+1 |
|
395 | self._history_level = self._get_history_max_index()+1 | |
396 |
|
396 | |||
397 | #----------------------- IPython PRIVATE management section -------------- |
|
397 | #----------------------- IPython PRIVATE management section -------------- | |
398 | def _after_execute(self): |
|
398 | def _after_execute(self): | |
399 | ''' |
|
399 | ''' | |
400 | Can be redefined to generate post event after excution is done |
|
400 | Can be redefined to generate post event after excution is done | |
401 | ''' |
|
401 | ''' | |
402 | pass |
|
402 | pass | |
403 |
|
403 | |||
404 | def _ask_exit(self): |
|
404 | def _ask_exit(self): | |
405 | ''' |
|
405 | ''' | |
406 | Can be redefined to generate post event to exit the Ipython shell |
|
406 | Can be redefined to generate post event to exit the Ipython shell | |
407 | ''' |
|
407 | ''' | |
408 | pass |
|
408 | pass | |
409 |
|
409 | |||
410 | def _get_history_max_index(self): |
|
410 | def _get_history_max_index(self): | |
411 | ''' |
|
411 | ''' | |
412 | returns the max length of the history buffer |
|
412 | returns the max length of the history buffer | |
413 |
|
413 | |||
414 | @return: history length |
|
414 | @return: history length | |
415 | @rtype: int |
|
415 | @rtype: int | |
416 | ''' |
|
416 | ''' | |
417 | return len(self._IP.input_hist_raw)-1 |
|
417 | return len(self._IP.input_hist_raw)-1 | |
418 |
|
418 | |||
419 | def _get_history(self): |
|
419 | def _get_history(self): | |
420 | ''' |
|
420 | ''' | |
421 | Get's the command string of the current history level. |
|
421 | Get's the command string of the current history level. | |
422 |
|
422 | |||
423 | @return: Historic command stri |
|
423 | @return: Historic command stri | |
424 | @rtype: string |
|
424 | @rtype: string | |
425 | ''' |
|
425 | ''' | |
426 | rv = self._IP.input_hist_raw[self._history_level].strip('\n') |
|
426 | rv = self._IP.input_hist_raw[self._history_level].strip('\n') | |
427 | return rv |
|
427 | return rv | |
428 |
|
428 | |||
429 | def _pager_help(self, text): |
|
429 | def _pager_help(self, text): | |
430 | ''' |
|
430 | ''' | |
431 | This function is used as a callback replacment to IPython help pager function |
|
431 | This function is used as a callback replacment to IPython help pager function | |
432 |
|
432 | |||
433 | It puts the 'text' value inside the self._help_text string that can be retrived via |
|
433 | It puts the 'text' value inside the self._help_text string that can be retrived via | |
434 | get_help_text function. |
|
434 | get_help_text function. | |
435 | ''' |
|
435 | ''' | |
436 | if self._help_text == None: |
|
436 | if self._help_text == None: | |
437 | self._help_text = text |
|
437 | self._help_text = text | |
438 | else: |
|
438 | else: | |
439 | self._help_text += text |
|
439 | self._help_text += text | |
440 |
|
440 | |||
441 | def _pager(self, IP, text): |
|
441 | def _pager(self, IP, text): | |
442 | ''' |
|
442 | ''' | |
443 | This function is used as a callback replacment to IPython pager function |
|
443 | This function is used as a callback replacment to IPython pager function | |
444 |
|
444 | |||
445 | It puts the 'text' value inside the self._doc_text string that can be retrived via |
|
445 | It puts the 'text' value inside the self._doc_text string that can be retrived via | |
446 | get_doc_text function. |
|
446 | get_doc_text function. | |
447 | ''' |
|
447 | ''' | |
448 | self._doc_text = text |
|
448 | self._doc_text = text | |
449 |
|
449 | |||
450 | def _raw_input_original(self, prompt=''): |
|
450 | def _raw_input_original(self, prompt=''): | |
451 | ''' |
|
451 | ''' | |
452 | Custom raw_input() replacement. Get's current line from console buffer. |
|
452 | Custom raw_input() replacement. Get's current line from console buffer. | |
453 |
|
453 | |||
454 | @param prompt: Prompt to print. Here for compatability as replacement. |
|
454 | @param prompt: Prompt to print. Here for compatability as replacement. | |
455 | @type prompt: string |
|
455 | @type prompt: string | |
456 |
|
456 | |||
457 | @return: The current command line text. |
|
457 | @return: The current command line text. | |
458 | @rtype: string |
|
458 | @rtype: string | |
459 | ''' |
|
459 | ''' | |
460 | return self._line_to_execute |
|
460 | return self._line_to_execute | |
461 |
|
461 | |||
462 | def _raw_input(self, prompt=''): |
|
462 | def _raw_input(self, prompt=''): | |
463 | """ A replacement from python's raw_input. |
|
463 | """ A replacement from python's raw_input. | |
464 | """ |
|
464 | """ | |
465 | raise NotImplementedError |
|
465 | raise NotImplementedError | |
466 |
|
466 | |||
467 | def _execute(self): |
|
467 | def _execute(self): | |
468 | ''' |
|
468 | ''' | |
469 | Executes the current line provided by the shell object. |
|
469 | Executes the current line provided by the shell object. | |
470 | ''' |
|
470 | ''' | |
471 |
|
471 | |||
472 | orig_stdout = sys.stdout |
|
472 | orig_stdout = sys.stdout | |
473 |
sys.stdout = IPython. |
|
473 | sys.stdout = IPython.shell.Term.cout | |
474 | #self.sys_displayhook_ori = sys.displayhook |
|
474 | #self.sys_displayhook_ori = sys.displayhook | |
475 | #sys.displayhook = self.displayhook |
|
475 | #sys.displayhook = self.displayhook | |
476 |
|
476 | |||
477 | try: |
|
477 | try: | |
478 | line = self._IP.raw_input(None, self._iter_more) |
|
478 | line = self._IP.raw_input(None, self._iter_more) | |
479 | if self._IP.autoindent: |
|
479 | if self._IP.autoindent: | |
480 | self._IP.readline_startup_hook(None) |
|
480 | self._IP.readline_startup_hook(None) | |
481 |
|
481 | |||
482 | except KeyboardInterrupt: |
|
482 | except KeyboardInterrupt: | |
483 | self._IP.write('\nKeyboardInterrupt\n') |
|
483 | self._IP.write('\nKeyboardInterrupt\n') | |
484 | self._IP.resetbuffer() |
|
484 | self._IP.resetbuffer() | |
485 | # keep cache in sync with the prompt counter: |
|
485 | # keep cache in sync with the prompt counter: | |
486 | self._IP.outputcache.prompt_count -= 1 |
|
486 | self._IP.outputcache.prompt_count -= 1 | |
487 |
|
487 | |||
488 | if self._IP.autoindent: |
|
488 | if self._IP.autoindent: | |
489 | self._IP.indent_current_nsp = 0 |
|
489 | self._IP.indent_current_nsp = 0 | |
490 | self._iter_more = 0 |
|
490 | self._iter_more = 0 | |
491 | except: |
|
491 | except: | |
492 | self._IP.showtraceback() |
|
492 | self._IP.showtraceback() | |
493 | else: |
|
493 | else: | |
494 | self._IP.write(str(self._IP.outputcache.prompt_out).strip()) |
|
494 | self._IP.write(str(self._IP.outputcache.prompt_out).strip()) | |
495 | self._iter_more = self._IP.push(line) |
|
495 | self._iter_more = self._IP.push(line) | |
496 | if (self._IP.SyntaxTB.last_syntax_error and \ |
|
496 | if (self._IP.SyntaxTB.last_syntax_error and \ | |
497 | self._IP.rc.autoedit_syntax): |
|
497 | self._IP.rc.autoedit_syntax): | |
498 | self._IP.edit_syntax_error() |
|
498 | self._IP.edit_syntax_error() | |
499 | if self._iter_more: |
|
499 | if self._iter_more: | |
500 | self._prompt = str(self._IP.outputcache.prompt2).strip() |
|
500 | self._prompt = str(self._IP.outputcache.prompt2).strip() | |
501 | if self._IP.autoindent: |
|
501 | if self._IP.autoindent: | |
502 | self._IP.readline_startup_hook(self._IP.pre_readline) |
|
502 | self._IP.readline_startup_hook(self._IP.pre_readline) | |
503 | else: |
|
503 | else: | |
504 | self._prompt = str(self._IP.outputcache.prompt1).strip() |
|
504 | self._prompt = str(self._IP.outputcache.prompt1).strip() | |
505 | self._IP.indent_current_nsp = 0 #we set indentation to 0 |
|
505 | self._IP.indent_current_nsp = 0 #we set indentation to 0 | |
506 |
|
506 | |||
507 | sys.stdout = orig_stdout |
|
507 | sys.stdout = orig_stdout | |
508 | #sys.displayhook = self.sys_displayhook_ori |
|
508 | #sys.displayhook = self.sys_displayhook_ori | |
509 |
|
509 | |||
510 | def _shell(self, ip, cmd): |
|
510 | def _shell(self, ip, cmd): | |
511 | ''' |
|
511 | ''' | |
512 | Replacement method to allow shell commands without them blocking. |
|
512 | Replacement method to allow shell commands without them blocking. | |
513 |
|
513 | |||
514 | @param ip: Ipython instance, same as self._IP |
|
514 | @param ip: Ipython instance, same as self._IP | |
515 | @type cmd: Ipython instance |
|
515 | @type cmd: Ipython instance | |
516 | @param cmd: Shell command to execute. |
|
516 | @param cmd: Shell command to execute. | |
517 | @type cmd: string |
|
517 | @type cmd: string | |
518 | ''' |
|
518 | ''' | |
519 | stdin, stdout = os.popen4(cmd) |
|
519 | stdin, stdout = os.popen4(cmd) | |
520 | result = stdout.read().decode('cp437').\ |
|
520 | result = stdout.read().decode('cp437').\ | |
521 | encode(locale.getpreferredencoding()) |
|
521 | encode(locale.getpreferredencoding()) | |
522 | #we use print command because the shell command is called |
|
522 | #we use print command because the shell command is called | |
523 | #inside IPython instance and thus is redirected to thread cout |
|
523 | #inside IPython instance and thus is redirected to thread cout | |
524 | #"\x01\x1b[1;36m\x02" <-- add colour to the text... |
|
524 | #"\x01\x1b[1;36m\x02" <-- add colour to the text... | |
525 | print "\x01\x1b[1;36m\x02"+result |
|
525 | print "\x01\x1b[1;36m\x02"+result | |
526 | stdout.close() |
|
526 | stdout.close() | |
527 | stdin.close() |
|
527 | stdin.close() |
@@ -1,171 +1,171 b'' | |||||
1 | # encoding: utf-8 |
|
1 | # encoding: utf-8 | |
2 |
|
2 | |||
3 | """Magic command interface for interactive parallel work.""" |
|
3 | """Magic command interface for interactive parallel work.""" | |
4 |
|
4 | |||
5 | __docformat__ = "restructuredtext en" |
|
5 | __docformat__ = "restructuredtext en" | |
6 |
|
6 | |||
7 | #------------------------------------------------------------------------------- |
|
7 | #------------------------------------------------------------------------------- | |
8 | # Copyright (C) 2008 The IPython Development Team |
|
8 | # Copyright (C) 2008 The IPython Development Team | |
9 | # |
|
9 | # | |
10 | # Distributed under the terms of the BSD License. The full license is in |
|
10 | # Distributed under the terms of the BSD License. The full license is in | |
11 | # the file COPYING, distributed as part of this software. |
|
11 | # the file COPYING, distributed as part of this software. | |
12 | #------------------------------------------------------------------------------- |
|
12 | #------------------------------------------------------------------------------- | |
13 |
|
13 | |||
14 | #------------------------------------------------------------------------------- |
|
14 | #------------------------------------------------------------------------------- | |
15 | # Imports |
|
15 | # Imports | |
16 | #------------------------------------------------------------------------------- |
|
16 | #------------------------------------------------------------------------------- | |
17 |
|
17 | |||
18 | import new |
|
18 | import new | |
19 |
|
19 | |||
20 | from IPython.core.iplib import InteractiveShell |
|
20 | from IPython.core.iplib import InteractiveShell | |
21 |
from IPython. |
|
21 | from IPython.core.shell import MTInteractiveShell | |
22 |
|
22 | |||
23 | from twisted.internet.defer import Deferred |
|
23 | from twisted.internet.defer import Deferred | |
24 |
|
24 | |||
25 |
|
25 | |||
26 | #------------------------------------------------------------------------------- |
|
26 | #------------------------------------------------------------------------------- | |
27 | # Definitions of magic functions for use with IPython |
|
27 | # Definitions of magic functions for use with IPython | |
28 | #------------------------------------------------------------------------------- |
|
28 | #------------------------------------------------------------------------------- | |
29 |
|
29 | |||
30 | NO_ACTIVE_CONTROLLER = """ |
|
30 | NO_ACTIVE_CONTROLLER = """ | |
31 | Error: No Controller is activated |
|
31 | Error: No Controller is activated | |
32 | Use activate() on a RemoteController object to activate it for magics. |
|
32 | Use activate() on a RemoteController object to activate it for magics. | |
33 | """ |
|
33 | """ | |
34 |
|
34 | |||
35 | def magic_result(self,parameter_s=''): |
|
35 | def magic_result(self,parameter_s=''): | |
36 | """Print the result of command i on all engines of the active controller. |
|
36 | """Print the result of command i on all engines of the active controller. | |
37 |
|
37 | |||
38 | To activate a controller in IPython, first create it and then call |
|
38 | To activate a controller in IPython, first create it and then call | |
39 | the activate() method. |
|
39 | the activate() method. | |
40 |
|
40 | |||
41 | Then you can do the following: |
|
41 | Then you can do the following: | |
42 |
|
42 | |||
43 | >>> result # Print the latest result |
|
43 | >>> result # Print the latest result | |
44 | Printing result... |
|
44 | Printing result... | |
45 | [127.0.0.1:0] In [1]: b = 10 |
|
45 | [127.0.0.1:0] In [1]: b = 10 | |
46 | [127.0.0.1:1] In [1]: b = 10 |
|
46 | [127.0.0.1:1] In [1]: b = 10 | |
47 |
|
47 | |||
48 | >>> result 0 # Print result 0 |
|
48 | >>> result 0 # Print result 0 | |
49 | In [14]: result 0 |
|
49 | In [14]: result 0 | |
50 | Printing result... |
|
50 | Printing result... | |
51 | [127.0.0.1:0] In [0]: a = 5 |
|
51 | [127.0.0.1:0] In [0]: a = 5 | |
52 | [127.0.0.1:1] In [0]: a = 5 |
|
52 | [127.0.0.1:1] In [0]: a = 5 | |
53 | """ |
|
53 | """ | |
54 | try: |
|
54 | try: | |
55 | activeController = __IPYTHON__.activeController |
|
55 | activeController = __IPYTHON__.activeController | |
56 | except AttributeError: |
|
56 | except AttributeError: | |
57 | print NO_ACTIVE_CONTROLLER |
|
57 | print NO_ACTIVE_CONTROLLER | |
58 | else: |
|
58 | else: | |
59 | try: |
|
59 | try: | |
60 | index = int(parameter_s) |
|
60 | index = int(parameter_s) | |
61 | except: |
|
61 | except: | |
62 | index = None |
|
62 | index = None | |
63 | result = activeController.get_result(index) |
|
63 | result = activeController.get_result(index) | |
64 | return result |
|
64 | return result | |
65 |
|
65 | |||
66 | def magic_px(self,parameter_s=''): |
|
66 | def magic_px(self,parameter_s=''): | |
67 | """Executes the given python command on the active IPython Controller. |
|
67 | """Executes the given python command on the active IPython Controller. | |
68 |
|
68 | |||
69 | To activate a Controller in IPython, first create it and then call |
|
69 | To activate a Controller in IPython, first create it and then call | |
70 | the activate() method. |
|
70 | the activate() method. | |
71 |
|
71 | |||
72 | Then you can do the following: |
|
72 | Then you can do the following: | |
73 |
|
73 | |||
74 | >>> %px a = 5 # Runs a = 5 on all nodes |
|
74 | >>> %px a = 5 # Runs a = 5 on all nodes | |
75 | """ |
|
75 | """ | |
76 |
|
76 | |||
77 | try: |
|
77 | try: | |
78 | activeController = __IPYTHON__.activeController |
|
78 | activeController = __IPYTHON__.activeController | |
79 | except AttributeError: |
|
79 | except AttributeError: | |
80 | print NO_ACTIVE_CONTROLLER |
|
80 | print NO_ACTIVE_CONTROLLER | |
81 | else: |
|
81 | else: | |
82 | print "Parallel execution on engines: %s" % activeController.targets |
|
82 | print "Parallel execution on engines: %s" % activeController.targets | |
83 | result = activeController.execute(parameter_s) |
|
83 | result = activeController.execute(parameter_s) | |
84 | return result |
|
84 | return result | |
85 |
|
85 | |||
86 | def pxrunsource(self, source, filename="<input>", symbol="single"): |
|
86 | def pxrunsource(self, source, filename="<input>", symbol="single"): | |
87 |
|
87 | |||
88 | try: |
|
88 | try: | |
89 | code = self.compile(source, filename, symbol) |
|
89 | code = self.compile(source, filename, symbol) | |
90 | except (OverflowError, SyntaxError, ValueError): |
|
90 | except (OverflowError, SyntaxError, ValueError): | |
91 | # Case 1 |
|
91 | # Case 1 | |
92 | self.showsyntaxerror(filename) |
|
92 | self.showsyntaxerror(filename) | |
93 | return None |
|
93 | return None | |
94 |
|
94 | |||
95 | if code is None: |
|
95 | if code is None: | |
96 | # Case 2 |
|
96 | # Case 2 | |
97 | return True |
|
97 | return True | |
98 |
|
98 | |||
99 | # Case 3 |
|
99 | # Case 3 | |
100 | # Because autopx is enabled, we now call executeAll or disable autopx if |
|
100 | # Because autopx is enabled, we now call executeAll or disable autopx if | |
101 | # %autopx or autopx has been called |
|
101 | # %autopx or autopx has been called | |
102 | if '_ip.magic("%autopx' in source or '_ip.magic("autopx' in source: |
|
102 | if '_ip.magic("%autopx' in source or '_ip.magic("autopx' in source: | |
103 | _disable_autopx(self) |
|
103 | _disable_autopx(self) | |
104 | return False |
|
104 | return False | |
105 | else: |
|
105 | else: | |
106 | try: |
|
106 | try: | |
107 | result = self.activeController.execute(source) |
|
107 | result = self.activeController.execute(source) | |
108 | except: |
|
108 | except: | |
109 | self.showtraceback() |
|
109 | self.showtraceback() | |
110 | else: |
|
110 | else: | |
111 | print result.__repr__() |
|
111 | print result.__repr__() | |
112 | return False |
|
112 | return False | |
113 |
|
113 | |||
114 | def magic_autopx(self, parameter_s=''): |
|
114 | def magic_autopx(self, parameter_s=''): | |
115 | """Toggles auto parallel mode for the active IPython Controller. |
|
115 | """Toggles auto parallel mode for the active IPython Controller. | |
116 |
|
116 | |||
117 | To activate a Controller in IPython, first create it and then call |
|
117 | To activate a Controller in IPython, first create it and then call | |
118 | the activate() method. |
|
118 | the activate() method. | |
119 |
|
119 | |||
120 | Then you can do the following: |
|
120 | Then you can do the following: | |
121 |
|
121 | |||
122 | >>> %autopx # Now all commands are executed in parallel |
|
122 | >>> %autopx # Now all commands are executed in parallel | |
123 | Auto Parallel Enabled |
|
123 | Auto Parallel Enabled | |
124 | Type %autopx to disable |
|
124 | Type %autopx to disable | |
125 | ... |
|
125 | ... | |
126 | >>> %autopx # Now all commands are locally executed |
|
126 | >>> %autopx # Now all commands are locally executed | |
127 | Auto Parallel Disabled |
|
127 | Auto Parallel Disabled | |
128 | """ |
|
128 | """ | |
129 |
|
129 | |||
130 | if hasattr(self, 'autopx'): |
|
130 | if hasattr(self, 'autopx'): | |
131 | if self.autopx == True: |
|
131 | if self.autopx == True: | |
132 | _disable_autopx(self) |
|
132 | _disable_autopx(self) | |
133 | else: |
|
133 | else: | |
134 | _enable_autopx(self) |
|
134 | _enable_autopx(self) | |
135 | else: |
|
135 | else: | |
136 | _enable_autopx(self) |
|
136 | _enable_autopx(self) | |
137 |
|
137 | |||
138 | def _enable_autopx(self): |
|
138 | def _enable_autopx(self): | |
139 | """Enable %autopx mode by saving the original runsource and installing |
|
139 | """Enable %autopx mode by saving the original runsource and installing | |
140 | pxrunsource. |
|
140 | pxrunsource. | |
141 | """ |
|
141 | """ | |
142 | try: |
|
142 | try: | |
143 | activeController = __IPYTHON__.activeController |
|
143 | activeController = __IPYTHON__.activeController | |
144 | except AttributeError: |
|
144 | except AttributeError: | |
145 | print "No active RemoteController found, use RemoteController.activate()." |
|
145 | print "No active RemoteController found, use RemoteController.activate()." | |
146 | else: |
|
146 | else: | |
147 | self._original_runsource = self.runsource |
|
147 | self._original_runsource = self.runsource | |
148 | self.runsource = new.instancemethod(pxrunsource, self, self.__class__) |
|
148 | self.runsource = new.instancemethod(pxrunsource, self, self.__class__) | |
149 | self.autopx = True |
|
149 | self.autopx = True | |
150 | print "Auto Parallel Enabled\nType %autopx to disable" |
|
150 | print "Auto Parallel Enabled\nType %autopx to disable" | |
151 |
|
151 | |||
152 | def _disable_autopx(self): |
|
152 | def _disable_autopx(self): | |
153 | """Disable %autopx by restoring the original runsource.""" |
|
153 | """Disable %autopx by restoring the original runsource.""" | |
154 | if hasattr(self, 'autopx'): |
|
154 | if hasattr(self, 'autopx'): | |
155 | if self.autopx == True: |
|
155 | if self.autopx == True: | |
156 | self.runsource = self._original_runsource |
|
156 | self.runsource = self._original_runsource | |
157 | self.autopx = False |
|
157 | self.autopx = False | |
158 | print "Auto Parallel Disabled" |
|
158 | print "Auto Parallel Disabled" | |
159 |
|
159 | |||
160 | # Add the new magic function to the class dict: |
|
160 | # Add the new magic function to the class dict: | |
161 |
|
161 | |||
162 | InteractiveShell.magic_result = magic_result |
|
162 | InteractiveShell.magic_result = magic_result | |
163 | InteractiveShell.magic_px = magic_px |
|
163 | InteractiveShell.magic_px = magic_px | |
164 | InteractiveShell.magic_autopx = magic_autopx |
|
164 | InteractiveShell.magic_autopx = magic_autopx | |
165 |
|
165 | |||
166 | # And remove the global name to keep global namespace clean. Don't worry, the |
|
166 | # And remove the global name to keep global namespace clean. Don't worry, the | |
167 | # copy bound to IPython stays, we're just removing the global name. |
|
167 | # copy bound to IPython stays, we're just removing the global name. | |
168 | del magic_result |
|
168 | del magic_result | |
169 | del magic_px |
|
169 | del magic_px | |
170 | del magic_autopx |
|
170 | del magic_autopx | |
171 |
|
171 |
@@ -1,300 +1,300 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 | """IPython Test Suite Runner. |
|
2 | """IPython Test Suite Runner. | |
3 |
|
3 | |||
4 | This module provides a main entry point to a user script to test IPython |
|
4 | This module provides a main entry point to a user script to test IPython | |
5 | itself from the command line. There are two ways of running this script: |
|
5 | itself from the command line. There are two ways of running this script: | |
6 |
|
6 | |||
7 | 1. With the syntax `iptest all`. This runs our entire test suite by |
|
7 | 1. With the syntax `iptest all`. This runs our entire test suite by | |
8 | calling this script (with different arguments) or trial recursively. This |
|
8 | calling this script (with different arguments) or trial recursively. This | |
9 | causes modules and package to be tested in different processes, using nose |
|
9 | causes modules and package to be tested in different processes, using nose | |
10 | or trial where appropriate. |
|
10 | or trial where appropriate. | |
11 | 2. With the regular nose syntax, like `iptest -vvs IPython`. In this form |
|
11 | 2. With the regular nose syntax, like `iptest -vvs IPython`. In this form | |
12 | the script simply calls nose, but with special command line flags and |
|
12 | the script simply calls nose, but with special command line flags and | |
13 | plugins loaded. |
|
13 | plugins loaded. | |
14 |
|
14 | |||
15 | For now, this script requires that both nose and twisted are installed. This |
|
15 | For now, this script requires that both nose and twisted are installed. This | |
16 | will change in the future. |
|
16 | will change in the future. | |
17 | """ |
|
17 | """ | |
18 |
|
18 | |||
19 | #----------------------------------------------------------------------------- |
|
19 | #----------------------------------------------------------------------------- | |
20 | # Module imports |
|
20 | # Module imports | |
21 | #----------------------------------------------------------------------------- |
|
21 | #----------------------------------------------------------------------------- | |
22 |
|
22 | |||
23 | import os |
|
23 | import os | |
24 | import os.path as path |
|
24 | import os.path as path | |
25 | import sys |
|
25 | import sys | |
26 | import subprocess |
|
26 | import subprocess | |
27 | import time |
|
27 | import time | |
28 | import warnings |
|
28 | import warnings | |
29 |
|
29 | |||
30 | import nose.plugins.builtin |
|
30 | import nose.plugins.builtin | |
31 | from nose.core import TestProgram |
|
31 | from nose.core import TestProgram | |
32 |
|
32 | |||
33 | from IPython.utils.platutils import find_cmd |
|
33 | from IPython.utils.platutils import find_cmd | |
34 | from IPython.testing.plugin.ipdoctest import IPythonDoctest |
|
34 | from IPython.testing.plugin.ipdoctest import IPythonDoctest | |
35 |
|
35 | |||
36 | pjoin = path.join |
|
36 | pjoin = path.join | |
37 |
|
37 | |||
38 | #----------------------------------------------------------------------------- |
|
38 | #----------------------------------------------------------------------------- | |
39 | # Logic for skipping doctests |
|
39 | # Logic for skipping doctests | |
40 | #----------------------------------------------------------------------------- |
|
40 | #----------------------------------------------------------------------------- | |
41 |
|
41 | |||
42 | def test_for(mod): |
|
42 | def test_for(mod): | |
43 | """Test to see if mod is importable.""" |
|
43 | """Test to see if mod is importable.""" | |
44 | try: |
|
44 | try: | |
45 | __import__(mod) |
|
45 | __import__(mod) | |
46 | except ImportError: |
|
46 | except ImportError: | |
47 | return False |
|
47 | return False | |
48 | else: |
|
48 | else: | |
49 | return True |
|
49 | return True | |
50 |
|
50 | |||
51 | have_curses = test_for('_curses') |
|
51 | have_curses = test_for('_curses') | |
52 | have_wx = test_for('wx') |
|
52 | have_wx = test_for('wx') | |
53 | have_zi = test_for('zope.interface') |
|
53 | have_zi = test_for('zope.interface') | |
54 | have_twisted = test_for('twisted') |
|
54 | have_twisted = test_for('twisted') | |
55 | have_foolscap = test_for('foolscap') |
|
55 | have_foolscap = test_for('foolscap') | |
56 | have_objc = test_for('objc') |
|
56 | have_objc = test_for('objc') | |
57 | have_pexpect = test_for('pexpect') |
|
57 | have_pexpect = test_for('pexpect') | |
58 |
|
58 | |||
59 | # For the IPythonDoctest plugin, we need to exclude certain patterns that cause |
|
59 | # For the IPythonDoctest plugin, we need to exclude certain patterns that cause | |
60 | # testing problems. We should strive to minimize the number of skipped |
|
60 | # testing problems. We should strive to minimize the number of skipped | |
61 | # modules, since this means untested code. As the testing machinery |
|
61 | # modules, since this means untested code. As the testing machinery | |
62 | # solidifies, this list should eventually become empty. |
|
62 | # solidifies, this list should eventually become empty. | |
63 | EXCLUDE = [pjoin('IPython', 'external'), |
|
63 | EXCLUDE = [pjoin('IPython', 'external'), | |
64 | pjoin('IPython', 'frontend', 'process', 'winprocess.py'), |
|
64 | pjoin('IPython', 'frontend', 'process', 'winprocess.py'), | |
65 | pjoin('IPython_doctest_plugin'), |
|
65 | pjoin('IPython_doctest_plugin'), | |
66 | pjoin('IPython', 'Gnuplot'), |
|
66 | pjoin('IPython', 'Gnuplot'), | |
67 | pjoin('IPython', 'Extensions', 'ipy_'), |
|
67 | pjoin('IPython', 'Extensions', 'ipy_'), | |
68 | pjoin('IPython', 'Extensions', 'clearcmd'), |
|
68 | pjoin('IPython', 'Extensions', 'clearcmd'), | |
69 | pjoin('IPython', 'Extensions', 'PhysicalQInteractive'), |
|
69 | pjoin('IPython', 'Extensions', 'PhysicalQInteractive'), | |
70 | pjoin('IPython', 'Extensions', 'scitedirector'), |
|
70 | pjoin('IPython', 'Extensions', 'scitedirector'), | |
71 | pjoin('IPython', 'Extensions', 'numeric_formats'), |
|
71 | pjoin('IPython', 'Extensions', 'numeric_formats'), | |
72 | pjoin('IPython', 'testing', 'attic'), |
|
72 | pjoin('IPython', 'testing', 'attic'), | |
73 | pjoin('IPython', 'testing', 'tutils'), |
|
73 | pjoin('IPython', 'testing', 'tutils'), | |
74 | pjoin('IPython', 'testing', 'tools'), |
|
74 | pjoin('IPython', 'testing', 'tools'), | |
75 | pjoin('IPython', 'testing', 'mkdoctests') |
|
75 | pjoin('IPython', 'testing', 'mkdoctests') | |
76 | ] |
|
76 | ] | |
77 |
|
77 | |||
78 | if not have_wx: |
|
78 | if not have_wx: | |
79 | EXCLUDE.append(pjoin('IPython', 'Extensions', 'igrid')) |
|
79 | EXCLUDE.append(pjoin('IPython', 'Extensions', 'igrid')) | |
80 | EXCLUDE.append(pjoin('IPython', 'gui')) |
|
80 | EXCLUDE.append(pjoin('IPython', 'gui')) | |
81 | EXCLUDE.append(pjoin('IPython', 'frontend', 'wx')) |
|
81 | EXCLUDE.append(pjoin('IPython', 'frontend', 'wx')) | |
82 |
|
82 | |||
83 | if not have_objc: |
|
83 | if not have_objc: | |
84 | EXCLUDE.append(pjoin('IPython', 'frontend', 'cocoa')) |
|
84 | EXCLUDE.append(pjoin('IPython', 'frontend', 'cocoa')) | |
85 |
|
85 | |||
86 | if not have_curses: |
|
86 | if not have_curses: | |
87 | EXCLUDE.append(pjoin('IPython', 'Extensions', 'ibrowse')) |
|
87 | EXCLUDE.append(pjoin('IPython', 'Extensions', 'ibrowse')) | |
88 |
|
88 | |||
89 | if not sys.platform == 'win32': |
|
89 | if not sys.platform == 'win32': | |
90 | EXCLUDE.append(pjoin('IPython', 'platutils_win32')) |
|
90 | EXCLUDE.append(pjoin('IPython', 'platutils_win32')) | |
91 |
|
91 | |||
92 | # These have to be skipped on win32 because the use echo, rm, cd, etc. |
|
92 | # These have to be skipped on win32 because the use echo, rm, cd, etc. | |
93 | # See ticket https://bugs.launchpad.net/bugs/366982 |
|
93 | # See ticket https://bugs.launchpad.net/bugs/366982 | |
94 | if sys.platform == 'win32': |
|
94 | if sys.platform == 'win32': | |
95 | EXCLUDE.append(pjoin('IPython', 'testing', 'plugin', 'test_exampleip')) |
|
95 | EXCLUDE.append(pjoin('IPython', 'testing', 'plugin', 'test_exampleip')) | |
96 | EXCLUDE.append(pjoin('IPython', 'testing', 'plugin', 'dtexample')) |
|
96 | EXCLUDE.append(pjoin('IPython', 'testing', 'plugin', 'dtexample')) | |
97 |
|
97 | |||
98 | if not os.name == 'posix': |
|
98 | if not os.name == 'posix': | |
99 | EXCLUDE.append(pjoin('IPython', 'platutils_posix')) |
|
99 | EXCLUDE.append(pjoin('IPython', 'platutils_posix')) | |
100 |
|
100 | |||
101 | if not have_pexpect: |
|
101 | if not have_pexpect: | |
102 | EXCLUDE.append(pjoin('IPython', 'lib', 'irunner')) |
|
102 | EXCLUDE.append(pjoin('IPython', 'lib', 'irunner')) | |
103 |
|
103 | |||
104 | # This is needed for the reg-exp to match on win32 in the ipdoctest plugin. |
|
104 | # This is needed for the reg-exp to match on win32 in the ipdoctest plugin. | |
105 | if sys.platform == 'win32': |
|
105 | if sys.platform == 'win32': | |
106 | EXCLUDE = [s.replace('\\','\\\\') for s in EXCLUDE] |
|
106 | EXCLUDE = [s.replace('\\','\\\\') for s in EXCLUDE] | |
107 |
|
107 | |||
108 |
|
108 | |||
109 | #----------------------------------------------------------------------------- |
|
109 | #----------------------------------------------------------------------------- | |
110 | # Functions and classes |
|
110 | # Functions and classes | |
111 | #----------------------------------------------------------------------------- |
|
111 | #----------------------------------------------------------------------------- | |
112 |
|
112 | |||
113 | def run_iptest(): |
|
113 | def run_iptest(): | |
114 | """Run the IPython test suite using nose. |
|
114 | """Run the IPython test suite using nose. | |
115 |
|
115 | |||
116 | This function is called when this script is **not** called with the form |
|
116 | This function is called when this script is **not** called with the form | |
117 | `iptest all`. It simply calls nose with appropriate command line flags |
|
117 | `iptest all`. It simply calls nose with appropriate command line flags | |
118 | and accepts all of the standard nose arguments. |
|
118 | and accepts all of the standard nose arguments. | |
119 | """ |
|
119 | """ | |
120 |
|
120 | |||
121 | warnings.filterwarnings('ignore', |
|
121 | warnings.filterwarnings('ignore', | |
122 | 'This will be removed soon. Use IPython.testing.util instead') |
|
122 | 'This will be removed soon. Use IPython.testing.util instead') | |
123 |
|
123 | |||
124 | argv = sys.argv + [ |
|
124 | argv = sys.argv + [ | |
125 | # Loading ipdoctest causes problems with Twisted. |
|
125 | # Loading ipdoctest causes problems with Twisted. | |
126 | # I am removing this as a temporary fix to get the |
|
126 | # I am removing this as a temporary fix to get the | |
127 | # test suite back into working shape. Our nose |
|
127 | # test suite back into working shape. Our nose | |
128 | # plugin needs to be gone through with a fine |
|
128 | # plugin needs to be gone through with a fine | |
129 | # toothed comb to find what is causing the problem. |
|
129 | # toothed comb to find what is causing the problem. | |
130 | '--with-ipdoctest', |
|
130 | '--with-ipdoctest', | |
131 | '--ipdoctest-tests','--ipdoctest-extension=txt', |
|
131 | '--ipdoctest-tests','--ipdoctest-extension=txt', | |
132 | '--detailed-errors', |
|
132 | '--detailed-errors', | |
133 |
|
133 | |||
134 | # We add --exe because of setuptools' imbecility (it |
|
134 | # We add --exe because of setuptools' imbecility (it | |
135 | # blindly does chmod +x on ALL files). Nose does the |
|
135 | # blindly does chmod +x on ALL files). Nose does the | |
136 | # right thing and it tries to avoid executables, |
|
136 | # right thing and it tries to avoid executables, | |
137 | # setuptools unfortunately forces our hand here. This |
|
137 | # setuptools unfortunately forces our hand here. This | |
138 | # has been discussed on the distutils list and the |
|
138 | # has been discussed on the distutils list and the | |
139 | # setuptools devs refuse to fix this problem! |
|
139 | # setuptools devs refuse to fix this problem! | |
140 | '--exe', |
|
140 | '--exe', | |
141 | ] |
|
141 | ] | |
142 |
|
142 | |||
143 | # Detect if any tests were required by explicitly calling an IPython |
|
143 | # Detect if any tests were required by explicitly calling an IPython | |
144 | # submodule or giving a specific path |
|
144 | # submodule or giving a specific path | |
145 | has_tests = False |
|
145 | has_tests = False | |
146 | for arg in sys.argv: |
|
146 | for arg in sys.argv: | |
147 | if 'IPython' in arg or arg.endswith('.py') or \ |
|
147 | if 'IPython' in arg or arg.endswith('.py') or \ | |
148 | (':' in arg and '.py' in arg): |
|
148 | (':' in arg and '.py' in arg): | |
149 | has_tests = True |
|
149 | has_tests = True | |
150 | break |
|
150 | break | |
151 |
|
151 | |||
152 | # If nothing was specifically requested, test full IPython |
|
152 | # If nothing was specifically requested, test full IPython | |
153 | if not has_tests: |
|
153 | if not has_tests: | |
154 | argv.append('IPython') |
|
154 | argv.append('IPython') | |
155 |
|
155 | |||
156 | # Construct list of plugins, omitting the existing doctest plugin, which |
|
156 | # Construct list of plugins, omitting the existing doctest plugin, which | |
157 | # ours replaces (and extends). |
|
157 | # ours replaces (and extends). | |
158 | plugins = [IPythonDoctest(EXCLUDE)] |
|
158 | plugins = [IPythonDoctest(EXCLUDE)] | |
159 | for p in nose.plugins.builtin.plugins: |
|
159 | for p in nose.plugins.builtin.plugins: | |
160 | plug = p() |
|
160 | plug = p() | |
161 | if plug.name == 'doctest': |
|
161 | if plug.name == 'doctest': | |
162 | continue |
|
162 | continue | |
163 |
|
163 | |||
164 | #print '*** adding plugin:',plug.name # dbg |
|
164 | #print '*** adding plugin:',plug.name # dbg | |
165 | plugins.append(plug) |
|
165 | plugins.append(plug) | |
166 |
|
166 | |||
167 | TestProgram(argv=argv,plugins=plugins) |
|
167 | TestProgram(argv=argv,plugins=plugins) | |
168 |
|
168 | |||
169 |
|
169 | |||
170 | class IPTester(object): |
|
170 | class IPTester(object): | |
171 | """Call that calls iptest or trial in a subprocess. |
|
171 | """Call that calls iptest or trial in a subprocess. | |
172 | """ |
|
172 | """ | |
173 | def __init__(self,runner='iptest',params=None): |
|
173 | def __init__(self,runner='iptest',params=None): | |
174 | """ """ |
|
174 | """ """ | |
175 | if runner == 'iptest': |
|
175 | if runner == 'iptest': | |
176 | self.runner = ['iptest','-v'] |
|
176 | self.runner = ['iptest','-v'] | |
177 | else: |
|
177 | else: | |
178 | self.runner = [find_cmd('trial')] |
|
178 | self.runner = [find_cmd('trial')] | |
179 | if params is None: |
|
179 | if params is None: | |
180 | params = [] |
|
180 | params = [] | |
181 | if isinstance(params,str): |
|
181 | if isinstance(params,str): | |
182 | params = [params] |
|
182 | params = [params] | |
183 | self.params = params |
|
183 | self.params = params | |
184 |
|
184 | |||
185 | # Assemble call |
|
185 | # Assemble call | |
186 | self.call_args = self.runner+self.params |
|
186 | self.call_args = self.runner+self.params | |
187 |
|
187 | |||
188 | def run(self): |
|
188 | def run(self): | |
189 | """Run the stored commands""" |
|
189 | """Run the stored commands""" | |
190 | return subprocess.call(self.call_args) |
|
190 | return subprocess.call(self.call_args) | |
191 |
|
191 | |||
192 |
|
192 | |||
193 | def make_runners(): |
|
193 | def make_runners(): | |
194 | """Define the modules and packages that need to be tested. |
|
194 | """Define the modules and packages that need to be tested. | |
195 | """ |
|
195 | """ | |
196 |
|
196 | |||
197 | # This omits additional top-level modules that should not be doctested. |
|
197 | # This omits additional top-level modules that should not be doctested. | |
198 |
# XXX: |
|
198 | # XXX: shell.py is also ommited because of a bug in the skip_doctest | |
199 | # decorator. See ticket https://bugs.launchpad.net/bugs/366209 |
|
199 | # decorator. See ticket https://bugs.launchpad.net/bugs/366209 | |
200 | top_mod = \ |
|
200 | top_mod = \ | |
201 | ['backgroundjobs.py', 'coloransi.py', 'completer.py', 'configloader.py', |
|
201 | ['backgroundjobs.py', 'coloransi.py', 'completer.py', 'configloader.py', | |
202 | 'crashhandler.py', 'debugger.py', 'deepreload.py', 'demo.py', |
|
202 | 'crashhandler.py', 'debugger.py', 'deepreload.py', 'demo.py', | |
203 | 'DPyGetOpt.py', 'dtutils.py', 'excolors.py', 'fakemodule.py', |
|
203 | 'DPyGetOpt.py', 'dtutils.py', 'excolors.py', 'fakemodule.py', | |
204 | 'generics.py', 'genutils.py', 'history.py', 'hooks.py', 'ipapi.py', |
|
204 | 'generics.py', 'genutils.py', 'history.py', 'hooks.py', 'ipapi.py', | |
205 | 'iplib.py', 'ipmaker.py', 'ipstruct.py', 'Itpl.py', |
|
205 | 'iplib.py', 'ipmaker.py', 'ipstruct.py', 'Itpl.py', | |
206 | 'logger.py', 'macro.py', 'magic.py', 'oinspect.py', |
|
206 | 'logger.py', 'macro.py', 'magic.py', 'oinspect.py', | |
207 | 'outputtrap.py', 'platutils.py', 'prefilter.py', 'prompts.py', |
|
207 | 'outputtrap.py', 'platutils.py', 'prefilter.py', 'prompts.py', | |
208 | 'PyColorize.py', 'release.py', 'rlineimpl.py', 'shadowns.py', |
|
208 | 'PyColorize.py', 'release.py', 'rlineimpl.py', 'shadowns.py', | |
209 | 'shellglobals.py', 'strdispatch.py', 'twshell.py', |
|
209 | 'shellglobals.py', 'strdispatch.py', 'twshell.py', | |
210 | 'ultraTB.py', 'upgrade_dir.py', 'usage.py', 'wildcard.py', |
|
210 | 'ultraTB.py', 'upgrade_dir.py', 'usage.py', 'wildcard.py', | |
211 | # See note above for why this is skipped |
|
211 | # See note above for why this is skipped | |
212 |
# ' |
|
212 | # 'shell.py', | |
213 | 'winconsole.py'] |
|
213 | 'winconsole.py'] | |
214 |
|
214 | |||
215 | if have_pexpect: |
|
215 | if have_pexpect: | |
216 | top_mod.append('irunner.py') |
|
216 | top_mod.append('irunner.py') | |
217 |
|
217 | |||
218 | if sys.platform == 'win32': |
|
218 | if sys.platform == 'win32': | |
219 | top_mod.append('platutils_win32.py') |
|
219 | top_mod.append('platutils_win32.py') | |
220 | elif os.name == 'posix': |
|
220 | elif os.name == 'posix': | |
221 | top_mod.append('platutils_posix.py') |
|
221 | top_mod.append('platutils_posix.py') | |
222 | else: |
|
222 | else: | |
223 | top_mod.append('platutils_dummy.py') |
|
223 | top_mod.append('platutils_dummy.py') | |
224 |
|
224 | |||
225 | # These are tested by nose, so skip IPython.kernel |
|
225 | # These are tested by nose, so skip IPython.kernel | |
226 | top_pack = ['config','Extensions','frontend', |
|
226 | top_pack = ['config','Extensions','frontend', | |
227 | 'testing','tests','tools','UserConfig'] |
|
227 | 'testing','tests','tools','UserConfig'] | |
228 |
|
228 | |||
229 | if have_wx: |
|
229 | if have_wx: | |
230 | top_pack.append('gui') |
|
230 | top_pack.append('gui') | |
231 |
|
231 | |||
232 | modules = ['IPython.%s' % m[:-3] for m in top_mod ] |
|
232 | modules = ['IPython.%s' % m[:-3] for m in top_mod ] | |
233 | packages = ['IPython.%s' % m for m in top_pack ] |
|
233 | packages = ['IPython.%s' % m for m in top_pack ] | |
234 |
|
234 | |||
235 | # Make runners |
|
235 | # Make runners | |
236 | runners = dict(zip(top_pack, [IPTester(params=v) for v in packages])) |
|
236 | runners = dict(zip(top_pack, [IPTester(params=v) for v in packages])) | |
237 |
|
237 | |||
238 | # Test IPython.kernel using trial if twisted is installed |
|
238 | # Test IPython.kernel using trial if twisted is installed | |
239 | if have_zi and have_twisted and have_foolscap: |
|
239 | if have_zi and have_twisted and have_foolscap: | |
240 | runners['trial'] = IPTester('trial',['IPython']) |
|
240 | runners['trial'] = IPTester('trial',['IPython']) | |
241 |
|
241 | |||
242 | runners['modules'] = IPTester(params=modules) |
|
242 | runners['modules'] = IPTester(params=modules) | |
243 |
|
243 | |||
244 | return runners |
|
244 | return runners | |
245 |
|
245 | |||
246 |
|
246 | |||
247 | def run_iptestall(): |
|
247 | def run_iptestall(): | |
248 | """Run the entire IPython test suite by calling nose and trial. |
|
248 | """Run the entire IPython test suite by calling nose and trial. | |
249 |
|
249 | |||
250 | This function constructs :class:`IPTester` instances for all IPython |
|
250 | This function constructs :class:`IPTester` instances for all IPython | |
251 | modules and package and then runs each of them. This causes the modules |
|
251 | modules and package and then runs each of them. This causes the modules | |
252 | and packages of IPython to be tested each in their own subprocess using |
|
252 | and packages of IPython to be tested each in their own subprocess using | |
253 | nose or twisted.trial appropriately. |
|
253 | nose or twisted.trial appropriately. | |
254 | """ |
|
254 | """ | |
255 | runners = make_runners() |
|
255 | runners = make_runners() | |
256 | # Run all test runners, tracking execution time |
|
256 | # Run all test runners, tracking execution time | |
257 | failed = {} |
|
257 | failed = {} | |
258 | t_start = time.time() |
|
258 | t_start = time.time() | |
259 | for name,runner in runners.iteritems(): |
|
259 | for name,runner in runners.iteritems(): | |
260 | print '*'*77 |
|
260 | print '*'*77 | |
261 | print 'IPython test set:',name |
|
261 | print 'IPython test set:',name | |
262 | res = runner.run() |
|
262 | res = runner.run() | |
263 | if res: |
|
263 | if res: | |
264 | failed[name] = res |
|
264 | failed[name] = res | |
265 | t_end = time.time() |
|
265 | t_end = time.time() | |
266 | t_tests = t_end - t_start |
|
266 | t_tests = t_end - t_start | |
267 | nrunners = len(runners) |
|
267 | nrunners = len(runners) | |
268 | nfail = len(failed) |
|
268 | nfail = len(failed) | |
269 | # summarize results |
|
269 | # summarize results | |
270 |
|
270 | |||
271 | print '*'*77 |
|
271 | print '*'*77 | |
272 | print 'Ran %s test sets in %.3fs' % (nrunners, t_tests) |
|
272 | print 'Ran %s test sets in %.3fs' % (nrunners, t_tests) | |
273 |
|
273 | |||
274 | if not failed: |
|
274 | if not failed: | |
275 | print 'OK' |
|
275 | print 'OK' | |
276 | else: |
|
276 | else: | |
277 | # If anything went wrong, point out what command to rerun manually to |
|
277 | # If anything went wrong, point out what command to rerun manually to | |
278 | # see the actual errors and individual summary |
|
278 | # see the actual errors and individual summary | |
279 | print 'ERROR - %s out of %s test sets failed.' % (nfail, nrunners) |
|
279 | print 'ERROR - %s out of %s test sets failed.' % (nfail, nrunners) | |
280 | for name in failed: |
|
280 | for name in failed: | |
281 | failed_runner = runners[name] |
|
281 | failed_runner = runners[name] | |
282 | print '-'*40 |
|
282 | print '-'*40 | |
283 | print 'Runner failed:',name |
|
283 | print 'Runner failed:',name | |
284 | print 'You may wish to rerun this one individually, with:' |
|
284 | print 'You may wish to rerun this one individually, with:' | |
285 | print ' '.join(failed_runner.call_args) |
|
285 | print ' '.join(failed_runner.call_args) | |
286 |
|
286 | |||
287 |
|
287 | |||
288 |
|
288 | |||
289 | def main(): |
|
289 | def main(): | |
290 | if len(sys.argv) == 1: |
|
290 | if len(sys.argv) == 1: | |
291 | run_iptestall() |
|
291 | run_iptestall() | |
292 | else: |
|
292 | else: | |
293 | if sys.argv[1] == 'all': |
|
293 | if sys.argv[1] == 'all': | |
294 | run_iptestall() |
|
294 | run_iptestall() | |
295 | else: |
|
295 | else: | |
296 | run_iptest() |
|
296 | run_iptest() | |
297 |
|
297 | |||
298 |
|
298 | |||
299 | if __name__ == '__main__': |
|
299 | if __name__ == '__main__': | |
300 | main() No newline at end of file |
|
300 | main() |
@@ -1,909 +1,909 b'' | |||||
1 | """Nose Plugin that supports IPython doctests. |
|
1 | """Nose Plugin that supports IPython doctests. | |
2 |
|
2 | |||
3 | Limitations: |
|
3 | Limitations: | |
4 |
|
4 | |||
5 | - When generating examples for use as doctests, make sure that you have |
|
5 | - When generating examples for use as doctests, make sure that you have | |
6 | pretty-printing OFF. This can be done either by starting ipython with the |
|
6 | pretty-printing OFF. This can be done either by starting ipython with the | |
7 | flag '--nopprint', by setting pprint to 0 in your ipythonrc file, or by |
|
7 | flag '--nopprint', by setting pprint to 0 in your ipythonrc file, or by | |
8 | interactively disabling it with %Pprint. This is required so that IPython |
|
8 | interactively disabling it with %Pprint. This is required so that IPython | |
9 | output matches that of normal Python, which is used by doctest for internal |
|
9 | output matches that of normal Python, which is used by doctest for internal | |
10 | execution. |
|
10 | execution. | |
11 |
|
11 | |||
12 | - Do not rely on specific prompt numbers for results (such as using |
|
12 | - Do not rely on specific prompt numbers for results (such as using | |
13 | '_34==True', for example). For IPython tests run via an external process the |
|
13 | '_34==True', for example). For IPython tests run via an external process the | |
14 | prompt numbers may be different, and IPython tests run as normal python code |
|
14 | prompt numbers may be different, and IPython tests run as normal python code | |
15 | won't even have these special _NN variables set at all. |
|
15 | won't even have these special _NN variables set at all. | |
16 | """ |
|
16 | """ | |
17 |
|
17 | |||
18 | #----------------------------------------------------------------------------- |
|
18 | #----------------------------------------------------------------------------- | |
19 | # Module imports |
|
19 | # Module imports | |
20 |
|
20 | |||
21 | # From the standard library |
|
21 | # From the standard library | |
22 | import __builtin__ |
|
22 | import __builtin__ | |
23 | import commands |
|
23 | import commands | |
24 | import doctest |
|
24 | import doctest | |
25 | import inspect |
|
25 | import inspect | |
26 | import logging |
|
26 | import logging | |
27 | import os |
|
27 | import os | |
28 | import re |
|
28 | import re | |
29 | import sys |
|
29 | import sys | |
30 | import traceback |
|
30 | import traceback | |
31 | import unittest |
|
31 | import unittest | |
32 |
|
32 | |||
33 | from inspect import getmodule |
|
33 | from inspect import getmodule | |
34 | from StringIO import StringIO |
|
34 | from StringIO import StringIO | |
35 |
|
35 | |||
36 | # We are overriding the default doctest runner, so we need to import a few |
|
36 | # We are overriding the default doctest runner, so we need to import a few | |
37 | # things from doctest directly |
|
37 | # things from doctest directly | |
38 | from doctest import (REPORTING_FLAGS, REPORT_ONLY_FIRST_FAILURE, |
|
38 | from doctest import (REPORTING_FLAGS, REPORT_ONLY_FIRST_FAILURE, | |
39 | _unittest_reportflags, DocTestRunner, |
|
39 | _unittest_reportflags, DocTestRunner, | |
40 | _extract_future_flags, pdb, _OutputRedirectingPdb, |
|
40 | _extract_future_flags, pdb, _OutputRedirectingPdb, | |
41 | _exception_traceback, |
|
41 | _exception_traceback, | |
42 | linecache) |
|
42 | linecache) | |
43 |
|
43 | |||
44 | # Third-party modules |
|
44 | # Third-party modules | |
45 | import nose.core |
|
45 | import nose.core | |
46 |
|
46 | |||
47 | from nose.plugins import doctests, Plugin |
|
47 | from nose.plugins import doctests, Plugin | |
48 | from nose.util import anyp, getpackage, test_address, resolve_name, tolist |
|
48 | from nose.util import anyp, getpackage, test_address, resolve_name, tolist | |
49 |
|
49 | |||
50 | #----------------------------------------------------------------------------- |
|
50 | #----------------------------------------------------------------------------- | |
51 | # Module globals and other constants |
|
51 | # Module globals and other constants | |
52 |
|
52 | |||
53 | log = logging.getLogger(__name__) |
|
53 | log = logging.getLogger(__name__) | |
54 |
|
54 | |||
55 | ########################################################################### |
|
55 | ########################################################################### | |
56 | # *** HACK *** |
|
56 | # *** HACK *** | |
57 | # We must start our own ipython object and heavily muck with it so that all the |
|
57 | # We must start our own ipython object and heavily muck with it so that all the | |
58 | # modifications IPython makes to system behavior don't send the doctest |
|
58 | # modifications IPython makes to system behavior don't send the doctest | |
59 | # machinery into a fit. This code should be considered a gross hack, but it |
|
59 | # machinery into a fit. This code should be considered a gross hack, but it | |
60 | # gets the job done. |
|
60 | # gets the job done. | |
61 |
|
61 | |||
62 | def default_argv(): |
|
62 | def default_argv(): | |
63 | """Return a valid default argv for creating testing instances of ipython""" |
|
63 | """Return a valid default argv for creating testing instances of ipython""" | |
64 |
|
64 | |||
65 | # Get the install directory for the user configuration and tell ipython to |
|
65 | # Get the install directory for the user configuration and tell ipython to | |
66 | # use the default profile from there. |
|
66 | # use the default profile from there. | |
67 | from IPython import UserConfig |
|
67 | from IPython import UserConfig | |
68 | ipcdir = os.path.dirname(UserConfig.__file__) |
|
68 | ipcdir = os.path.dirname(UserConfig.__file__) | |
69 | #ipconf = os.path.join(ipcdir,'ipy_user_conf.py') |
|
69 | #ipconf = os.path.join(ipcdir,'ipy_user_conf.py') | |
70 | ipconf = os.path.join(ipcdir,'ipythonrc') |
|
70 | ipconf = os.path.join(ipcdir,'ipythonrc') | |
71 | #print 'conf:',ipconf # dbg |
|
71 | #print 'conf:',ipconf # dbg | |
72 |
|
72 | |||
73 | return ['--colors=NoColor','--noterm_title','-rcfile=%s' % ipconf] |
|
73 | return ['--colors=NoColor','--noterm_title','-rcfile=%s' % ipconf] | |
74 |
|
74 | |||
75 |
|
75 | |||
76 | # Hack to modify the %run command so we can sync the user's namespace with the |
|
76 | # Hack to modify the %run command so we can sync the user's namespace with the | |
77 | # test globals. Once we move over to a clean magic system, this will be done |
|
77 | # test globals. Once we move over to a clean magic system, this will be done | |
78 | # with much less ugliness. |
|
78 | # with much less ugliness. | |
79 |
|
79 | |||
80 | class py_file_finder(object): |
|
80 | class py_file_finder(object): | |
81 | def __init__(self,test_filename): |
|
81 | def __init__(self,test_filename): | |
82 | self.test_filename = test_filename |
|
82 | self.test_filename = test_filename | |
83 |
|
83 | |||
84 | def __call__(self,name): |
|
84 | def __call__(self,name): | |
85 | from IPython.utils.genutils import get_py_filename |
|
85 | from IPython.utils.genutils import get_py_filename | |
86 | try: |
|
86 | try: | |
87 | return get_py_filename(name) |
|
87 | return get_py_filename(name) | |
88 | except IOError: |
|
88 | except IOError: | |
89 | test_dir = os.path.dirname(self.test_filename) |
|
89 | test_dir = os.path.dirname(self.test_filename) | |
90 | new_path = os.path.join(test_dir,name) |
|
90 | new_path = os.path.join(test_dir,name) | |
91 | return get_py_filename(new_path) |
|
91 | return get_py_filename(new_path) | |
92 |
|
92 | |||
93 |
|
93 | |||
94 | def _run_ns_sync(self,arg_s,runner=None): |
|
94 | def _run_ns_sync(self,arg_s,runner=None): | |
95 | """Modified version of %run that syncs testing namespaces. |
|
95 | """Modified version of %run that syncs testing namespaces. | |
96 |
|
96 | |||
97 | This is strictly needed for running doctests that call %run. |
|
97 | This is strictly needed for running doctests that call %run. | |
98 | """ |
|
98 | """ | |
99 |
|
99 | |||
100 | # When tests call %run directly (not via doctest) these function attributes |
|
100 | # When tests call %run directly (not via doctest) these function attributes | |
101 | # are not set |
|
101 | # are not set | |
102 | try: |
|
102 | try: | |
103 | fname = _run_ns_sync.test_filename |
|
103 | fname = _run_ns_sync.test_filename | |
104 | except AttributeError: |
|
104 | except AttributeError: | |
105 | fname = arg_s |
|
105 | fname = arg_s | |
106 |
|
106 | |||
107 | finder = py_file_finder(fname) |
|
107 | finder = py_file_finder(fname) | |
108 | out = _ip.IP.magic_run_ori(arg_s,runner,finder) |
|
108 | out = _ip.IP.magic_run_ori(arg_s,runner,finder) | |
109 |
|
109 | |||
110 | # Simliarly, there is no test_globs when a test is NOT a doctest |
|
110 | # Simliarly, there is no test_globs when a test is NOT a doctest | |
111 | if hasattr(_run_ns_sync,'test_globs'): |
|
111 | if hasattr(_run_ns_sync,'test_globs'): | |
112 | _run_ns_sync.test_globs.update(_ip.user_ns) |
|
112 | _run_ns_sync.test_globs.update(_ip.user_ns) | |
113 | return out |
|
113 | return out | |
114 |
|
114 | |||
115 |
|
115 | |||
116 | class ipnsdict(dict): |
|
116 | class ipnsdict(dict): | |
117 | """A special subclass of dict for use as an IPython namespace in doctests. |
|
117 | """A special subclass of dict for use as an IPython namespace in doctests. | |
118 |
|
118 | |||
119 | This subclass adds a simple checkpointing capability so that when testing |
|
119 | This subclass adds a simple checkpointing capability so that when testing | |
120 | machinery clears it (we use it as the test execution context), it doesn't |
|
120 | machinery clears it (we use it as the test execution context), it doesn't | |
121 | get completely destroyed. |
|
121 | get completely destroyed. | |
122 | """ |
|
122 | """ | |
123 |
|
123 | |||
124 | def __init__(self,*a): |
|
124 | def __init__(self,*a): | |
125 | dict.__init__(self,*a) |
|
125 | dict.__init__(self,*a) | |
126 | self._savedict = {} |
|
126 | self._savedict = {} | |
127 |
|
127 | |||
128 | def clear(self): |
|
128 | def clear(self): | |
129 | dict.clear(self) |
|
129 | dict.clear(self) | |
130 | self.update(self._savedict) |
|
130 | self.update(self._savedict) | |
131 |
|
131 | |||
132 | def _checkpoint(self): |
|
132 | def _checkpoint(self): | |
133 | self._savedict.clear() |
|
133 | self._savedict.clear() | |
134 | self._savedict.update(self) |
|
134 | self._savedict.update(self) | |
135 |
|
135 | |||
136 | def update(self,other): |
|
136 | def update(self,other): | |
137 | self._checkpoint() |
|
137 | self._checkpoint() | |
138 | dict.update(self,other) |
|
138 | dict.update(self,other) | |
139 |
|
139 | |||
140 | # If '_' is in the namespace, python won't set it when executing code, |
|
140 | # If '_' is in the namespace, python won't set it when executing code, | |
141 | # and we have examples that test it. So we ensure that the namespace |
|
141 | # and we have examples that test it. So we ensure that the namespace | |
142 | # is always 'clean' of it before it's used for test code execution. |
|
142 | # is always 'clean' of it before it's used for test code execution. | |
143 | self.pop('_',None) |
|
143 | self.pop('_',None) | |
144 |
|
144 | |||
145 | # The builtins namespace must *always* be the real __builtin__ module, |
|
145 | # The builtins namespace must *always* be the real __builtin__ module, | |
146 | # else weird stuff happens. The main ipython code does have provisions |
|
146 | # else weird stuff happens. The main ipython code does have provisions | |
147 | # to ensure this after %run, but since in this class we do some |
|
147 | # to ensure this after %run, but since in this class we do some | |
148 | # aggressive low-level cleaning of the execution namespace, we need to |
|
148 | # aggressive low-level cleaning of the execution namespace, we need to | |
149 | # correct for that ourselves, to ensure consitency with the 'real' |
|
149 | # correct for that ourselves, to ensure consitency with the 'real' | |
150 | # ipython. |
|
150 | # ipython. | |
151 | self['__builtins__'] = __builtin__ |
|
151 | self['__builtins__'] = __builtin__ | |
152 |
|
152 | |||
153 |
|
153 | |||
154 | def start_ipython(): |
|
154 | def start_ipython(): | |
155 | """Start a global IPython shell, which we need for IPython-specific syntax. |
|
155 | """Start a global IPython shell, which we need for IPython-specific syntax. | |
156 | """ |
|
156 | """ | |
157 |
|
157 | |||
158 | # This function should only ever run once! |
|
158 | # This function should only ever run once! | |
159 | if hasattr(start_ipython,'already_called'): |
|
159 | if hasattr(start_ipython,'already_called'): | |
160 | return |
|
160 | return | |
161 | start_ipython.already_called = True |
|
161 | start_ipython.already_called = True | |
162 |
|
162 | |||
163 | # Ok, first time we're called, go ahead |
|
163 | # Ok, first time we're called, go ahead | |
164 | import new |
|
164 | import new | |
165 |
|
165 | |||
166 | import IPython |
|
166 | import IPython | |
167 | from IPython.core import ipapi |
|
167 | from IPython.core import ipapi | |
168 |
|
168 | |||
169 | def xsys(cmd): |
|
169 | def xsys(cmd): | |
170 | """Execute a command and print its output. |
|
170 | """Execute a command and print its output. | |
171 |
|
171 | |||
172 | This is just a convenience function to replace the IPython system call |
|
172 | This is just a convenience function to replace the IPython system call | |
173 | with one that is more doctest-friendly. |
|
173 | with one that is more doctest-friendly. | |
174 | """ |
|
174 | """ | |
175 | cmd = _ip.IP.var_expand(cmd,depth=1) |
|
175 | cmd = _ip.IP.var_expand(cmd,depth=1) | |
176 | sys.stdout.write(commands.getoutput(cmd)) |
|
176 | sys.stdout.write(commands.getoutput(cmd)) | |
177 | sys.stdout.flush() |
|
177 | sys.stdout.flush() | |
178 |
|
178 | |||
179 | # Store certain global objects that IPython modifies |
|
179 | # Store certain global objects that IPython modifies | |
180 | _displayhook = sys.displayhook |
|
180 | _displayhook = sys.displayhook | |
181 | _excepthook = sys.excepthook |
|
181 | _excepthook = sys.excepthook | |
182 | _main = sys.modules.get('__main__') |
|
182 | _main = sys.modules.get('__main__') | |
183 |
|
183 | |||
184 | argv = default_argv() |
|
184 | argv = default_argv() | |
185 |
|
185 | |||
186 | # Start IPython instance. We customize it to start with minimal frills. |
|
186 | # Start IPython instance. We customize it to start with minimal frills. | |
187 | user_ns,global_ns = ipapi.make_user_namespaces(ipnsdict(),dict()) |
|
187 | user_ns,global_ns = ipapi.make_user_namespaces(ipnsdict(),dict()) | |
188 |
IPython. |
|
188 | IPython.shell.IPShell(argv,user_ns,global_ns) | |
189 |
|
189 | |||
190 | # Deactivate the various python system hooks added by ipython for |
|
190 | # Deactivate the various python system hooks added by ipython for | |
191 | # interactive convenience so we don't confuse the doctest system |
|
191 | # interactive convenience so we don't confuse the doctest system | |
192 | sys.modules['__main__'] = _main |
|
192 | sys.modules['__main__'] = _main | |
193 | sys.displayhook = _displayhook |
|
193 | sys.displayhook = _displayhook | |
194 | sys.excepthook = _excepthook |
|
194 | sys.excepthook = _excepthook | |
195 |
|
195 | |||
196 | # So that ipython magics and aliases can be doctested (they work by making |
|
196 | # So that ipython magics and aliases can be doctested (they work by making | |
197 | # a call into a global _ip object) |
|
197 | # a call into a global _ip object) | |
198 | _ip = ipapi.get() |
|
198 | _ip = ipapi.get() | |
199 | __builtin__._ip = _ip |
|
199 | __builtin__._ip = _ip | |
200 |
|
200 | |||
201 | # Modify the IPython system call with one that uses getoutput, so that we |
|
201 | # Modify the IPython system call with one that uses getoutput, so that we | |
202 | # can capture subcommands and print them to Python's stdout, otherwise the |
|
202 | # can capture subcommands and print them to Python's stdout, otherwise the | |
203 | # doctest machinery would miss them. |
|
203 | # doctest machinery would miss them. | |
204 | _ip.system = xsys |
|
204 | _ip.system = xsys | |
205 |
|
205 | |||
206 | # Also patch our %run function in. |
|
206 | # Also patch our %run function in. | |
207 | im = new.instancemethod(_run_ns_sync,_ip.IP, _ip.IP.__class__) |
|
207 | im = new.instancemethod(_run_ns_sync,_ip.IP, _ip.IP.__class__) | |
208 | _ip.IP.magic_run_ori = _ip.IP.magic_run |
|
208 | _ip.IP.magic_run_ori = _ip.IP.magic_run | |
209 | _ip.IP.magic_run = im |
|
209 | _ip.IP.magic_run = im | |
210 |
|
210 | |||
211 | # The start call MUST be made here. I'm not sure yet why it doesn't work if |
|
211 | # The start call MUST be made here. I'm not sure yet why it doesn't work if | |
212 | # it is made later, at plugin initialization time, but in all my tests, that's |
|
212 | # it is made later, at plugin initialization time, but in all my tests, that's | |
213 | # the case. |
|
213 | # the case. | |
214 | start_ipython() |
|
214 | start_ipython() | |
215 |
|
215 | |||
216 | # *** END HACK *** |
|
216 | # *** END HACK *** | |
217 | ########################################################################### |
|
217 | ########################################################################### | |
218 |
|
218 | |||
219 | # Classes and functions |
|
219 | # Classes and functions | |
220 |
|
220 | |||
221 | def is_extension_module(filename): |
|
221 | def is_extension_module(filename): | |
222 | """Return whether the given filename is an extension module. |
|
222 | """Return whether the given filename is an extension module. | |
223 |
|
223 | |||
224 | This simply checks that the extension is either .so or .pyd. |
|
224 | This simply checks that the extension is either .so or .pyd. | |
225 | """ |
|
225 | """ | |
226 | return os.path.splitext(filename)[1].lower() in ('.so','.pyd') |
|
226 | return os.path.splitext(filename)[1].lower() in ('.so','.pyd') | |
227 |
|
227 | |||
228 |
|
228 | |||
229 | class DocTestSkip(object): |
|
229 | class DocTestSkip(object): | |
230 | """Object wrapper for doctests to be skipped.""" |
|
230 | """Object wrapper for doctests to be skipped.""" | |
231 |
|
231 | |||
232 | ds_skip = """Doctest to skip. |
|
232 | ds_skip = """Doctest to skip. | |
233 | >>> 1 #doctest: +SKIP |
|
233 | >>> 1 #doctest: +SKIP | |
234 | """ |
|
234 | """ | |
235 |
|
235 | |||
236 | def __init__(self,obj): |
|
236 | def __init__(self,obj): | |
237 | self.obj = obj |
|
237 | self.obj = obj | |
238 |
|
238 | |||
239 | def __getattribute__(self,key): |
|
239 | def __getattribute__(self,key): | |
240 | if key == '__doc__': |
|
240 | if key == '__doc__': | |
241 | return DocTestSkip.ds_skip |
|
241 | return DocTestSkip.ds_skip | |
242 | else: |
|
242 | else: | |
243 | return getattr(object.__getattribute__(self,'obj'),key) |
|
243 | return getattr(object.__getattribute__(self,'obj'),key) | |
244 |
|
244 | |||
245 | # Modified version of the one in the stdlib, that fixes a python bug (doctests |
|
245 | # Modified version of the one in the stdlib, that fixes a python bug (doctests | |
246 | # not found in extension modules, http://bugs.python.org/issue3158) |
|
246 | # not found in extension modules, http://bugs.python.org/issue3158) | |
247 | class DocTestFinder(doctest.DocTestFinder): |
|
247 | class DocTestFinder(doctest.DocTestFinder): | |
248 |
|
248 | |||
249 | def _from_module(self, module, object): |
|
249 | def _from_module(self, module, object): | |
250 | """ |
|
250 | """ | |
251 | Return true if the given object is defined in the given |
|
251 | Return true if the given object is defined in the given | |
252 | module. |
|
252 | module. | |
253 | """ |
|
253 | """ | |
254 | if module is None: |
|
254 | if module is None: | |
255 | return True |
|
255 | return True | |
256 | elif inspect.isfunction(object): |
|
256 | elif inspect.isfunction(object): | |
257 | return module.__dict__ is object.func_globals |
|
257 | return module.__dict__ is object.func_globals | |
258 | elif inspect.isbuiltin(object): |
|
258 | elif inspect.isbuiltin(object): | |
259 | return module.__name__ == object.__module__ |
|
259 | return module.__name__ == object.__module__ | |
260 | elif inspect.isclass(object): |
|
260 | elif inspect.isclass(object): | |
261 | return module.__name__ == object.__module__ |
|
261 | return module.__name__ == object.__module__ | |
262 | elif inspect.ismethod(object): |
|
262 | elif inspect.ismethod(object): | |
263 | # This one may be a bug in cython that fails to correctly set the |
|
263 | # This one may be a bug in cython that fails to correctly set the | |
264 | # __module__ attribute of methods, but since the same error is easy |
|
264 | # __module__ attribute of methods, but since the same error is easy | |
265 | # to make by extension code writers, having this safety in place |
|
265 | # to make by extension code writers, having this safety in place | |
266 | # isn't such a bad idea |
|
266 | # isn't such a bad idea | |
267 | return module.__name__ == object.im_class.__module__ |
|
267 | return module.__name__ == object.im_class.__module__ | |
268 | elif inspect.getmodule(object) is not None: |
|
268 | elif inspect.getmodule(object) is not None: | |
269 | return module is inspect.getmodule(object) |
|
269 | return module is inspect.getmodule(object) | |
270 | elif hasattr(object, '__module__'): |
|
270 | elif hasattr(object, '__module__'): | |
271 | return module.__name__ == object.__module__ |
|
271 | return module.__name__ == object.__module__ | |
272 | elif isinstance(object, property): |
|
272 | elif isinstance(object, property): | |
273 | return True # [XX] no way not be sure. |
|
273 | return True # [XX] no way not be sure. | |
274 | else: |
|
274 | else: | |
275 | raise ValueError("object must be a class or function") |
|
275 | raise ValueError("object must be a class or function") | |
276 |
|
276 | |||
277 | def _find(self, tests, obj, name, module, source_lines, globs, seen): |
|
277 | def _find(self, tests, obj, name, module, source_lines, globs, seen): | |
278 | """ |
|
278 | """ | |
279 | Find tests for the given object and any contained objects, and |
|
279 | Find tests for the given object and any contained objects, and | |
280 | add them to `tests`. |
|
280 | add them to `tests`. | |
281 | """ |
|
281 | """ | |
282 |
|
282 | |||
283 | if hasattr(obj,"skip_doctest"): |
|
283 | if hasattr(obj,"skip_doctest"): | |
284 | #print 'SKIPPING DOCTEST FOR:',obj # dbg |
|
284 | #print 'SKIPPING DOCTEST FOR:',obj # dbg | |
285 | obj = DocTestSkip(obj) |
|
285 | obj = DocTestSkip(obj) | |
286 |
|
286 | |||
287 | doctest.DocTestFinder._find(self,tests, obj, name, module, |
|
287 | doctest.DocTestFinder._find(self,tests, obj, name, module, | |
288 | source_lines, globs, seen) |
|
288 | source_lines, globs, seen) | |
289 |
|
289 | |||
290 | # Below we re-run pieces of the above method with manual modifications, |
|
290 | # Below we re-run pieces of the above method with manual modifications, | |
291 | # because the original code is buggy and fails to correctly identify |
|
291 | # because the original code is buggy and fails to correctly identify | |
292 | # doctests in extension modules. |
|
292 | # doctests in extension modules. | |
293 |
|
293 | |||
294 | # Local shorthands |
|
294 | # Local shorthands | |
295 | from inspect import isroutine, isclass, ismodule |
|
295 | from inspect import isroutine, isclass, ismodule | |
296 |
|
296 | |||
297 | # Look for tests in a module's contained objects. |
|
297 | # Look for tests in a module's contained objects. | |
298 | if inspect.ismodule(obj) and self._recurse: |
|
298 | if inspect.ismodule(obj) and self._recurse: | |
299 | for valname, val in obj.__dict__.items(): |
|
299 | for valname, val in obj.__dict__.items(): | |
300 | valname1 = '%s.%s' % (name, valname) |
|
300 | valname1 = '%s.%s' % (name, valname) | |
301 | if ( (isroutine(val) or isclass(val)) |
|
301 | if ( (isroutine(val) or isclass(val)) | |
302 | and self._from_module(module, val) ): |
|
302 | and self._from_module(module, val) ): | |
303 |
|
303 | |||
304 | self._find(tests, val, valname1, module, source_lines, |
|
304 | self._find(tests, val, valname1, module, source_lines, | |
305 | globs, seen) |
|
305 | globs, seen) | |
306 |
|
306 | |||
307 | # Look for tests in a class's contained objects. |
|
307 | # Look for tests in a class's contained objects. | |
308 | if inspect.isclass(obj) and self._recurse: |
|
308 | if inspect.isclass(obj) and self._recurse: | |
309 | #print 'RECURSE into class:',obj # dbg |
|
309 | #print 'RECURSE into class:',obj # dbg | |
310 | for valname, val in obj.__dict__.items(): |
|
310 | for valname, val in obj.__dict__.items(): | |
311 | # Special handling for staticmethod/classmethod. |
|
311 | # Special handling for staticmethod/classmethod. | |
312 | if isinstance(val, staticmethod): |
|
312 | if isinstance(val, staticmethod): | |
313 | val = getattr(obj, valname) |
|
313 | val = getattr(obj, valname) | |
314 | if isinstance(val, classmethod): |
|
314 | if isinstance(val, classmethod): | |
315 | val = getattr(obj, valname).im_func |
|
315 | val = getattr(obj, valname).im_func | |
316 |
|
316 | |||
317 | # Recurse to methods, properties, and nested classes. |
|
317 | # Recurse to methods, properties, and nested classes. | |
318 | if ((inspect.isfunction(val) or inspect.isclass(val) or |
|
318 | if ((inspect.isfunction(val) or inspect.isclass(val) or | |
319 | inspect.ismethod(val) or |
|
319 | inspect.ismethod(val) or | |
320 | isinstance(val, property)) and |
|
320 | isinstance(val, property)) and | |
321 | self._from_module(module, val)): |
|
321 | self._from_module(module, val)): | |
322 | valname = '%s.%s' % (name, valname) |
|
322 | valname = '%s.%s' % (name, valname) | |
323 | self._find(tests, val, valname, module, source_lines, |
|
323 | self._find(tests, val, valname, module, source_lines, | |
324 | globs, seen) |
|
324 | globs, seen) | |
325 |
|
325 | |||
326 |
|
326 | |||
327 | class IPDoctestOutputChecker(doctest.OutputChecker): |
|
327 | class IPDoctestOutputChecker(doctest.OutputChecker): | |
328 | """Second-chance checker with support for random tests. |
|
328 | """Second-chance checker with support for random tests. | |
329 |
|
329 | |||
330 | If the default comparison doesn't pass, this checker looks in the expected |
|
330 | If the default comparison doesn't pass, this checker looks in the expected | |
331 | output string for flags that tell us to ignore the output. |
|
331 | output string for flags that tell us to ignore the output. | |
332 | """ |
|
332 | """ | |
333 |
|
333 | |||
334 | random_re = re.compile(r'#\s*random\s+') |
|
334 | random_re = re.compile(r'#\s*random\s+') | |
335 |
|
335 | |||
336 | def check_output(self, want, got, optionflags): |
|
336 | def check_output(self, want, got, optionflags): | |
337 | """Check output, accepting special markers embedded in the output. |
|
337 | """Check output, accepting special markers embedded in the output. | |
338 |
|
338 | |||
339 | If the output didn't pass the default validation but the special string |
|
339 | If the output didn't pass the default validation but the special string | |
340 | '#random' is included, we accept it.""" |
|
340 | '#random' is included, we accept it.""" | |
341 |
|
341 | |||
342 | # Let the original tester verify first, in case people have valid tests |
|
342 | # Let the original tester verify first, in case people have valid tests | |
343 | # that happen to have a comment saying '#random' embedded in. |
|
343 | # that happen to have a comment saying '#random' embedded in. | |
344 | ret = doctest.OutputChecker.check_output(self, want, got, |
|
344 | ret = doctest.OutputChecker.check_output(self, want, got, | |
345 | optionflags) |
|
345 | optionflags) | |
346 | if not ret and self.random_re.search(want): |
|
346 | if not ret and self.random_re.search(want): | |
347 | #print >> sys.stderr, 'RANDOM OK:',want # dbg |
|
347 | #print >> sys.stderr, 'RANDOM OK:',want # dbg | |
348 | return True |
|
348 | return True | |
349 |
|
349 | |||
350 | return ret |
|
350 | return ret | |
351 |
|
351 | |||
352 |
|
352 | |||
353 | class DocTestCase(doctests.DocTestCase): |
|
353 | class DocTestCase(doctests.DocTestCase): | |
354 | """Proxy for DocTestCase: provides an address() method that |
|
354 | """Proxy for DocTestCase: provides an address() method that | |
355 | returns the correct address for the doctest case. Otherwise |
|
355 | returns the correct address for the doctest case. Otherwise | |
356 | acts as a proxy to the test case. To provide hints for address(), |
|
356 | acts as a proxy to the test case. To provide hints for address(), | |
357 | an obj may also be passed -- this will be used as the test object |
|
357 | an obj may also be passed -- this will be used as the test object | |
358 | for purposes of determining the test address, if it is provided. |
|
358 | for purposes of determining the test address, if it is provided. | |
359 | """ |
|
359 | """ | |
360 |
|
360 | |||
361 | # Note: this method was taken from numpy's nosetester module. |
|
361 | # Note: this method was taken from numpy's nosetester module. | |
362 |
|
362 | |||
363 | # Subclass nose.plugins.doctests.DocTestCase to work around a bug in |
|
363 | # Subclass nose.plugins.doctests.DocTestCase to work around a bug in | |
364 | # its constructor that blocks non-default arguments from being passed |
|
364 | # its constructor that blocks non-default arguments from being passed | |
365 | # down into doctest.DocTestCase |
|
365 | # down into doctest.DocTestCase | |
366 |
|
366 | |||
367 | def __init__(self, test, optionflags=0, setUp=None, tearDown=None, |
|
367 | def __init__(self, test, optionflags=0, setUp=None, tearDown=None, | |
368 | checker=None, obj=None, result_var='_'): |
|
368 | checker=None, obj=None, result_var='_'): | |
369 | self._result_var = result_var |
|
369 | self._result_var = result_var | |
370 | doctests.DocTestCase.__init__(self, test, |
|
370 | doctests.DocTestCase.__init__(self, test, | |
371 | optionflags=optionflags, |
|
371 | optionflags=optionflags, | |
372 | setUp=setUp, tearDown=tearDown, |
|
372 | setUp=setUp, tearDown=tearDown, | |
373 | checker=checker) |
|
373 | checker=checker) | |
374 | # Now we must actually copy the original constructor from the stdlib |
|
374 | # Now we must actually copy the original constructor from the stdlib | |
375 | # doctest class, because we can't call it directly and a bug in nose |
|
375 | # doctest class, because we can't call it directly and a bug in nose | |
376 | # means it never gets passed the right arguments. |
|
376 | # means it never gets passed the right arguments. | |
377 |
|
377 | |||
378 | self._dt_optionflags = optionflags |
|
378 | self._dt_optionflags = optionflags | |
379 | self._dt_checker = checker |
|
379 | self._dt_checker = checker | |
380 | self._dt_test = test |
|
380 | self._dt_test = test | |
381 | self._dt_setUp = setUp |
|
381 | self._dt_setUp = setUp | |
382 | self._dt_tearDown = tearDown |
|
382 | self._dt_tearDown = tearDown | |
383 |
|
383 | |||
384 | # XXX - store this runner once in the object! |
|
384 | # XXX - store this runner once in the object! | |
385 | runner = IPDocTestRunner(optionflags=optionflags, |
|
385 | runner = IPDocTestRunner(optionflags=optionflags, | |
386 | checker=checker, verbose=False) |
|
386 | checker=checker, verbose=False) | |
387 | self._dt_runner = runner |
|
387 | self._dt_runner = runner | |
388 |
|
388 | |||
389 |
|
389 | |||
390 | # Each doctest should remember what directory it was loaded from... |
|
390 | # Each doctest should remember what directory it was loaded from... | |
391 | self._ori_dir = os.getcwd() |
|
391 | self._ori_dir = os.getcwd() | |
392 |
|
392 | |||
393 | # Modified runTest from the default stdlib |
|
393 | # Modified runTest from the default stdlib | |
394 | def runTest(self): |
|
394 | def runTest(self): | |
395 | test = self._dt_test |
|
395 | test = self._dt_test | |
396 | runner = self._dt_runner |
|
396 | runner = self._dt_runner | |
397 |
|
397 | |||
398 | old = sys.stdout |
|
398 | old = sys.stdout | |
399 | new = StringIO() |
|
399 | new = StringIO() | |
400 | optionflags = self._dt_optionflags |
|
400 | optionflags = self._dt_optionflags | |
401 |
|
401 | |||
402 | if not (optionflags & REPORTING_FLAGS): |
|
402 | if not (optionflags & REPORTING_FLAGS): | |
403 | # The option flags don't include any reporting flags, |
|
403 | # The option flags don't include any reporting flags, | |
404 | # so add the default reporting flags |
|
404 | # so add the default reporting flags | |
405 | optionflags |= _unittest_reportflags |
|
405 | optionflags |= _unittest_reportflags | |
406 |
|
406 | |||
407 | try: |
|
407 | try: | |
408 | # Save our current directory and switch out to the one where the |
|
408 | # Save our current directory and switch out to the one where the | |
409 | # test was originally created, in case another doctest did a |
|
409 | # test was originally created, in case another doctest did a | |
410 | # directory change. We'll restore this in the finally clause. |
|
410 | # directory change. We'll restore this in the finally clause. | |
411 | curdir = os.getcwd() |
|
411 | curdir = os.getcwd() | |
412 | os.chdir(self._ori_dir) |
|
412 | os.chdir(self._ori_dir) | |
413 |
|
413 | |||
414 | runner.DIVIDER = "-"*70 |
|
414 | runner.DIVIDER = "-"*70 | |
415 | failures, tries = runner.run(test,out=new.write, |
|
415 | failures, tries = runner.run(test,out=new.write, | |
416 | clear_globs=False) |
|
416 | clear_globs=False) | |
417 | finally: |
|
417 | finally: | |
418 | sys.stdout = old |
|
418 | sys.stdout = old | |
419 | os.chdir(curdir) |
|
419 | os.chdir(curdir) | |
420 |
|
420 | |||
421 | if failures: |
|
421 | if failures: | |
422 | raise self.failureException(self.format_failure(new.getvalue())) |
|
422 | raise self.failureException(self.format_failure(new.getvalue())) | |
423 |
|
423 | |||
424 | def setUp(self): |
|
424 | def setUp(self): | |
425 | """Modified test setup that syncs with ipython namespace""" |
|
425 | """Modified test setup that syncs with ipython namespace""" | |
426 |
|
426 | |||
427 | if isinstance(self._dt_test.examples[0],IPExample): |
|
427 | if isinstance(self._dt_test.examples[0],IPExample): | |
428 | # for IPython examples *only*, we swap the globals with the ipython |
|
428 | # for IPython examples *only*, we swap the globals with the ipython | |
429 | # namespace, after updating it with the globals (which doctest |
|
429 | # namespace, after updating it with the globals (which doctest | |
430 | # fills with the necessary info from the module being tested). |
|
430 | # fills with the necessary info from the module being tested). | |
431 | _ip.IP.user_ns.update(self._dt_test.globs) |
|
431 | _ip.IP.user_ns.update(self._dt_test.globs) | |
432 | self._dt_test.globs = _ip.IP.user_ns |
|
432 | self._dt_test.globs = _ip.IP.user_ns | |
433 |
|
433 | |||
434 | doctests.DocTestCase.setUp(self) |
|
434 | doctests.DocTestCase.setUp(self) | |
435 |
|
435 | |||
436 |
|
436 | |||
437 | # A simple subclassing of the original with a different class name, so we can |
|
437 | # A simple subclassing of the original with a different class name, so we can | |
438 | # distinguish and treat differently IPython examples from pure python ones. |
|
438 | # distinguish and treat differently IPython examples from pure python ones. | |
439 | class IPExample(doctest.Example): pass |
|
439 | class IPExample(doctest.Example): pass | |
440 |
|
440 | |||
441 |
|
441 | |||
442 | class IPExternalExample(doctest.Example): |
|
442 | class IPExternalExample(doctest.Example): | |
443 | """Doctest examples to be run in an external process.""" |
|
443 | """Doctest examples to be run in an external process.""" | |
444 |
|
444 | |||
445 | def __init__(self, source, want, exc_msg=None, lineno=0, indent=0, |
|
445 | def __init__(self, source, want, exc_msg=None, lineno=0, indent=0, | |
446 | options=None): |
|
446 | options=None): | |
447 | # Parent constructor |
|
447 | # Parent constructor | |
448 | doctest.Example.__init__(self,source,want,exc_msg,lineno,indent,options) |
|
448 | doctest.Example.__init__(self,source,want,exc_msg,lineno,indent,options) | |
449 |
|
449 | |||
450 | # An EXTRA newline is needed to prevent pexpect hangs |
|
450 | # An EXTRA newline is needed to prevent pexpect hangs | |
451 | self.source += '\n' |
|
451 | self.source += '\n' | |
452 |
|
452 | |||
453 |
|
453 | |||
454 | class IPDocTestParser(doctest.DocTestParser): |
|
454 | class IPDocTestParser(doctest.DocTestParser): | |
455 | """ |
|
455 | """ | |
456 | A class used to parse strings containing doctest examples. |
|
456 | A class used to parse strings containing doctest examples. | |
457 |
|
457 | |||
458 | Note: This is a version modified to properly recognize IPython input and |
|
458 | Note: This is a version modified to properly recognize IPython input and | |
459 | convert any IPython examples into valid Python ones. |
|
459 | convert any IPython examples into valid Python ones. | |
460 | """ |
|
460 | """ | |
461 | # This regular expression is used to find doctest examples in a |
|
461 | # This regular expression is used to find doctest examples in a | |
462 | # string. It defines three groups: `source` is the source code |
|
462 | # string. It defines three groups: `source` is the source code | |
463 | # (including leading indentation and prompts); `indent` is the |
|
463 | # (including leading indentation and prompts); `indent` is the | |
464 | # indentation of the first (PS1) line of the source code; and |
|
464 | # indentation of the first (PS1) line of the source code; and | |
465 | # `want` is the expected output (including leading indentation). |
|
465 | # `want` is the expected output (including leading indentation). | |
466 |
|
466 | |||
467 | # Classic Python prompts or default IPython ones |
|
467 | # Classic Python prompts or default IPython ones | |
468 | _PS1_PY = r'>>>' |
|
468 | _PS1_PY = r'>>>' | |
469 | _PS2_PY = r'\.\.\.' |
|
469 | _PS2_PY = r'\.\.\.' | |
470 |
|
470 | |||
471 | _PS1_IP = r'In\ \[\d+\]:' |
|
471 | _PS1_IP = r'In\ \[\d+\]:' | |
472 | _PS2_IP = r'\ \ \ \.\.\.+:' |
|
472 | _PS2_IP = r'\ \ \ \.\.\.+:' | |
473 |
|
473 | |||
474 | _RE_TPL = r''' |
|
474 | _RE_TPL = r''' | |
475 | # Source consists of a PS1 line followed by zero or more PS2 lines. |
|
475 | # Source consists of a PS1 line followed by zero or more PS2 lines. | |
476 | (?P<source> |
|
476 | (?P<source> | |
477 | (?:^(?P<indent> [ ]*) (?P<ps1> %s) .*) # PS1 line |
|
477 | (?:^(?P<indent> [ ]*) (?P<ps1> %s) .*) # PS1 line | |
478 | (?:\n [ ]* (?P<ps2> %s) .*)*) # PS2 lines |
|
478 | (?:\n [ ]* (?P<ps2> %s) .*)*) # PS2 lines | |
479 | \n? # a newline |
|
479 | \n? # a newline | |
480 | # Want consists of any non-blank lines that do not start with PS1. |
|
480 | # Want consists of any non-blank lines that do not start with PS1. | |
481 | (?P<want> (?:(?![ ]*$) # Not a blank line |
|
481 | (?P<want> (?:(?![ ]*$) # Not a blank line | |
482 | (?![ ]*%s) # Not a line starting with PS1 |
|
482 | (?![ ]*%s) # Not a line starting with PS1 | |
483 | (?![ ]*%s) # Not a line starting with PS2 |
|
483 | (?![ ]*%s) # Not a line starting with PS2 | |
484 | .*$\n? # But any other line |
|
484 | .*$\n? # But any other line | |
485 | )*) |
|
485 | )*) | |
486 | ''' |
|
486 | ''' | |
487 |
|
487 | |||
488 | _EXAMPLE_RE_PY = re.compile( _RE_TPL % (_PS1_PY,_PS2_PY,_PS1_PY,_PS2_PY), |
|
488 | _EXAMPLE_RE_PY = re.compile( _RE_TPL % (_PS1_PY,_PS2_PY,_PS1_PY,_PS2_PY), | |
489 | re.MULTILINE | re.VERBOSE) |
|
489 | re.MULTILINE | re.VERBOSE) | |
490 |
|
490 | |||
491 | _EXAMPLE_RE_IP = re.compile( _RE_TPL % (_PS1_IP,_PS2_IP,_PS1_IP,_PS2_IP), |
|
491 | _EXAMPLE_RE_IP = re.compile( _RE_TPL % (_PS1_IP,_PS2_IP,_PS1_IP,_PS2_IP), | |
492 | re.MULTILINE | re.VERBOSE) |
|
492 | re.MULTILINE | re.VERBOSE) | |
493 |
|
493 | |||
494 | # Mark a test as being fully random. In this case, we simply append the |
|
494 | # Mark a test as being fully random. In this case, we simply append the | |
495 | # random marker ('#random') to each individual example's output. This way |
|
495 | # random marker ('#random') to each individual example's output. This way | |
496 | # we don't need to modify any other code. |
|
496 | # we don't need to modify any other code. | |
497 | _RANDOM_TEST = re.compile(r'#\s*all-random\s+') |
|
497 | _RANDOM_TEST = re.compile(r'#\s*all-random\s+') | |
498 |
|
498 | |||
499 | # Mark tests to be executed in an external process - currently unsupported. |
|
499 | # Mark tests to be executed in an external process - currently unsupported. | |
500 | _EXTERNAL_IP = re.compile(r'#\s*ipdoctest:\s*EXTERNAL') |
|
500 | _EXTERNAL_IP = re.compile(r'#\s*ipdoctest:\s*EXTERNAL') | |
501 |
|
501 | |||
502 | def ip2py(self,source): |
|
502 | def ip2py(self,source): | |
503 | """Convert input IPython source into valid Python.""" |
|
503 | """Convert input IPython source into valid Python.""" | |
504 | out = [] |
|
504 | out = [] | |
505 | newline = out.append |
|
505 | newline = out.append | |
506 | #print 'IPSRC:\n',source,'\n###' # dbg |
|
506 | #print 'IPSRC:\n',source,'\n###' # dbg | |
507 | # The input source must be first stripped of all bracketing whitespace |
|
507 | # The input source must be first stripped of all bracketing whitespace | |
508 | # and turned into lines, so it looks to the parser like regular user |
|
508 | # and turned into lines, so it looks to the parser like regular user | |
509 | # input |
|
509 | # input | |
510 | for lnum,line in enumerate(source.strip().splitlines()): |
|
510 | for lnum,line in enumerate(source.strip().splitlines()): | |
511 | newline(_ip.IP.prefilter(line,lnum>0)) |
|
511 | newline(_ip.IP.prefilter(line,lnum>0)) | |
512 | newline('') # ensure a closing newline, needed by doctest |
|
512 | newline('') # ensure a closing newline, needed by doctest | |
513 | #print "PYSRC:", '\n'.join(out) # dbg |
|
513 | #print "PYSRC:", '\n'.join(out) # dbg | |
514 | return '\n'.join(out) |
|
514 | return '\n'.join(out) | |
515 |
|
515 | |||
516 | def parse(self, string, name='<string>'): |
|
516 | def parse(self, string, name='<string>'): | |
517 | """ |
|
517 | """ | |
518 | Divide the given string into examples and intervening text, |
|
518 | Divide the given string into examples and intervening text, | |
519 | and return them as a list of alternating Examples and strings. |
|
519 | and return them as a list of alternating Examples and strings. | |
520 | Line numbers for the Examples are 0-based. The optional |
|
520 | Line numbers for the Examples are 0-based. The optional | |
521 | argument `name` is a name identifying this string, and is only |
|
521 | argument `name` is a name identifying this string, and is only | |
522 | used for error messages. |
|
522 | used for error messages. | |
523 | """ |
|
523 | """ | |
524 |
|
524 | |||
525 | #print 'Parse string:\n',string # dbg |
|
525 | #print 'Parse string:\n',string # dbg | |
526 |
|
526 | |||
527 | string = string.expandtabs() |
|
527 | string = string.expandtabs() | |
528 | # If all lines begin with the same indentation, then strip it. |
|
528 | # If all lines begin with the same indentation, then strip it. | |
529 | min_indent = self._min_indent(string) |
|
529 | min_indent = self._min_indent(string) | |
530 | if min_indent > 0: |
|
530 | if min_indent > 0: | |
531 | string = '\n'.join([l[min_indent:] for l in string.split('\n')]) |
|
531 | string = '\n'.join([l[min_indent:] for l in string.split('\n')]) | |
532 |
|
532 | |||
533 | output = [] |
|
533 | output = [] | |
534 | charno, lineno = 0, 0 |
|
534 | charno, lineno = 0, 0 | |
535 |
|
535 | |||
536 | # We make 'all random' tests by adding the '# random' mark to every |
|
536 | # We make 'all random' tests by adding the '# random' mark to every | |
537 | # block of output in the test. |
|
537 | # block of output in the test. | |
538 | if self._RANDOM_TEST.search(string): |
|
538 | if self._RANDOM_TEST.search(string): | |
539 | random_marker = '\n# random' |
|
539 | random_marker = '\n# random' | |
540 | else: |
|
540 | else: | |
541 | random_marker = '' |
|
541 | random_marker = '' | |
542 |
|
542 | |||
543 | # Whether to convert the input from ipython to python syntax |
|
543 | # Whether to convert the input from ipython to python syntax | |
544 | ip2py = False |
|
544 | ip2py = False | |
545 | # Find all doctest examples in the string. First, try them as Python |
|
545 | # Find all doctest examples in the string. First, try them as Python | |
546 | # examples, then as IPython ones |
|
546 | # examples, then as IPython ones | |
547 | terms = list(self._EXAMPLE_RE_PY.finditer(string)) |
|
547 | terms = list(self._EXAMPLE_RE_PY.finditer(string)) | |
548 | if terms: |
|
548 | if terms: | |
549 | # Normal Python example |
|
549 | # Normal Python example | |
550 | #print '-'*70 # dbg |
|
550 | #print '-'*70 # dbg | |
551 | #print 'PyExample, Source:\n',string # dbg |
|
551 | #print 'PyExample, Source:\n',string # dbg | |
552 | #print '-'*70 # dbg |
|
552 | #print '-'*70 # dbg | |
553 | Example = doctest.Example |
|
553 | Example = doctest.Example | |
554 | else: |
|
554 | else: | |
555 | # It's an ipython example. Note that IPExamples are run |
|
555 | # It's an ipython example. Note that IPExamples are run | |
556 | # in-process, so their syntax must be turned into valid python. |
|
556 | # in-process, so their syntax must be turned into valid python. | |
557 | # IPExternalExamples are run out-of-process (via pexpect) so they |
|
557 | # IPExternalExamples are run out-of-process (via pexpect) so they | |
558 | # don't need any filtering (a real ipython will be executing them). |
|
558 | # don't need any filtering (a real ipython will be executing them). | |
559 | terms = list(self._EXAMPLE_RE_IP.finditer(string)) |
|
559 | terms = list(self._EXAMPLE_RE_IP.finditer(string)) | |
560 | if self._EXTERNAL_IP.search(string): |
|
560 | if self._EXTERNAL_IP.search(string): | |
561 | #print '-'*70 # dbg |
|
561 | #print '-'*70 # dbg | |
562 | #print 'IPExternalExample, Source:\n',string # dbg |
|
562 | #print 'IPExternalExample, Source:\n',string # dbg | |
563 | #print '-'*70 # dbg |
|
563 | #print '-'*70 # dbg | |
564 | Example = IPExternalExample |
|
564 | Example = IPExternalExample | |
565 | else: |
|
565 | else: | |
566 | #print '-'*70 # dbg |
|
566 | #print '-'*70 # dbg | |
567 | #print 'IPExample, Source:\n',string # dbg |
|
567 | #print 'IPExample, Source:\n',string # dbg | |
568 | #print '-'*70 # dbg |
|
568 | #print '-'*70 # dbg | |
569 | Example = IPExample |
|
569 | Example = IPExample | |
570 | ip2py = True |
|
570 | ip2py = True | |
571 |
|
571 | |||
572 | for m in terms: |
|
572 | for m in terms: | |
573 | # Add the pre-example text to `output`. |
|
573 | # Add the pre-example text to `output`. | |
574 | output.append(string[charno:m.start()]) |
|
574 | output.append(string[charno:m.start()]) | |
575 | # Update lineno (lines before this example) |
|
575 | # Update lineno (lines before this example) | |
576 | lineno += string.count('\n', charno, m.start()) |
|
576 | lineno += string.count('\n', charno, m.start()) | |
577 | # Extract info from the regexp match. |
|
577 | # Extract info from the regexp match. | |
578 | (source, options, want, exc_msg) = \ |
|
578 | (source, options, want, exc_msg) = \ | |
579 | self._parse_example(m, name, lineno,ip2py) |
|
579 | self._parse_example(m, name, lineno,ip2py) | |
580 |
|
580 | |||
581 | # Append the random-output marker (it defaults to empty in most |
|
581 | # Append the random-output marker (it defaults to empty in most | |
582 | # cases, it's only non-empty for 'all-random' tests): |
|
582 | # cases, it's only non-empty for 'all-random' tests): | |
583 | want += random_marker |
|
583 | want += random_marker | |
584 |
|
584 | |||
585 | if Example is IPExternalExample: |
|
585 | if Example is IPExternalExample: | |
586 | options[doctest.NORMALIZE_WHITESPACE] = True |
|
586 | options[doctest.NORMALIZE_WHITESPACE] = True | |
587 | want += '\n' |
|
587 | want += '\n' | |
588 |
|
588 | |||
589 | # Create an Example, and add it to the list. |
|
589 | # Create an Example, and add it to the list. | |
590 | if not self._IS_BLANK_OR_COMMENT(source): |
|
590 | if not self._IS_BLANK_OR_COMMENT(source): | |
591 | output.append(Example(source, want, exc_msg, |
|
591 | output.append(Example(source, want, exc_msg, | |
592 | lineno=lineno, |
|
592 | lineno=lineno, | |
593 | indent=min_indent+len(m.group('indent')), |
|
593 | indent=min_indent+len(m.group('indent')), | |
594 | options=options)) |
|
594 | options=options)) | |
595 | # Update lineno (lines inside this example) |
|
595 | # Update lineno (lines inside this example) | |
596 | lineno += string.count('\n', m.start(), m.end()) |
|
596 | lineno += string.count('\n', m.start(), m.end()) | |
597 | # Update charno. |
|
597 | # Update charno. | |
598 | charno = m.end() |
|
598 | charno = m.end() | |
599 | # Add any remaining post-example text to `output`. |
|
599 | # Add any remaining post-example text to `output`. | |
600 | output.append(string[charno:]) |
|
600 | output.append(string[charno:]) | |
601 | return output |
|
601 | return output | |
602 |
|
602 | |||
603 | def _parse_example(self, m, name, lineno,ip2py=False): |
|
603 | def _parse_example(self, m, name, lineno,ip2py=False): | |
604 | """ |
|
604 | """ | |
605 | Given a regular expression match from `_EXAMPLE_RE` (`m`), |
|
605 | Given a regular expression match from `_EXAMPLE_RE` (`m`), | |
606 | return a pair `(source, want)`, where `source` is the matched |
|
606 | return a pair `(source, want)`, where `source` is the matched | |
607 | example's source code (with prompts and indentation stripped); |
|
607 | example's source code (with prompts and indentation stripped); | |
608 | and `want` is the example's expected output (with indentation |
|
608 | and `want` is the example's expected output (with indentation | |
609 | stripped). |
|
609 | stripped). | |
610 |
|
610 | |||
611 | `name` is the string's name, and `lineno` is the line number |
|
611 | `name` is the string's name, and `lineno` is the line number | |
612 | where the example starts; both are used for error messages. |
|
612 | where the example starts; both are used for error messages. | |
613 |
|
613 | |||
614 | Optional: |
|
614 | Optional: | |
615 | `ip2py`: if true, filter the input via IPython to convert the syntax |
|
615 | `ip2py`: if true, filter the input via IPython to convert the syntax | |
616 | into valid python. |
|
616 | into valid python. | |
617 | """ |
|
617 | """ | |
618 |
|
618 | |||
619 | # Get the example's indentation level. |
|
619 | # Get the example's indentation level. | |
620 | indent = len(m.group('indent')) |
|
620 | indent = len(m.group('indent')) | |
621 |
|
621 | |||
622 | # Divide source into lines; check that they're properly |
|
622 | # Divide source into lines; check that they're properly | |
623 | # indented; and then strip their indentation & prompts. |
|
623 | # indented; and then strip their indentation & prompts. | |
624 | source_lines = m.group('source').split('\n') |
|
624 | source_lines = m.group('source').split('\n') | |
625 |
|
625 | |||
626 | # We're using variable-length input prompts |
|
626 | # We're using variable-length input prompts | |
627 | ps1 = m.group('ps1') |
|
627 | ps1 = m.group('ps1') | |
628 | ps2 = m.group('ps2') |
|
628 | ps2 = m.group('ps2') | |
629 | ps1_len = len(ps1) |
|
629 | ps1_len = len(ps1) | |
630 |
|
630 | |||
631 | self._check_prompt_blank(source_lines, indent, name, lineno,ps1_len) |
|
631 | self._check_prompt_blank(source_lines, indent, name, lineno,ps1_len) | |
632 | if ps2: |
|
632 | if ps2: | |
633 | self._check_prefix(source_lines[1:], ' '*indent + ps2, name, lineno) |
|
633 | self._check_prefix(source_lines[1:], ' '*indent + ps2, name, lineno) | |
634 |
|
634 | |||
635 | source = '\n'.join([sl[indent+ps1_len+1:] for sl in source_lines]) |
|
635 | source = '\n'.join([sl[indent+ps1_len+1:] for sl in source_lines]) | |
636 |
|
636 | |||
637 | if ip2py: |
|
637 | if ip2py: | |
638 | # Convert source input from IPython into valid Python syntax |
|
638 | # Convert source input from IPython into valid Python syntax | |
639 | source = self.ip2py(source) |
|
639 | source = self.ip2py(source) | |
640 |
|
640 | |||
641 | # Divide want into lines; check that it's properly indented; and |
|
641 | # Divide want into lines; check that it's properly indented; and | |
642 | # then strip the indentation. Spaces before the last newline should |
|
642 | # then strip the indentation. Spaces before the last newline should | |
643 | # be preserved, so plain rstrip() isn't good enough. |
|
643 | # be preserved, so plain rstrip() isn't good enough. | |
644 | want = m.group('want') |
|
644 | want = m.group('want') | |
645 | want_lines = want.split('\n') |
|
645 | want_lines = want.split('\n') | |
646 | if len(want_lines) > 1 and re.match(r' *$', want_lines[-1]): |
|
646 | if len(want_lines) > 1 and re.match(r' *$', want_lines[-1]): | |
647 | del want_lines[-1] # forget final newline & spaces after it |
|
647 | del want_lines[-1] # forget final newline & spaces after it | |
648 | self._check_prefix(want_lines, ' '*indent, name, |
|
648 | self._check_prefix(want_lines, ' '*indent, name, | |
649 | lineno + len(source_lines)) |
|
649 | lineno + len(source_lines)) | |
650 |
|
650 | |||
651 | # Remove ipython output prompt that might be present in the first line |
|
651 | # Remove ipython output prompt that might be present in the first line | |
652 | want_lines[0] = re.sub(r'Out\[\d+\]: \s*?\n?','',want_lines[0]) |
|
652 | want_lines[0] = re.sub(r'Out\[\d+\]: \s*?\n?','',want_lines[0]) | |
653 |
|
653 | |||
654 | want = '\n'.join([wl[indent:] for wl in want_lines]) |
|
654 | want = '\n'.join([wl[indent:] for wl in want_lines]) | |
655 |
|
655 | |||
656 | # If `want` contains a traceback message, then extract it. |
|
656 | # If `want` contains a traceback message, then extract it. | |
657 | m = self._EXCEPTION_RE.match(want) |
|
657 | m = self._EXCEPTION_RE.match(want) | |
658 | if m: |
|
658 | if m: | |
659 | exc_msg = m.group('msg') |
|
659 | exc_msg = m.group('msg') | |
660 | else: |
|
660 | else: | |
661 | exc_msg = None |
|
661 | exc_msg = None | |
662 |
|
662 | |||
663 | # Extract options from the source. |
|
663 | # Extract options from the source. | |
664 | options = self._find_options(source, name, lineno) |
|
664 | options = self._find_options(source, name, lineno) | |
665 |
|
665 | |||
666 | return source, options, want, exc_msg |
|
666 | return source, options, want, exc_msg | |
667 |
|
667 | |||
668 | def _check_prompt_blank(self, lines, indent, name, lineno, ps1_len): |
|
668 | def _check_prompt_blank(self, lines, indent, name, lineno, ps1_len): | |
669 | """ |
|
669 | """ | |
670 | Given the lines of a source string (including prompts and |
|
670 | Given the lines of a source string (including prompts and | |
671 | leading indentation), check to make sure that every prompt is |
|
671 | leading indentation), check to make sure that every prompt is | |
672 | followed by a space character. If any line is not followed by |
|
672 | followed by a space character. If any line is not followed by | |
673 | a space character, then raise ValueError. |
|
673 | a space character, then raise ValueError. | |
674 |
|
674 | |||
675 | Note: IPython-modified version which takes the input prompt length as a |
|
675 | Note: IPython-modified version which takes the input prompt length as a | |
676 | parameter, so that prompts of variable length can be dealt with. |
|
676 | parameter, so that prompts of variable length can be dealt with. | |
677 | """ |
|
677 | """ | |
678 | space_idx = indent+ps1_len |
|
678 | space_idx = indent+ps1_len | |
679 | min_len = space_idx+1 |
|
679 | min_len = space_idx+1 | |
680 | for i, line in enumerate(lines): |
|
680 | for i, line in enumerate(lines): | |
681 | if len(line) >= min_len and line[space_idx] != ' ': |
|
681 | if len(line) >= min_len and line[space_idx] != ' ': | |
682 | raise ValueError('line %r of the docstring for %s ' |
|
682 | raise ValueError('line %r of the docstring for %s ' | |
683 | 'lacks blank after %s: %r' % |
|
683 | 'lacks blank after %s: %r' % | |
684 | (lineno+i+1, name, |
|
684 | (lineno+i+1, name, | |
685 | line[indent:space_idx], line)) |
|
685 | line[indent:space_idx], line)) | |
686 |
|
686 | |||
687 |
|
687 | |||
688 | SKIP = doctest.register_optionflag('SKIP') |
|
688 | SKIP = doctest.register_optionflag('SKIP') | |
689 |
|
689 | |||
690 |
|
690 | |||
691 | class IPDocTestRunner(doctest.DocTestRunner,object): |
|
691 | class IPDocTestRunner(doctest.DocTestRunner,object): | |
692 | """Test runner that synchronizes the IPython namespace with test globals. |
|
692 | """Test runner that synchronizes the IPython namespace with test globals. | |
693 | """ |
|
693 | """ | |
694 |
|
694 | |||
695 | def run(self, test, compileflags=None, out=None, clear_globs=True): |
|
695 | def run(self, test, compileflags=None, out=None, clear_globs=True): | |
696 |
|
696 | |||
697 | # Hack: ipython needs access to the execution context of the example, |
|
697 | # Hack: ipython needs access to the execution context of the example, | |
698 | # so that it can propagate user variables loaded by %run into |
|
698 | # so that it can propagate user variables loaded by %run into | |
699 | # test.globs. We put them here into our modified %run as a function |
|
699 | # test.globs. We put them here into our modified %run as a function | |
700 | # attribute. Our new %run will then only make the namespace update |
|
700 | # attribute. Our new %run will then only make the namespace update | |
701 | # when called (rather than unconconditionally updating test.globs here |
|
701 | # when called (rather than unconconditionally updating test.globs here | |
702 | # for all examples, most of which won't be calling %run anyway). |
|
702 | # for all examples, most of which won't be calling %run anyway). | |
703 | _run_ns_sync.test_globs = test.globs |
|
703 | _run_ns_sync.test_globs = test.globs | |
704 | _run_ns_sync.test_filename = test.filename |
|
704 | _run_ns_sync.test_filename = test.filename | |
705 |
|
705 | |||
706 | return super(IPDocTestRunner,self).run(test, |
|
706 | return super(IPDocTestRunner,self).run(test, | |
707 | compileflags,out,clear_globs) |
|
707 | compileflags,out,clear_globs) | |
708 |
|
708 | |||
709 |
|
709 | |||
710 | class DocFileCase(doctest.DocFileCase): |
|
710 | class DocFileCase(doctest.DocFileCase): | |
711 | """Overrides to provide filename |
|
711 | """Overrides to provide filename | |
712 | """ |
|
712 | """ | |
713 | def address(self): |
|
713 | def address(self): | |
714 | return (self._dt_test.filename, None, None) |
|
714 | return (self._dt_test.filename, None, None) | |
715 |
|
715 | |||
716 |
|
716 | |||
717 | class ExtensionDoctest(doctests.Doctest): |
|
717 | class ExtensionDoctest(doctests.Doctest): | |
718 | """Nose Plugin that supports doctests in extension modules. |
|
718 | """Nose Plugin that supports doctests in extension modules. | |
719 | """ |
|
719 | """ | |
720 | name = 'extdoctest' # call nosetests with --with-extdoctest |
|
720 | name = 'extdoctest' # call nosetests with --with-extdoctest | |
721 | enabled = True |
|
721 | enabled = True | |
722 |
|
722 | |||
723 | def __init__(self,exclude_patterns=None): |
|
723 | def __init__(self,exclude_patterns=None): | |
724 | """Create a new ExtensionDoctest plugin. |
|
724 | """Create a new ExtensionDoctest plugin. | |
725 |
|
725 | |||
726 | Parameters |
|
726 | Parameters | |
727 | ---------- |
|
727 | ---------- | |
728 |
|
728 | |||
729 | exclude_patterns : sequence of strings, optional |
|
729 | exclude_patterns : sequence of strings, optional | |
730 | These patterns are compiled as regular expressions, subsequently used |
|
730 | These patterns are compiled as regular expressions, subsequently used | |
731 | to exclude any filename which matches them from inclusion in the test |
|
731 | to exclude any filename which matches them from inclusion in the test | |
732 | suite (using pattern.search(), NOT pattern.match() ). |
|
732 | suite (using pattern.search(), NOT pattern.match() ). | |
733 | """ |
|
733 | """ | |
734 |
|
734 | |||
735 | if exclude_patterns is None: |
|
735 | if exclude_patterns is None: | |
736 | exclude_patterns = [] |
|
736 | exclude_patterns = [] | |
737 | self.exclude_patterns = map(re.compile,exclude_patterns) |
|
737 | self.exclude_patterns = map(re.compile,exclude_patterns) | |
738 | doctests.Doctest.__init__(self) |
|
738 | doctests.Doctest.__init__(self) | |
739 |
|
739 | |||
740 | def options(self, parser, env=os.environ): |
|
740 | def options(self, parser, env=os.environ): | |
741 | Plugin.options(self, parser, env) |
|
741 | Plugin.options(self, parser, env) | |
742 | parser.add_option('--doctest-tests', action='store_true', |
|
742 | parser.add_option('--doctest-tests', action='store_true', | |
743 | dest='doctest_tests', |
|
743 | dest='doctest_tests', | |
744 | default=env.get('NOSE_DOCTEST_TESTS',True), |
|
744 | default=env.get('NOSE_DOCTEST_TESTS',True), | |
745 | help="Also look for doctests in test modules. " |
|
745 | help="Also look for doctests in test modules. " | |
746 | "Note that classes, methods and functions should " |
|
746 | "Note that classes, methods and functions should " | |
747 | "have either doctests or non-doctest tests, " |
|
747 | "have either doctests or non-doctest tests, " | |
748 | "not both. [NOSE_DOCTEST_TESTS]") |
|
748 | "not both. [NOSE_DOCTEST_TESTS]") | |
749 | parser.add_option('--doctest-extension', action="append", |
|
749 | parser.add_option('--doctest-extension', action="append", | |
750 | dest="doctestExtension", |
|
750 | dest="doctestExtension", | |
751 | help="Also look for doctests in files with " |
|
751 | help="Also look for doctests in files with " | |
752 | "this extension [NOSE_DOCTEST_EXTENSION]") |
|
752 | "this extension [NOSE_DOCTEST_EXTENSION]") | |
753 | # Set the default as a list, if given in env; otherwise |
|
753 | # Set the default as a list, if given in env; otherwise | |
754 | # an additional value set on the command line will cause |
|
754 | # an additional value set on the command line will cause | |
755 | # an error. |
|
755 | # an error. | |
756 | env_setting = env.get('NOSE_DOCTEST_EXTENSION') |
|
756 | env_setting = env.get('NOSE_DOCTEST_EXTENSION') | |
757 | if env_setting is not None: |
|
757 | if env_setting is not None: | |
758 | parser.set_defaults(doctestExtension=tolist(env_setting)) |
|
758 | parser.set_defaults(doctestExtension=tolist(env_setting)) | |
759 |
|
759 | |||
760 |
|
760 | |||
761 | def configure(self, options, config): |
|
761 | def configure(self, options, config): | |
762 | Plugin.configure(self, options, config) |
|
762 | Plugin.configure(self, options, config) | |
763 | self.doctest_tests = options.doctest_tests |
|
763 | self.doctest_tests = options.doctest_tests | |
764 | self.extension = tolist(options.doctestExtension) |
|
764 | self.extension = tolist(options.doctestExtension) | |
765 |
|
765 | |||
766 | self.parser = doctest.DocTestParser() |
|
766 | self.parser = doctest.DocTestParser() | |
767 | self.finder = DocTestFinder() |
|
767 | self.finder = DocTestFinder() | |
768 | self.checker = IPDoctestOutputChecker() |
|
768 | self.checker = IPDoctestOutputChecker() | |
769 | self.globs = None |
|
769 | self.globs = None | |
770 | self.extraglobs = None |
|
770 | self.extraglobs = None | |
771 |
|
771 | |||
772 |
|
772 | |||
773 | def loadTestsFromExtensionModule(self,filename): |
|
773 | def loadTestsFromExtensionModule(self,filename): | |
774 | bpath,mod = os.path.split(filename) |
|
774 | bpath,mod = os.path.split(filename) | |
775 | modname = os.path.splitext(mod)[0] |
|
775 | modname = os.path.splitext(mod)[0] | |
776 | try: |
|
776 | try: | |
777 | sys.path.append(bpath) |
|
777 | sys.path.append(bpath) | |
778 | module = __import__(modname) |
|
778 | module = __import__(modname) | |
779 | tests = list(self.loadTestsFromModule(module)) |
|
779 | tests = list(self.loadTestsFromModule(module)) | |
780 | finally: |
|
780 | finally: | |
781 | sys.path.pop() |
|
781 | sys.path.pop() | |
782 | return tests |
|
782 | return tests | |
783 |
|
783 | |||
784 | # NOTE: the method below is almost a copy of the original one in nose, with |
|
784 | # NOTE: the method below is almost a copy of the original one in nose, with | |
785 | # a few modifications to control output checking. |
|
785 | # a few modifications to control output checking. | |
786 |
|
786 | |||
787 | def loadTestsFromModule(self, module): |
|
787 | def loadTestsFromModule(self, module): | |
788 | #print '*** ipdoctest - lTM',module # dbg |
|
788 | #print '*** ipdoctest - lTM',module # dbg | |
789 |
|
789 | |||
790 | if not self.matches(module.__name__): |
|
790 | if not self.matches(module.__name__): | |
791 | log.debug("Doctest doesn't want module %s", module) |
|
791 | log.debug("Doctest doesn't want module %s", module) | |
792 | return |
|
792 | return | |
793 |
|
793 | |||
794 | tests = self.finder.find(module,globs=self.globs, |
|
794 | tests = self.finder.find(module,globs=self.globs, | |
795 | extraglobs=self.extraglobs) |
|
795 | extraglobs=self.extraglobs) | |
796 | if not tests: |
|
796 | if not tests: | |
797 | return |
|
797 | return | |
798 |
|
798 | |||
799 | # always use whitespace and ellipsis options |
|
799 | # always use whitespace and ellipsis options | |
800 | optionflags = doctest.NORMALIZE_WHITESPACE | doctest.ELLIPSIS |
|
800 | optionflags = doctest.NORMALIZE_WHITESPACE | doctest.ELLIPSIS | |
801 |
|
801 | |||
802 | tests.sort() |
|
802 | tests.sort() | |
803 | module_file = module.__file__ |
|
803 | module_file = module.__file__ | |
804 | if module_file[-4:] in ('.pyc', '.pyo'): |
|
804 | if module_file[-4:] in ('.pyc', '.pyo'): | |
805 | module_file = module_file[:-1] |
|
805 | module_file = module_file[:-1] | |
806 | for test in tests: |
|
806 | for test in tests: | |
807 | if not test.examples: |
|
807 | if not test.examples: | |
808 | continue |
|
808 | continue | |
809 | if not test.filename: |
|
809 | if not test.filename: | |
810 | test.filename = module_file |
|
810 | test.filename = module_file | |
811 |
|
811 | |||
812 | yield DocTestCase(test, |
|
812 | yield DocTestCase(test, | |
813 | optionflags=optionflags, |
|
813 | optionflags=optionflags, | |
814 | checker=self.checker) |
|
814 | checker=self.checker) | |
815 |
|
815 | |||
816 |
|
816 | |||
817 | def loadTestsFromFile(self, filename): |
|
817 | def loadTestsFromFile(self, filename): | |
818 | if is_extension_module(filename): |
|
818 | if is_extension_module(filename): | |
819 | for t in self.loadTestsFromExtensionModule(filename): |
|
819 | for t in self.loadTestsFromExtensionModule(filename): | |
820 | yield t |
|
820 | yield t | |
821 | else: |
|
821 | else: | |
822 | if self.extension and anyp(filename.endswith, self.extension): |
|
822 | if self.extension and anyp(filename.endswith, self.extension): | |
823 | name = os.path.basename(filename) |
|
823 | name = os.path.basename(filename) | |
824 | dh = open(filename) |
|
824 | dh = open(filename) | |
825 | try: |
|
825 | try: | |
826 | doc = dh.read() |
|
826 | doc = dh.read() | |
827 | finally: |
|
827 | finally: | |
828 | dh.close() |
|
828 | dh.close() | |
829 | test = self.parser.get_doctest( |
|
829 | test = self.parser.get_doctest( | |
830 | doc, globs={'__file__': filename}, name=name, |
|
830 | doc, globs={'__file__': filename}, name=name, | |
831 | filename=filename, lineno=0) |
|
831 | filename=filename, lineno=0) | |
832 | if test.examples: |
|
832 | if test.examples: | |
833 | #print 'FileCase:',test.examples # dbg |
|
833 | #print 'FileCase:',test.examples # dbg | |
834 | yield DocFileCase(test) |
|
834 | yield DocFileCase(test) | |
835 | else: |
|
835 | else: | |
836 | yield False # no tests to load |
|
836 | yield False # no tests to load | |
837 |
|
837 | |||
838 | def wantFile(self,filename): |
|
838 | def wantFile(self,filename): | |
839 | """Return whether the given filename should be scanned for tests. |
|
839 | """Return whether the given filename should be scanned for tests. | |
840 |
|
840 | |||
841 | Modified version that accepts extension modules as valid containers for |
|
841 | Modified version that accepts extension modules as valid containers for | |
842 | doctests. |
|
842 | doctests. | |
843 | """ |
|
843 | """ | |
844 | # print '*** ipdoctest- wantFile:',filename # dbg |
|
844 | # print '*** ipdoctest- wantFile:',filename # dbg | |
845 |
|
845 | |||
846 | for pat in self.exclude_patterns: |
|
846 | for pat in self.exclude_patterns: | |
847 | if pat.search(filename): |
|
847 | if pat.search(filename): | |
848 | # print '###>>> SKIP:',filename # dbg |
|
848 | # print '###>>> SKIP:',filename # dbg | |
849 | return False |
|
849 | return False | |
850 |
|
850 | |||
851 | if is_extension_module(filename): |
|
851 | if is_extension_module(filename): | |
852 | return True |
|
852 | return True | |
853 | else: |
|
853 | else: | |
854 | return doctests.Doctest.wantFile(self,filename) |
|
854 | return doctests.Doctest.wantFile(self,filename) | |
855 |
|
855 | |||
856 |
|
856 | |||
857 | class IPythonDoctest(ExtensionDoctest): |
|
857 | class IPythonDoctest(ExtensionDoctest): | |
858 | """Nose Plugin that supports doctests in extension modules. |
|
858 | """Nose Plugin that supports doctests in extension modules. | |
859 | """ |
|
859 | """ | |
860 | name = 'ipdoctest' # call nosetests with --with-ipdoctest |
|
860 | name = 'ipdoctest' # call nosetests with --with-ipdoctest | |
861 | enabled = True |
|
861 | enabled = True | |
862 |
|
862 | |||
863 | def makeTest(self, obj, parent): |
|
863 | def makeTest(self, obj, parent): | |
864 | """Look for doctests in the given object, which will be a |
|
864 | """Look for doctests in the given object, which will be a | |
865 | function, method or class. |
|
865 | function, method or class. | |
866 | """ |
|
866 | """ | |
867 | # always use whitespace and ellipsis options |
|
867 | # always use whitespace and ellipsis options | |
868 | optionflags = doctest.NORMALIZE_WHITESPACE | doctest.ELLIPSIS |
|
868 | optionflags = doctest.NORMALIZE_WHITESPACE | doctest.ELLIPSIS | |
869 |
|
869 | |||
870 | doctests = self.finder.find(obj, module=getmodule(parent)) |
|
870 | doctests = self.finder.find(obj, module=getmodule(parent)) | |
871 | if doctests: |
|
871 | if doctests: | |
872 | for test in doctests: |
|
872 | for test in doctests: | |
873 | if len(test.examples) == 0: |
|
873 | if len(test.examples) == 0: | |
874 | continue |
|
874 | continue | |
875 |
|
875 | |||
876 | yield DocTestCase(test, obj=obj, |
|
876 | yield DocTestCase(test, obj=obj, | |
877 | optionflags=optionflags, |
|
877 | optionflags=optionflags, | |
878 | checker=self.checker) |
|
878 | checker=self.checker) | |
879 |
|
879 | |||
880 | def options(self, parser, env=os.environ): |
|
880 | def options(self, parser, env=os.environ): | |
881 | Plugin.options(self, parser, env) |
|
881 | Plugin.options(self, parser, env) | |
882 | parser.add_option('--ipdoctest-tests', action='store_true', |
|
882 | parser.add_option('--ipdoctest-tests', action='store_true', | |
883 | dest='ipdoctest_tests', |
|
883 | dest='ipdoctest_tests', | |
884 | default=env.get('NOSE_IPDOCTEST_TESTS',True), |
|
884 | default=env.get('NOSE_IPDOCTEST_TESTS',True), | |
885 | help="Also look for doctests in test modules. " |
|
885 | help="Also look for doctests in test modules. " | |
886 | "Note that classes, methods and functions should " |
|
886 | "Note that classes, methods and functions should " | |
887 | "have either doctests or non-doctest tests, " |
|
887 | "have either doctests or non-doctest tests, " | |
888 | "not both. [NOSE_IPDOCTEST_TESTS]") |
|
888 | "not both. [NOSE_IPDOCTEST_TESTS]") | |
889 | parser.add_option('--ipdoctest-extension', action="append", |
|
889 | parser.add_option('--ipdoctest-extension', action="append", | |
890 | dest="ipdoctest_extension", |
|
890 | dest="ipdoctest_extension", | |
891 | help="Also look for doctests in files with " |
|
891 | help="Also look for doctests in files with " | |
892 | "this extension [NOSE_IPDOCTEST_EXTENSION]") |
|
892 | "this extension [NOSE_IPDOCTEST_EXTENSION]") | |
893 | # Set the default as a list, if given in env; otherwise |
|
893 | # Set the default as a list, if given in env; otherwise | |
894 | # an additional value set on the command line will cause |
|
894 | # an additional value set on the command line will cause | |
895 | # an error. |
|
895 | # an error. | |
896 | env_setting = env.get('NOSE_IPDOCTEST_EXTENSION') |
|
896 | env_setting = env.get('NOSE_IPDOCTEST_EXTENSION') | |
897 | if env_setting is not None: |
|
897 | if env_setting is not None: | |
898 | parser.set_defaults(ipdoctest_extension=tolist(env_setting)) |
|
898 | parser.set_defaults(ipdoctest_extension=tolist(env_setting)) | |
899 |
|
899 | |||
900 | def configure(self, options, config): |
|
900 | def configure(self, options, config): | |
901 | Plugin.configure(self, options, config) |
|
901 | Plugin.configure(self, options, config) | |
902 | self.doctest_tests = options.ipdoctest_tests |
|
902 | self.doctest_tests = options.ipdoctest_tests | |
903 | self.extension = tolist(options.ipdoctest_extension) |
|
903 | self.extension = tolist(options.ipdoctest_extension) | |
904 |
|
904 | |||
905 | self.parser = IPDocTestParser() |
|
905 | self.parser = IPDocTestParser() | |
906 | self.finder = DocTestFinder(parser=self.parser) |
|
906 | self.finder = DocTestFinder(parser=self.parser) | |
907 | self.checker = IPDoctestOutputChecker() |
|
907 | self.checker = IPDoctestOutputChecker() | |
908 | self.globs = None |
|
908 | self.globs = None | |
909 | self.extraglobs = None |
|
909 | self.extraglobs = None |
@@ -1,645 +1,645 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 | #***************************************************************************** |
|
2 | #***************************************************************************** | |
3 | # Copyright (C) 2001-2004 Fernando Perez. <fperez@colorado.edu> |
|
3 | # Copyright (C) 2001-2004 Fernando Perez. <fperez@colorado.edu> | |
4 | # |
|
4 | # | |
5 | # Distributed under the terms of the BSD License. The full license is in |
|
5 | # Distributed under the terms of the BSD License. The full license is in | |
6 | # the file COPYING, distributed as part of this software. |
|
6 | # the file COPYING, distributed as part of this software. | |
7 | #***************************************************************************** |
|
7 | #***************************************************************************** | |
8 |
|
8 | |||
9 | __doc__ = """ |
|
9 | __doc__ = """ | |
10 | IPython -- An enhanced Interactive Python |
|
10 | IPython -- An enhanced Interactive Python | |
11 | ========================================= |
|
11 | ========================================= | |
12 |
|
12 | |||
13 | A Python shell with automatic history (input and output), dynamic object |
|
13 | A Python shell with automatic history (input and output), dynamic object | |
14 | introspection, easier configuration, command completion, access to the system |
|
14 | introspection, easier configuration, command completion, access to the system | |
15 | shell and more. |
|
15 | shell and more. | |
16 |
|
16 | |||
17 | IPython can also be embedded in running programs. See EMBEDDING below. |
|
17 | IPython can also be embedded in running programs. See EMBEDDING below. | |
18 |
|
18 | |||
19 |
|
19 | |||
20 | USAGE |
|
20 | USAGE | |
21 | ipython [options] files |
|
21 | ipython [options] files | |
22 |
|
22 | |||
23 | If invoked with no options, it executes all the files listed in |
|
23 | If invoked with no options, it executes all the files listed in | |
24 | sequence and drops you into the interpreter while still acknowledging |
|
24 | sequence and drops you into the interpreter while still acknowledging | |
25 | any options you may have set in your ipythonrc file. This behavior is |
|
25 | any options you may have set in your ipythonrc file. This behavior is | |
26 | different from standard Python, which when called as python -i will |
|
26 | different from standard Python, which when called as python -i will | |
27 | only execute one file and will ignore your configuration setup. |
|
27 | only execute one file and will ignore your configuration setup. | |
28 |
|
28 | |||
29 | Please note that some of the configuration options are not available at |
|
29 | Please note that some of the configuration options are not available at | |
30 | the command line, simply because they are not practical here. Look into |
|
30 | the command line, simply because they are not practical here. Look into | |
31 | your ipythonrc configuration file for details on those. This file |
|
31 | your ipythonrc configuration file for details on those. This file | |
32 | typically installed in the $HOME/.ipython directory. |
|
32 | typically installed in the $HOME/.ipython directory. | |
33 |
|
33 | |||
34 | For Windows users, $HOME resolves to C:\\Documents and |
|
34 | For Windows users, $HOME resolves to C:\\Documents and | |
35 | Settings\\YourUserName in most instances, and _ipython is used instead |
|
35 | Settings\\YourUserName in most instances, and _ipython is used instead | |
36 | of .ipython, since some Win32 programs have problems with dotted names |
|
36 | of .ipython, since some Win32 programs have problems with dotted names | |
37 | in directories. |
|
37 | in directories. | |
38 |
|
38 | |||
39 | In the rest of this text, we will refer to this directory as |
|
39 | In the rest of this text, we will refer to this directory as | |
40 | IPYTHONDIR. |
|
40 | IPYTHONDIR. | |
41 |
|
41 | |||
42 |
|
42 | |||
43 | SPECIAL THREADING OPTIONS |
|
43 | SPECIAL THREADING OPTIONS | |
44 | The following special options are ONLY valid at the beginning of the |
|
44 | The following special options are ONLY valid at the beginning of the | |
45 | command line, and not later. This is because they control the initial- |
|
45 | command line, and not later. This is because they control the initial- | |
46 | ization of ipython itself, before the normal option-handling mechanism |
|
46 | ization of ipython itself, before the normal option-handling mechanism | |
47 | is active. |
|
47 | is active. | |
48 |
|
48 | |||
49 | -gthread, -qthread, -q4thread, -wthread, -pylab |
|
49 | -gthread, -qthread, -q4thread, -wthread, -pylab | |
50 |
|
50 | |||
51 | Only ONE of these can be given, and it can only be given as the |
|
51 | Only ONE of these can be given, and it can only be given as the | |
52 | first option passed to IPython (it will have no effect in any |
|
52 | first option passed to IPython (it will have no effect in any | |
53 | other position). They provide threading support for the GTK, QT |
|
53 | other position). They provide threading support for the GTK, QT | |
54 | and WXWidgets toolkits, and for the matplotlib library. |
|
54 | and WXWidgets toolkits, and for the matplotlib library. | |
55 |
|
55 | |||
56 | With any of the first four options, IPython starts running a |
|
56 | With any of the first four options, IPython starts running a | |
57 | separate thread for the graphical toolkit's operation, so that |
|
57 | separate thread for the graphical toolkit's operation, so that | |
58 | you can open and control graphical elements from within an |
|
58 | you can open and control graphical elements from within an | |
59 | IPython command line, without blocking. All four provide |
|
59 | IPython command line, without blocking. All four provide | |
60 | essentially the same functionality, respectively for GTK, QT3, |
|
60 | essentially the same functionality, respectively for GTK, QT3, | |
61 | QT4 and WXWidgets (via their Python interfaces). |
|
61 | QT4 and WXWidgets (via their Python interfaces). | |
62 |
|
62 | |||
63 | Note that with -wthread, you can additionally use the -wxversion |
|
63 | Note that with -wthread, you can additionally use the -wxversion | |
64 | option to request a specific version of wx to be used. This |
|
64 | option to request a specific version of wx to be used. This | |
65 | requires that you have the 'wxversion' Python module installed, |
|
65 | requires that you have the 'wxversion' Python module installed, | |
66 | which is part of recent wxPython distributions. |
|
66 | which is part of recent wxPython distributions. | |
67 |
|
67 | |||
68 | If -pylab is given, IPython loads special support for the mat- |
|
68 | If -pylab is given, IPython loads special support for the mat- | |
69 | plotlib library (http://matplotlib.sourceforge.net), allowing |
|
69 | plotlib library (http://matplotlib.sourceforge.net), allowing | |
70 | interactive usage of any of its backends as defined in the |
|
70 | interactive usage of any of its backends as defined in the | |
71 | user's .matplotlibrc file. It automatically activates GTK, QT |
|
71 | user's .matplotlibrc file. It automatically activates GTK, QT | |
72 | or WX threading for IPyhton if the choice of matplotlib backend |
|
72 | or WX threading for IPyhton if the choice of matplotlib backend | |
73 | requires it. It also modifies the %run command to correctly |
|
73 | requires it. It also modifies the %run command to correctly | |
74 | execute (without blocking) any matplotlib-based script which |
|
74 | execute (without blocking) any matplotlib-based script which | |
75 | calls show() at the end. |
|
75 | calls show() at the end. | |
76 |
|
76 | |||
77 | -tk The -g/q/q4/wthread options, and -pylab (if matplotlib is |
|
77 | -tk The -g/q/q4/wthread options, and -pylab (if matplotlib is | |
78 | configured to use GTK, QT or WX), will normally block Tk |
|
78 | configured to use GTK, QT or WX), will normally block Tk | |
79 | graphical interfaces. This means that when GTK, QT or WX |
|
79 | graphical interfaces. This means that when GTK, QT or WX | |
80 | threading is active, any attempt to open a Tk GUI will result in |
|
80 | threading is active, any attempt to open a Tk GUI will result in | |
81 | a dead window, and possibly cause the Python interpreter to |
|
81 | a dead window, and possibly cause the Python interpreter to | |
82 | crash. An extra option, -tk, is available to address this |
|
82 | crash. An extra option, -tk, is available to address this | |
83 | issue. It can ONLY be given as a SECOND option after any of the |
|
83 | issue. It can ONLY be given as a SECOND option after any of the | |
84 | above (-gthread, -qthread, q4thread, -wthread or -pylab). |
|
84 | above (-gthread, -qthread, q4thread, -wthread or -pylab). | |
85 |
|
85 | |||
86 | If -tk is given, IPython will try to coordinate Tk threading |
|
86 | If -tk is given, IPython will try to coordinate Tk threading | |
87 | with GTK, QT or WX. This is however potentially unreliable, and |
|
87 | with GTK, QT or WX. This is however potentially unreliable, and | |
88 | you will have to test on your platform and Python configuration |
|
88 | you will have to test on your platform and Python configuration | |
89 | to determine whether it works for you. Debian users have |
|
89 | to determine whether it works for you. Debian users have | |
90 | reported success, apparently due to the fact that Debian builds |
|
90 | reported success, apparently due to the fact that Debian builds | |
91 | all of Tcl, Tk, Tkinter and Python with pthreads support. Under |
|
91 | all of Tcl, Tk, Tkinter and Python with pthreads support. Under | |
92 | other Linux environments (such as Fedora Core 2/3), this option |
|
92 | other Linux environments (such as Fedora Core 2/3), this option | |
93 | has caused random crashes and lockups of the Python interpreter. |
|
93 | has caused random crashes and lockups of the Python interpreter. | |
94 | Under other operating systems (Mac OSX and Windows), you'll need |
|
94 | Under other operating systems (Mac OSX and Windows), you'll need | |
95 | to try it to find out, since currently no user reports are |
|
95 | to try it to find out, since currently no user reports are | |
96 | available. |
|
96 | available. | |
97 |
|
97 | |||
98 | There is unfortunately no way for IPython to determine at run- |
|
98 | There is unfortunately no way for IPython to determine at run- | |
99 | time whether -tk will work reliably or not, so you will need to |
|
99 | time whether -tk will work reliably or not, so you will need to | |
100 | do some experiments before relying on it for regular work. |
|
100 | do some experiments before relying on it for regular work. | |
101 |
|
101 | |||
102 | A WARNING ABOUT SIGNALS AND THREADS |
|
102 | A WARNING ABOUT SIGNALS AND THREADS | |
103 |
|
103 | |||
104 | When any of the thread systems (GTK, QT or WX) are active, either |
|
104 | When any of the thread systems (GTK, QT or WX) are active, either | |
105 | directly or via -pylab with a threaded backend, it is impossible to |
|
105 | directly or via -pylab with a threaded backend, it is impossible to | |
106 | interrupt long-running Python code via Ctrl-C. IPython can not pass |
|
106 | interrupt long-running Python code via Ctrl-C. IPython can not pass | |
107 | the KeyboardInterrupt exception (or the underlying SIGINT) across |
|
107 | the KeyboardInterrupt exception (or the underlying SIGINT) across | |
108 | threads, so any long-running process started from IPython will run to |
|
108 | threads, so any long-running process started from IPython will run to | |
109 | completion, or will have to be killed via an external (OS-based) |
|
109 | completion, or will have to be killed via an external (OS-based) | |
110 | mechanism. |
|
110 | mechanism. | |
111 |
|
111 | |||
112 | To the best of my knowledge, this limitation is imposed by the Python |
|
112 | To the best of my knowledge, this limitation is imposed by the Python | |
113 | interpreter itself, and it comes from the difficulty of writing |
|
113 | interpreter itself, and it comes from the difficulty of writing | |
114 | portable signal/threaded code. If any user is an expert on this topic |
|
114 | portable signal/threaded code. If any user is an expert on this topic | |
115 | and can suggest a better solution, I would love to hear about it. In |
|
115 | and can suggest a better solution, I would love to hear about it. In | |
116 |
the IPython sources, look at the |
|
116 | the IPython sources, look at the shell.py module, and in particular at | |
117 | the runcode() method. |
|
117 | the runcode() method. | |
118 |
|
118 | |||
119 | REGULAR OPTIONS |
|
119 | REGULAR OPTIONS | |
120 | After the above threading options have been given, regular options can |
|
120 | After the above threading options have been given, regular options can | |
121 | follow in any order. All options can be abbreviated to their shortest |
|
121 | follow in any order. All options can be abbreviated to their shortest | |
122 | non-ambiguous form and are case-sensitive. One or two dashes can be |
|
122 | non-ambiguous form and are case-sensitive. One or two dashes can be | |
123 | used. Some options have an alternate short form, indicated after a |. |
|
123 | used. Some options have an alternate short form, indicated after a |. | |
124 |
|
124 | |||
125 | Most options can also be set from your ipythonrc configuration file. |
|
125 | Most options can also be set from your ipythonrc configuration file. | |
126 | See the provided examples for assistance. Options given on the comman- |
|
126 | See the provided examples for assistance. Options given on the comman- | |
127 | dline override the values set in the ipythonrc file. |
|
127 | dline override the values set in the ipythonrc file. | |
128 |
|
128 | |||
129 | All options with a [no] prepended can be specified in negated form |
|
129 | All options with a [no] prepended can be specified in negated form | |
130 | (using -nooption instead of -option) to turn the feature off. |
|
130 | (using -nooption instead of -option) to turn the feature off. | |
131 |
|
131 | |||
132 | -h, --help |
|
132 | -h, --help | |
133 | Show summary of options. |
|
133 | Show summary of options. | |
134 |
|
134 | |||
135 | -pylab This can only be given as the first option passed to IPython (it |
|
135 | -pylab This can only be given as the first option passed to IPython (it | |
136 | will have no effect in any other position). It adds special sup- |
|
136 | will have no effect in any other position). It adds special sup- | |
137 | port for the matplotlib library (http://matplotlib.source- |
|
137 | port for the matplotlib library (http://matplotlib.source- | |
138 | forge.net), allowing interactive usage of any of its backends as |
|
138 | forge.net), allowing interactive usage of any of its backends as | |
139 | defined in the user's .matplotlibrc file. It automatically |
|
139 | defined in the user's .matplotlibrc file. It automatically | |
140 | activates GTK or WX threading for IPyhton if the choice of mat- |
|
140 | activates GTK or WX threading for IPyhton if the choice of mat- | |
141 | plotlib backend requires it. It also modifies the @run command |
|
141 | plotlib backend requires it. It also modifies the @run command | |
142 | to correctly execute (without blocking) any matplotlib-based |
|
142 | to correctly execute (without blocking) any matplotlib-based | |
143 | script which calls show() at the end. |
|
143 | script which calls show() at the end. | |
144 |
|
144 | |||
145 | -autocall <val> |
|
145 | -autocall <val> | |
146 | Make IPython automatically call any callable object even if you |
|
146 | Make IPython automatically call any callable object even if you | |
147 | didn't type explicit parentheses. For example, 'str 43' becomes |
|
147 | didn't type explicit parentheses. For example, 'str 43' becomes | |
148 | 'str(43)' automatically. The value can be '0' to disable the |
|
148 | 'str(43)' automatically. The value can be '0' to disable the | |
149 | feature, '1' for 'smart' autocall, where it is not applied if |
|
149 | feature, '1' for 'smart' autocall, where it is not applied if | |
150 | there are no more arguments on the line, and '2' for 'full' |
|
150 | there are no more arguments on the line, and '2' for 'full' | |
151 | autocall, where all callable objects are automatically called |
|
151 | autocall, where all callable objects are automatically called | |
152 | (even if no arguments are present). The default is '1'. |
|
152 | (even if no arguments are present). The default is '1'. | |
153 |
|
153 | |||
154 | -[no]autoindent |
|
154 | -[no]autoindent | |
155 | Turn automatic indentation on/off. |
|
155 | Turn automatic indentation on/off. | |
156 |
|
156 | |||
157 | -[no]automagic |
|
157 | -[no]automagic | |
158 | Make magic commands automatic (without needing their first char- |
|
158 | Make magic commands automatic (without needing their first char- | |
159 | acter to be %). Type %magic at the IPython prompt for more |
|
159 | acter to be %). Type %magic at the IPython prompt for more | |
160 | information. |
|
160 | information. | |
161 |
|
161 | |||
162 | -[no]autoedit_syntax |
|
162 | -[no]autoedit_syntax | |
163 | When a syntax error occurs after editing a file, automatically |
|
163 | When a syntax error occurs after editing a file, automatically | |
164 | open the file to the trouble causing line for convenient fixing. |
|
164 | open the file to the trouble causing line for convenient fixing. | |
165 |
|
165 | |||
166 | -[no]banner |
|
166 | -[no]banner | |
167 | Print the intial information banner (default on). |
|
167 | Print the intial information banner (default on). | |
168 |
|
168 | |||
169 | -c <command> |
|
169 | -c <command> | |
170 | Execute the given command string, and set sys.argv to ['c']. |
|
170 | Execute the given command string, and set sys.argv to ['c']. | |
171 | This is similar to the -c option in the normal Python inter- |
|
171 | This is similar to the -c option in the normal Python inter- | |
172 | preter. |
|
172 | preter. | |
173 |
|
173 | |||
174 | -cache_size|cs <n> |
|
174 | -cache_size|cs <n> | |
175 | Size of the output cache (maximum number of entries to hold in |
|
175 | Size of the output cache (maximum number of entries to hold in | |
176 | memory). The default is 1000, you can change it permanently in |
|
176 | memory). The default is 1000, you can change it permanently in | |
177 | your config file. Setting it to 0 completely disables the |
|
177 | your config file. Setting it to 0 completely disables the | |
178 | caching system, and the minimum value accepted is 20 (if you |
|
178 | caching system, and the minimum value accepted is 20 (if you | |
179 | provide a value less than 20, it is reset to 0 and a warning is |
|
179 | provide a value less than 20, it is reset to 0 and a warning is | |
180 | issued). This limit is defined because otherwise you'll spend |
|
180 | issued). This limit is defined because otherwise you'll spend | |
181 | more time re-flushing a too small cache than working. |
|
181 | more time re-flushing a too small cache than working. | |
182 |
|
182 | |||
183 | -classic|cl |
|
183 | -classic|cl | |
184 | Gives IPython a similar feel to the classic Python prompt. |
|
184 | Gives IPython a similar feel to the classic Python prompt. | |
185 |
|
185 | |||
186 | -colors <scheme> |
|
186 | -colors <scheme> | |
187 | Color scheme for prompts and exception reporting. Currently |
|
187 | Color scheme for prompts and exception reporting. Currently | |
188 | implemented: NoColor, Linux, and LightBG. |
|
188 | implemented: NoColor, Linux, and LightBG. | |
189 |
|
189 | |||
190 | -[no]color_info |
|
190 | -[no]color_info | |
191 | IPython can display information about objects via a set of func- |
|
191 | IPython can display information about objects via a set of func- | |
192 | tions, and optionally can use colors for this, syntax highlight- |
|
192 | tions, and optionally can use colors for this, syntax highlight- | |
193 | ing source code and various other elements. However, because |
|
193 | ing source code and various other elements. However, because | |
194 | this information is passed through a pager (like 'less') and |
|
194 | this information is passed through a pager (like 'less') and | |
195 | many pagers get confused with color codes, this option is off by |
|
195 | many pagers get confused with color codes, this option is off by | |
196 | default. You can test it and turn it on permanently in your |
|
196 | default. You can test it and turn it on permanently in your | |
197 | ipythonrc file if it works for you. As a reference, the 'less' |
|
197 | ipythonrc file if it works for you. As a reference, the 'less' | |
198 | pager supplied with Mandrake 8.2 works ok, but that in RedHat |
|
198 | pager supplied with Mandrake 8.2 works ok, but that in RedHat | |
199 | 7.2 doesn't. |
|
199 | 7.2 doesn't. | |
200 |
|
200 | |||
201 | Test it and turn it on permanently if it works with your system. |
|
201 | Test it and turn it on permanently if it works with your system. | |
202 | The magic function @color_info allows you to toggle this inter- |
|
202 | The magic function @color_info allows you to toggle this inter- | |
203 | actively for testing. |
|
203 | actively for testing. | |
204 |
|
204 | |||
205 | -[no]confirm_exit |
|
205 | -[no]confirm_exit | |
206 | Set to confirm when you try to exit IPython with an EOF (Con- |
|
206 | Set to confirm when you try to exit IPython with an EOF (Con- | |
207 | trol-D in Unix, Control-Z/Enter in Windows). Note that using the |
|
207 | trol-D in Unix, Control-Z/Enter in Windows). Note that using the | |
208 | magic functions @Exit or @Quit you can force a direct exit, |
|
208 | magic functions @Exit or @Quit you can force a direct exit, | |
209 | bypassing any confirmation. |
|
209 | bypassing any confirmation. | |
210 |
|
210 | |||
211 | -[no]debug |
|
211 | -[no]debug | |
212 | Show information about the loading process. Very useful to pin |
|
212 | Show information about the loading process. Very useful to pin | |
213 | down problems with your configuration files or to get details |
|
213 | down problems with your configuration files or to get details | |
214 | about session restores. |
|
214 | about session restores. | |
215 |
|
215 | |||
216 | -[no]deep_reload |
|
216 | -[no]deep_reload | |
217 | IPython can use the deep_reload module which reloads changes in |
|
217 | IPython can use the deep_reload module which reloads changes in | |
218 | modules recursively (it replaces the reload() function, so you |
|
218 | modules recursively (it replaces the reload() function, so you | |
219 | don't need to change anything to use it). deep_reload() forces a |
|
219 | don't need to change anything to use it). deep_reload() forces a | |
220 | full reload of modules whose code may have changed, which the |
|
220 | full reload of modules whose code may have changed, which the | |
221 | default reload() function does not. |
|
221 | default reload() function does not. | |
222 |
|
222 | |||
223 | When deep_reload is off, IPython will use the normal reload(), |
|
223 | When deep_reload is off, IPython will use the normal reload(), | |
224 | but deep_reload will still be available as dreload(). This fea- |
|
224 | but deep_reload will still be available as dreload(). This fea- | |
225 | ture is off by default [which means that you have both normal |
|
225 | ture is off by default [which means that you have both normal | |
226 | reload() and dreload()]. |
|
226 | reload() and dreload()]. | |
227 |
|
227 | |||
228 | -editor <name> |
|
228 | -editor <name> | |
229 | Which editor to use with the @edit command. By default, IPython |
|
229 | Which editor to use with the @edit command. By default, IPython | |
230 | will honor your EDITOR environment variable (if not set, vi is |
|
230 | will honor your EDITOR environment variable (if not set, vi is | |
231 | the Unix default and notepad the Windows one). Since this editor |
|
231 | the Unix default and notepad the Windows one). Since this editor | |
232 | is invoked on the fly by IPython and is meant for editing small |
|
232 | is invoked on the fly by IPython and is meant for editing small | |
233 | code snippets, you may want to use a small, lightweight editor |
|
233 | code snippets, you may want to use a small, lightweight editor | |
234 | here (in case your default EDITOR is something like Emacs). |
|
234 | here (in case your default EDITOR is something like Emacs). | |
235 |
|
235 | |||
236 | -ipythondir <name> |
|
236 | -ipythondir <name> | |
237 | The name of your IPython configuration directory IPYTHONDIR. |
|
237 | The name of your IPython configuration directory IPYTHONDIR. | |
238 | This can also be specified through the environment variable |
|
238 | This can also be specified through the environment variable | |
239 | IPYTHONDIR. |
|
239 | IPYTHONDIR. | |
240 |
|
240 | |||
241 | -log|l Generate a log file of all input. The file is named |
|
241 | -log|l Generate a log file of all input. The file is named | |
242 | ipython_log.py in your current directory (which prevents logs |
|
242 | ipython_log.py in your current directory (which prevents logs | |
243 | from multiple IPython sessions from trampling each other). You |
|
243 | from multiple IPython sessions from trampling each other). You | |
244 | can use this to later restore a session by loading your logfile |
|
244 | can use this to later restore a session by loading your logfile | |
245 | as a file to be executed with option -logplay (see below). |
|
245 | as a file to be executed with option -logplay (see below). | |
246 |
|
246 | |||
247 | -logfile|lf |
|
247 | -logfile|lf | |
248 | Specify the name of your logfile. |
|
248 | Specify the name of your logfile. | |
249 |
|
249 | |||
250 | -logplay|lp |
|
250 | -logplay|lp | |
251 | Replay a previous log. For restoring a session as close as pos- |
|
251 | Replay a previous log. For restoring a session as close as pos- | |
252 | sible to the state you left it in, use this option (don't just |
|
252 | sible to the state you left it in, use this option (don't just | |
253 | run the logfile). With -logplay, IPython will try to reconstruct |
|
253 | run the logfile). With -logplay, IPython will try to reconstruct | |
254 | the previous working environment in full, not just execute the |
|
254 | the previous working environment in full, not just execute the | |
255 | commands in the logfile. |
|
255 | commands in the logfile. | |
256 | When a session is restored, logging is automatically turned on |
|
256 | When a session is restored, logging is automatically turned on | |
257 | again with the name of the logfile it was invoked with (it is |
|
257 | again with the name of the logfile it was invoked with (it is | |
258 | read from the log header). So once you've turned logging on for |
|
258 | read from the log header). So once you've turned logging on for | |
259 | a session, you can quit IPython and reload it as many times as |
|
259 | a session, you can quit IPython and reload it as many times as | |
260 | you want and it will continue to log its history and restore |
|
260 | you want and it will continue to log its history and restore | |
261 | from the beginning every time. |
|
261 | from the beginning every time. | |
262 |
|
262 | |||
263 | Caveats: there are limitations in this option. The history vari- |
|
263 | Caveats: there are limitations in this option. The history vari- | |
264 | ables _i*,_* and _dh don't get restored properly. In the future |
|
264 | ables _i*,_* and _dh don't get restored properly. In the future | |
265 | we will try to implement full session saving by writing and |
|
265 | we will try to implement full session saving by writing and | |
266 | retrieving a failed because of inherent limitations of Python's |
|
266 | retrieving a failed because of inherent limitations of Python's | |
267 | Pickle module, so this may have to wait. |
|
267 | Pickle module, so this may have to wait. | |
268 |
|
268 | |||
269 | -[no]messages |
|
269 | -[no]messages | |
270 | Print messages which IPython collects about its startup process |
|
270 | Print messages which IPython collects about its startup process | |
271 | (default on). |
|
271 | (default on). | |
272 |
|
272 | |||
273 | -[no]pdb |
|
273 | -[no]pdb | |
274 | Automatically call the pdb debugger after every uncaught excep- |
|
274 | Automatically call the pdb debugger after every uncaught excep- | |
275 | tion. If you are used to debugging using pdb, this puts you |
|
275 | tion. If you are used to debugging using pdb, this puts you | |
276 | automatically inside of it after any call (either in IPython or |
|
276 | automatically inside of it after any call (either in IPython or | |
277 | in code called by it) which triggers an exception which goes |
|
277 | in code called by it) which triggers an exception which goes | |
278 | uncaught. |
|
278 | uncaught. | |
279 |
|
279 | |||
280 | -[no]pprint |
|
280 | -[no]pprint | |
281 | IPython can optionally use the pprint (pretty printer) module |
|
281 | IPython can optionally use the pprint (pretty printer) module | |
282 | for displaying results. pprint tends to give a nicer display of |
|
282 | for displaying results. pprint tends to give a nicer display of | |
283 | nested data structures. If you like it, you can turn it on per- |
|
283 | nested data structures. If you like it, you can turn it on per- | |
284 | manently in your config file (default off). |
|
284 | manently in your config file (default off). | |
285 |
|
285 | |||
286 | -profile|p <name> |
|
286 | -profile|p <name> | |
287 | Assume that your config file is ipythonrc-<name> (looks in cur- |
|
287 | Assume that your config file is ipythonrc-<name> (looks in cur- | |
288 | rent dir first, then in IPYTHONDIR). This is a quick way to keep |
|
288 | rent dir first, then in IPYTHONDIR). This is a quick way to keep | |
289 | and load multiple config files for different tasks, especially |
|
289 | and load multiple config files for different tasks, especially | |
290 | if you use the include option of config files. You can keep a |
|
290 | if you use the include option of config files. You can keep a | |
291 | basic IPYTHONDIR/ipythonrc file and then have other 'profiles' |
|
291 | basic IPYTHONDIR/ipythonrc file and then have other 'profiles' | |
292 | which include this one and load extra things for particular |
|
292 | which include this one and load extra things for particular | |
293 | tasks. For example: |
|
293 | tasks. For example: | |
294 |
|
294 | |||
295 | 1) $HOME/.ipython/ipythonrc : load basic things you always want. |
|
295 | 1) $HOME/.ipython/ipythonrc : load basic things you always want. | |
296 | 2) $HOME/.ipython/ipythonrc-math : load (1) and basic math- |
|
296 | 2) $HOME/.ipython/ipythonrc-math : load (1) and basic math- | |
297 | related modules. |
|
297 | related modules. | |
298 | 3) $HOME/.ipython/ipythonrc-numeric : load (1) and Numeric and |
|
298 | 3) $HOME/.ipython/ipythonrc-numeric : load (1) and Numeric and | |
299 | plotting modules. |
|
299 | plotting modules. | |
300 |
|
300 | |||
301 | Since it is possible to create an endless loop by having circu- |
|
301 | Since it is possible to create an endless loop by having circu- | |
302 | lar file inclusions, IPython will stop if it reaches 15 recur- |
|
302 | lar file inclusions, IPython will stop if it reaches 15 recur- | |
303 | sive inclusions. |
|
303 | sive inclusions. | |
304 |
|
304 | |||
305 | -prompt_in1|pi1 <string> |
|
305 | -prompt_in1|pi1 <string> | |
306 | Specify the string used for input prompts. Note that if you are |
|
306 | Specify the string used for input prompts. Note that if you are | |
307 | using numbered prompts, the number is represented with a '\#' in |
|
307 | using numbered prompts, the number is represented with a '\#' in | |
308 | the string. Don't forget to quote strings with spaces embedded |
|
308 | the string. Don't forget to quote strings with spaces embedded | |
309 | in them. Default: 'In [\#]: '. |
|
309 | in them. Default: 'In [\#]: '. | |
310 |
|
310 | |||
311 | Most bash-like escapes can be used to customize IPython's |
|
311 | Most bash-like escapes can be used to customize IPython's | |
312 | prompts, as well as a few additional ones which are IPython-spe- |
|
312 | prompts, as well as a few additional ones which are IPython-spe- | |
313 | cific. All valid prompt escapes are described in detail in the |
|
313 | cific. All valid prompt escapes are described in detail in the | |
314 | Customization section of the IPython HTML/PDF manual. |
|
314 | Customization section of the IPython HTML/PDF manual. | |
315 |
|
315 | |||
316 | -prompt_in2|pi2 <string> |
|
316 | -prompt_in2|pi2 <string> | |
317 | Similar to the previous option, but used for the continuation |
|
317 | Similar to the previous option, but used for the continuation | |
318 | prompts. The special sequence '\D' is similar to '\#', but with |
|
318 | prompts. The special sequence '\D' is similar to '\#', but with | |
319 | all digits replaced dots (so you can have your continuation |
|
319 | all digits replaced dots (so you can have your continuation | |
320 | prompt aligned with your input prompt). Default: ' .\D.: ' |
|
320 | prompt aligned with your input prompt). Default: ' .\D.: ' | |
321 | (note three spaces at the start for alignment with 'In [\#]'). |
|
321 | (note three spaces at the start for alignment with 'In [\#]'). | |
322 |
|
322 | |||
323 | -prompt_out|po <string> |
|
323 | -prompt_out|po <string> | |
324 | String used for output prompts, also uses numbers like |
|
324 | String used for output prompts, also uses numbers like | |
325 | prompt_in1. Default: 'Out[\#]:'. |
|
325 | prompt_in1. Default: 'Out[\#]:'. | |
326 |
|
326 | |||
327 | -quick Start in bare bones mode (no config file loaded). |
|
327 | -quick Start in bare bones mode (no config file loaded). | |
328 |
|
328 | |||
329 | -rcfile <name> |
|
329 | -rcfile <name> | |
330 | Name of your IPython resource configuration file. normally |
|
330 | Name of your IPython resource configuration file. normally | |
331 | IPython loads ipythonrc (from current directory) or |
|
331 | IPython loads ipythonrc (from current directory) or | |
332 | IPYTHONDIR/ipythonrc. If the loading of your config file fails, |
|
332 | IPYTHONDIR/ipythonrc. If the loading of your config file fails, | |
333 | IPython starts with a bare bones configuration (no modules |
|
333 | IPython starts with a bare bones configuration (no modules | |
334 | loaded at all). |
|
334 | loaded at all). | |
335 |
|
335 | |||
336 | -[no]readline |
|
336 | -[no]readline | |
337 | Use the readline library, which is needed to support name com- |
|
337 | Use the readline library, which is needed to support name com- | |
338 | pletion and command history, among other things. It is enabled |
|
338 | pletion and command history, among other things. It is enabled | |
339 | by default, but may cause problems for users of X/Emacs in |
|
339 | by default, but may cause problems for users of X/Emacs in | |
340 | Python comint or shell buffers. |
|
340 | Python comint or shell buffers. | |
341 |
|
341 | |||
342 | Note that emacs 'eterm' buffers (opened with M-x term) support |
|
342 | Note that emacs 'eterm' buffers (opened with M-x term) support | |
343 | IPython's readline and syntax coloring fine, only 'emacs' (M-x |
|
343 | IPython's readline and syntax coloring fine, only 'emacs' (M-x | |
344 | shell and C-c !) buffers do not. |
|
344 | shell and C-c !) buffers do not. | |
345 |
|
345 | |||
346 | -screen_length|sl <n> |
|
346 | -screen_length|sl <n> | |
347 | Number of lines of your screen. This is used to control print- |
|
347 | Number of lines of your screen. This is used to control print- | |
348 | ing of very long strings. Strings longer than this number of |
|
348 | ing of very long strings. Strings longer than this number of | |
349 | lines will be sent through a pager instead of directly printed. |
|
349 | lines will be sent through a pager instead of directly printed. | |
350 |
|
350 | |||
351 | The default value for this is 0, which means IPython will auto- |
|
351 | The default value for this is 0, which means IPython will auto- | |
352 | detect your screen size every time it needs to print certain |
|
352 | detect your screen size every time it needs to print certain | |
353 | potentially long strings (this doesn't change the behavior of |
|
353 | potentially long strings (this doesn't change the behavior of | |
354 | the 'print' keyword, it's only triggered internally). If for |
|
354 | the 'print' keyword, it's only triggered internally). If for | |
355 | some reason this isn't working well (it needs curses support), |
|
355 | some reason this isn't working well (it needs curses support), | |
356 | specify it yourself. Otherwise don't change the default. |
|
356 | specify it yourself. Otherwise don't change the default. | |
357 |
|
357 | |||
358 | -separate_in|si <string> |
|
358 | -separate_in|si <string> | |
359 | Separator before input prompts. Default '0. |
|
359 | Separator before input prompts. Default '0. | |
360 |
|
360 | |||
361 | -separate_out|so <string> |
|
361 | -separate_out|so <string> | |
362 | Separator before output prompts. Default: 0 (nothing). |
|
362 | Separator before output prompts. Default: 0 (nothing). | |
363 |
|
363 | |||
364 | -separate_out2|so2 <string> |
|
364 | -separate_out2|so2 <string> | |
365 | Separator after output prompts. Default: 0 (nothing). |
|
365 | Separator after output prompts. Default: 0 (nothing). | |
366 |
|
366 | |||
367 | -nosep Shorthand for '-separate_in 0 -separate_out 0 -separate_out2 0'. |
|
367 | -nosep Shorthand for '-separate_in 0 -separate_out 0 -separate_out2 0'. | |
368 | Simply removes all input/output separators. |
|
368 | Simply removes all input/output separators. | |
369 |
|
369 | |||
370 | -upgrade |
|
370 | -upgrade | |
371 | Allows you to upgrade your IPYTHONDIR configuration when you |
|
371 | Allows you to upgrade your IPYTHONDIR configuration when you | |
372 | install a new version of IPython. Since new versions may |
|
372 | install a new version of IPython. Since new versions may | |
373 | include new command lines options or example files, this copies |
|
373 | include new command lines options or example files, this copies | |
374 | updated ipythonrc-type files. However, it backs up (with a .old |
|
374 | updated ipythonrc-type files. However, it backs up (with a .old | |
375 | extension) all files which it overwrites so that you can merge |
|
375 | extension) all files which it overwrites so that you can merge | |
376 | back any custimizations you might have in your personal files. |
|
376 | back any custimizations you might have in your personal files. | |
377 |
|
377 | |||
378 | -Version |
|
378 | -Version | |
379 | Print version information and exit. |
|
379 | Print version information and exit. | |
380 |
|
380 | |||
381 | -wxversion <string> |
|
381 | -wxversion <string> | |
382 | Select a specific version of wxPython (used in conjunction with |
|
382 | Select a specific version of wxPython (used in conjunction with | |
383 | -wthread). Requires the wxversion module, part of recent |
|
383 | -wthread). Requires the wxversion module, part of recent | |
384 | wxPython distributions. |
|
384 | wxPython distributions. | |
385 |
|
385 | |||
386 | -xmode <modename> |
|
386 | -xmode <modename> | |
387 | Mode for exception reporting. The valid modes are Plain, Con- |
|
387 | Mode for exception reporting. The valid modes are Plain, Con- | |
388 | text, and Verbose. |
|
388 | text, and Verbose. | |
389 |
|
389 | |||
390 | - Plain: similar to python's normal traceback printing. |
|
390 | - Plain: similar to python's normal traceback printing. | |
391 |
|
391 | |||
392 | - Context: prints 5 lines of context source code around each |
|
392 | - Context: prints 5 lines of context source code around each | |
393 | line in the traceback. |
|
393 | line in the traceback. | |
394 |
|
394 | |||
395 | - Verbose: similar to Context, but additionally prints the vari- |
|
395 | - Verbose: similar to Context, but additionally prints the vari- | |
396 | ables currently visible where the exception happened (shortening |
|
396 | ables currently visible where the exception happened (shortening | |
397 | their strings if too long). This can potentially be very slow, |
|
397 | their strings if too long). This can potentially be very slow, | |
398 | if you happen to have a huge data structure whose string repre- |
|
398 | if you happen to have a huge data structure whose string repre- | |
399 | sentation is complex to compute. Your computer may appear to |
|
399 | sentation is complex to compute. Your computer may appear to | |
400 | freeze for a while with cpu usage at 100%. If this occurs, you |
|
400 | freeze for a while with cpu usage at 100%. If this occurs, you | |
401 | can cancel the traceback with Ctrl-C (maybe hitting it more than |
|
401 | can cancel the traceback with Ctrl-C (maybe hitting it more than | |
402 | once). |
|
402 | once). | |
403 |
|
403 | |||
404 |
|
404 | |||
405 | EMBEDDING |
|
405 | EMBEDDING | |
406 | It is possible to start an IPython instance inside your own Python pro- |
|
406 | It is possible to start an IPython instance inside your own Python pro- | |
407 | grams. In the documentation example files there are some illustrations |
|
407 | grams. In the documentation example files there are some illustrations | |
408 | on how to do this. |
|
408 | on how to do this. | |
409 |
|
409 | |||
410 | This feature allows you to evalutate dynamically the state of your |
|
410 | This feature allows you to evalutate dynamically the state of your | |
411 | code, operate with your variables, analyze them, etc. Note however |
|
411 | code, operate with your variables, analyze them, etc. Note however | |
412 | that any changes you make to values while in the shell do NOT propagate |
|
412 | that any changes you make to values while in the shell do NOT propagate | |
413 | back to the running code, so it is safe to modify your values because |
|
413 | back to the running code, so it is safe to modify your values because | |
414 | you won't break your code in bizarre ways by doing so. |
|
414 | you won't break your code in bizarre ways by doing so. | |
415 | """ |
|
415 | """ | |
416 |
|
416 | |||
417 | cmd_line_usage = __doc__ |
|
417 | cmd_line_usage = __doc__ | |
418 |
|
418 | |||
419 | #--------------------------------------------------------------------------- |
|
419 | #--------------------------------------------------------------------------- | |
420 | interactive_usage = """ |
|
420 | interactive_usage = """ | |
421 | IPython -- An enhanced Interactive Python |
|
421 | IPython -- An enhanced Interactive Python | |
422 | ========================================= |
|
422 | ========================================= | |
423 |
|
423 | |||
424 | IPython offers a combination of convenient shell features, special commands |
|
424 | IPython offers a combination of convenient shell features, special commands | |
425 | and a history mechanism for both input (command history) and output (results |
|
425 | and a history mechanism for both input (command history) and output (results | |
426 | caching, similar to Mathematica). It is intended to be a fully compatible |
|
426 | caching, similar to Mathematica). It is intended to be a fully compatible | |
427 | replacement for the standard Python interpreter, while offering vastly |
|
427 | replacement for the standard Python interpreter, while offering vastly | |
428 | improved functionality and flexibility. |
|
428 | improved functionality and flexibility. | |
429 |
|
429 | |||
430 | At your system command line, type 'ipython -help' to see the command line |
|
430 | At your system command line, type 'ipython -help' to see the command line | |
431 | options available. This document only describes interactive features. |
|
431 | options available. This document only describes interactive features. | |
432 |
|
432 | |||
433 | Warning: IPython relies on the existence of a global variable called __IP which |
|
433 | Warning: IPython relies on the existence of a global variable called __IP which | |
434 | controls the shell itself. If you redefine __IP to anything, bizarre behavior |
|
434 | controls the shell itself. If you redefine __IP to anything, bizarre behavior | |
435 | will quickly occur. |
|
435 | will quickly occur. | |
436 |
|
436 | |||
437 | MAIN FEATURES |
|
437 | MAIN FEATURES | |
438 |
|
438 | |||
439 | * Access to the standard Python help. As of Python 2.1, a help system is |
|
439 | * Access to the standard Python help. As of Python 2.1, a help system is | |
440 | available with access to object docstrings and the Python manuals. Simply |
|
440 | available with access to object docstrings and the Python manuals. Simply | |
441 | type 'help' (no quotes) to access it. |
|
441 | type 'help' (no quotes) to access it. | |
442 |
|
442 | |||
443 | * Magic commands: type %magic for information on the magic subsystem. |
|
443 | * Magic commands: type %magic for information on the magic subsystem. | |
444 |
|
444 | |||
445 | * System command aliases, via the %alias command or the ipythonrc config file. |
|
445 | * System command aliases, via the %alias command or the ipythonrc config file. | |
446 |
|
446 | |||
447 | * Dynamic object information: |
|
447 | * Dynamic object information: | |
448 |
|
448 | |||
449 | Typing ?word or word? prints detailed information about an object. If |
|
449 | Typing ?word or word? prints detailed information about an object. If | |
450 | certain strings in the object are too long (docstrings, code, etc.) they get |
|
450 | certain strings in the object are too long (docstrings, code, etc.) they get | |
451 | snipped in the center for brevity. |
|
451 | snipped in the center for brevity. | |
452 |
|
452 | |||
453 | Typing ??word or word?? gives access to the full information without |
|
453 | Typing ??word or word?? gives access to the full information without | |
454 | snipping long strings. Long strings are sent to the screen through the less |
|
454 | snipping long strings. Long strings are sent to the screen through the less | |
455 | pager if longer than the screen, printed otherwise. |
|
455 | pager if longer than the screen, printed otherwise. | |
456 |
|
456 | |||
457 | The ?/?? system gives access to the full source code for any object (if |
|
457 | The ?/?? system gives access to the full source code for any object (if | |
458 | available), shows function prototypes and other useful information. |
|
458 | available), shows function prototypes and other useful information. | |
459 |
|
459 | |||
460 | If you just want to see an object's docstring, type '%pdoc object' (without |
|
460 | If you just want to see an object's docstring, type '%pdoc object' (without | |
461 | quotes, and without % if you have automagic on). |
|
461 | quotes, and without % if you have automagic on). | |
462 |
|
462 | |||
463 | Both %pdoc and ?/?? give you access to documentation even on things which are |
|
463 | Both %pdoc and ?/?? give you access to documentation even on things which are | |
464 | not explicitely defined. Try for example typing {}.get? or after import os, |
|
464 | not explicitely defined. Try for example typing {}.get? or after import os, | |
465 | type os.path.abspath??. The magic functions %pdef, %source and %file operate |
|
465 | type os.path.abspath??. The magic functions %pdef, %source and %file operate | |
466 | similarly. |
|
466 | similarly. | |
467 |
|
467 | |||
468 | * Completion in the local namespace, by typing TAB at the prompt. |
|
468 | * Completion in the local namespace, by typing TAB at the prompt. | |
469 |
|
469 | |||
470 | At any time, hitting tab will complete any available python commands or |
|
470 | At any time, hitting tab will complete any available python commands or | |
471 | variable names, and show you a list of the possible completions if there's |
|
471 | variable names, and show you a list of the possible completions if there's | |
472 | no unambiguous one. It will also complete filenames in the current directory. |
|
472 | no unambiguous one. It will also complete filenames in the current directory. | |
473 |
|
473 | |||
474 | This feature requires the readline and rlcomplete modules, so it won't work |
|
474 | This feature requires the readline and rlcomplete modules, so it won't work | |
475 | if your Python lacks readline support (such as under Windows). |
|
475 | if your Python lacks readline support (such as under Windows). | |
476 |
|
476 | |||
477 | * Search previous command history in two ways (also requires readline): |
|
477 | * Search previous command history in two ways (also requires readline): | |
478 |
|
478 | |||
479 | - Start typing, and then use Ctrl-p (previous,up) and Ctrl-n (next,down) to |
|
479 | - Start typing, and then use Ctrl-p (previous,up) and Ctrl-n (next,down) to | |
480 | search through only the history items that match what you've typed so |
|
480 | search through only the history items that match what you've typed so | |
481 | far. If you use Ctrl-p/Ctrl-n at a blank prompt, they just behave like |
|
481 | far. If you use Ctrl-p/Ctrl-n at a blank prompt, they just behave like | |
482 | normal arrow keys. |
|
482 | normal arrow keys. | |
483 |
|
483 | |||
484 | - Hit Ctrl-r: opens a search prompt. Begin typing and the system searches |
|
484 | - Hit Ctrl-r: opens a search prompt. Begin typing and the system searches | |
485 | your history for lines that match what you've typed so far, completing as |
|
485 | your history for lines that match what you've typed so far, completing as | |
486 | much as it can. |
|
486 | much as it can. | |
487 |
|
487 | |||
488 | * Persistent command history across sessions (readline required). |
|
488 | * Persistent command history across sessions (readline required). | |
489 |
|
489 | |||
490 | * Logging of input with the ability to save and restore a working session. |
|
490 | * Logging of input with the ability to save and restore a working session. | |
491 |
|
491 | |||
492 | * System escape with !. Typing !ls will run 'ls' in the current directory. |
|
492 | * System escape with !. Typing !ls will run 'ls' in the current directory. | |
493 |
|
493 | |||
494 | * The reload command does a 'deep' reload of a module: changes made to the |
|
494 | * The reload command does a 'deep' reload of a module: changes made to the | |
495 | module since you imported will actually be available without having to exit. |
|
495 | module since you imported will actually be available without having to exit. | |
496 |
|
496 | |||
497 | * Verbose and colored exception traceback printouts. See the magic xmode and |
|
497 | * Verbose and colored exception traceback printouts. See the magic xmode and | |
498 | xcolor functions for details (just type %magic). |
|
498 | xcolor functions for details (just type %magic). | |
499 |
|
499 | |||
500 | * Input caching system: |
|
500 | * Input caching system: | |
501 |
|
501 | |||
502 | IPython offers numbered prompts (In/Out) with input and output caching. All |
|
502 | IPython offers numbered prompts (In/Out) with input and output caching. All | |
503 | input is saved and can be retrieved as variables (besides the usual arrow |
|
503 | input is saved and can be retrieved as variables (besides the usual arrow | |
504 | key recall). |
|
504 | key recall). | |
505 |
|
505 | |||
506 | The following GLOBAL variables always exist (so don't overwrite them!): |
|
506 | The following GLOBAL variables always exist (so don't overwrite them!): | |
507 | _i: stores previous input. |
|
507 | _i: stores previous input. | |
508 | _ii: next previous. |
|
508 | _ii: next previous. | |
509 | _iii: next-next previous. |
|
509 | _iii: next-next previous. | |
510 | _ih : a list of all input _ih[n] is the input from line n. |
|
510 | _ih : a list of all input _ih[n] is the input from line n. | |
511 |
|
511 | |||
512 | Additionally, global variables named _i<n> are dynamically created (<n> |
|
512 | Additionally, global variables named _i<n> are dynamically created (<n> | |
513 | being the prompt counter), such that _i<n> == _ih[<n>] |
|
513 | being the prompt counter), such that _i<n> == _ih[<n>] | |
514 |
|
514 | |||
515 | For example, what you typed at prompt 14 is available as _i14 and _ih[14]. |
|
515 | For example, what you typed at prompt 14 is available as _i14 and _ih[14]. | |
516 |
|
516 | |||
517 | You can create macros which contain multiple input lines from this history, |
|
517 | You can create macros which contain multiple input lines from this history, | |
518 | for later re-execution, with the %macro function. |
|
518 | for later re-execution, with the %macro function. | |
519 |
|
519 | |||
520 | The history function %hist allows you to see any part of your input history |
|
520 | The history function %hist allows you to see any part of your input history | |
521 | by printing a range of the _i variables. Note that inputs which contain |
|
521 | by printing a range of the _i variables. Note that inputs which contain | |
522 | magic functions (%) appear in the history with a prepended comment. This is |
|
522 | magic functions (%) appear in the history with a prepended comment. This is | |
523 | because they aren't really valid Python code, so you can't exec them. |
|
523 | because they aren't really valid Python code, so you can't exec them. | |
524 |
|
524 | |||
525 | * Output caching system: |
|
525 | * Output caching system: | |
526 |
|
526 | |||
527 | For output that is returned from actions, a system similar to the input |
|
527 | For output that is returned from actions, a system similar to the input | |
528 | cache exists but using _ instead of _i. Only actions that produce a result |
|
528 | cache exists but using _ instead of _i. Only actions that produce a result | |
529 | (NOT assignments, for example) are cached. If you are familiar with |
|
529 | (NOT assignments, for example) are cached. If you are familiar with | |
530 | Mathematica, IPython's _ variables behave exactly like Mathematica's % |
|
530 | Mathematica, IPython's _ variables behave exactly like Mathematica's % | |
531 | variables. |
|
531 | variables. | |
532 |
|
532 | |||
533 | The following GLOBAL variables always exist (so don't overwrite them!): |
|
533 | The following GLOBAL variables always exist (so don't overwrite them!): | |
534 | _ (one underscore): previous output. |
|
534 | _ (one underscore): previous output. | |
535 | __ (two underscores): next previous. |
|
535 | __ (two underscores): next previous. | |
536 | ___ (three underscores): next-next previous. |
|
536 | ___ (three underscores): next-next previous. | |
537 |
|
537 | |||
538 | Global variables named _<n> are dynamically created (<n> being the prompt |
|
538 | Global variables named _<n> are dynamically created (<n> being the prompt | |
539 | counter), such that the result of output <n> is always available as _<n>. |
|
539 | counter), such that the result of output <n> is always available as _<n>. | |
540 |
|
540 | |||
541 | Finally, a global dictionary named _oh exists with entries for all lines |
|
541 | Finally, a global dictionary named _oh exists with entries for all lines | |
542 | which generated output. |
|
542 | which generated output. | |
543 |
|
543 | |||
544 | * Directory history: |
|
544 | * Directory history: | |
545 |
|
545 | |||
546 | Your history of visited directories is kept in the global list _dh, and the |
|
546 | Your history of visited directories is kept in the global list _dh, and the | |
547 | magic %cd command can be used to go to any entry in that list. |
|
547 | magic %cd command can be used to go to any entry in that list. | |
548 |
|
548 | |||
549 | * Auto-parentheses and auto-quotes (adapted from Nathan Gray's LazyPython) |
|
549 | * Auto-parentheses and auto-quotes (adapted from Nathan Gray's LazyPython) | |
550 |
|
550 | |||
551 | 1. Auto-parentheses |
|
551 | 1. Auto-parentheses | |
552 | Callable objects (i.e. functions, methods, etc) can be invoked like |
|
552 | Callable objects (i.e. functions, methods, etc) can be invoked like | |
553 | this (notice the commas between the arguments): |
|
553 | this (notice the commas between the arguments): | |
554 | >>> callable_ob arg1, arg2, arg3 |
|
554 | >>> callable_ob arg1, arg2, arg3 | |
555 | and the input will be translated to this: |
|
555 | and the input will be translated to this: | |
556 | --> callable_ob(arg1, arg2, arg3) |
|
556 | --> callable_ob(arg1, arg2, arg3) | |
557 | You can force auto-parentheses by using '/' as the first character |
|
557 | You can force auto-parentheses by using '/' as the first character | |
558 | of a line. For example: |
|
558 | of a line. For example: | |
559 | >>> /globals # becomes 'globals()' |
|
559 | >>> /globals # becomes 'globals()' | |
560 | Note that the '/' MUST be the first character on the line! This |
|
560 | Note that the '/' MUST be the first character on the line! This | |
561 | won't work: |
|
561 | won't work: | |
562 | >>> print /globals # syntax error |
|
562 | >>> print /globals # syntax error | |
563 |
|
563 | |||
564 | In most cases the automatic algorithm should work, so you should |
|
564 | In most cases the automatic algorithm should work, so you should | |
565 | rarely need to explicitly invoke /. One notable exception is if you |
|
565 | rarely need to explicitly invoke /. One notable exception is if you | |
566 | are trying to call a function with a list of tuples as arguments (the |
|
566 | are trying to call a function with a list of tuples as arguments (the | |
567 | parenthesis will confuse IPython): |
|
567 | parenthesis will confuse IPython): | |
568 | In [1]: zip (1,2,3),(4,5,6) # won't work |
|
568 | In [1]: zip (1,2,3),(4,5,6) # won't work | |
569 | but this will work: |
|
569 | but this will work: | |
570 | In [2]: /zip (1,2,3),(4,5,6) |
|
570 | In [2]: /zip (1,2,3),(4,5,6) | |
571 | ------> zip ((1,2,3),(4,5,6)) |
|
571 | ------> zip ((1,2,3),(4,5,6)) | |
572 | Out[2]= [(1, 4), (2, 5), (3, 6)] |
|
572 | Out[2]= [(1, 4), (2, 5), (3, 6)] | |
573 |
|
573 | |||
574 | IPython tells you that it has altered your command line by |
|
574 | IPython tells you that it has altered your command line by | |
575 | displaying the new command line preceded by -->. e.g.: |
|
575 | displaying the new command line preceded by -->. e.g.: | |
576 | In [18]: callable list |
|
576 | In [18]: callable list | |
577 | -------> callable (list) |
|
577 | -------> callable (list) | |
578 |
|
578 | |||
579 | 2. Auto-Quoting |
|
579 | 2. Auto-Quoting | |
580 | You can force auto-quoting of a function's arguments by using ',' as |
|
580 | You can force auto-quoting of a function's arguments by using ',' as | |
581 | the first character of a line. For example: |
|
581 | the first character of a line. For example: | |
582 | >>> ,my_function /home/me # becomes my_function("/home/me") |
|
582 | >>> ,my_function /home/me # becomes my_function("/home/me") | |
583 |
|
583 | |||
584 | If you use ';' instead, the whole argument is quoted as a single |
|
584 | If you use ';' instead, the whole argument is quoted as a single | |
585 | string (while ',' splits on whitespace): |
|
585 | string (while ',' splits on whitespace): | |
586 | >>> ,my_function a b c # becomes my_function("a","b","c") |
|
586 | >>> ,my_function a b c # becomes my_function("a","b","c") | |
587 | >>> ;my_function a b c # becomes my_function("a b c") |
|
587 | >>> ;my_function a b c # becomes my_function("a b c") | |
588 |
|
588 | |||
589 | Note that the ',' MUST be the first character on the line! This |
|
589 | Note that the ',' MUST be the first character on the line! This | |
590 | won't work: |
|
590 | won't work: | |
591 | >>> x = ,my_function /home/me # syntax error |
|
591 | >>> x = ,my_function /home/me # syntax error | |
592 | """ |
|
592 | """ | |
593 |
|
593 | |||
594 | quick_reference = r""" |
|
594 | quick_reference = r""" | |
595 | IPython -- An enhanced Interactive Python - Quick Reference Card |
|
595 | IPython -- An enhanced Interactive Python - Quick Reference Card | |
596 | ================================================================ |
|
596 | ================================================================ | |
597 |
|
597 | |||
598 | obj?, obj?? : Get help, or more help for object (also works as |
|
598 | obj?, obj?? : Get help, or more help for object (also works as | |
599 | ?obj, ??obj). |
|
599 | ?obj, ??obj). | |
600 | ?foo.*abc* : List names in 'foo' containing 'abc' in them. |
|
600 | ?foo.*abc* : List names in 'foo' containing 'abc' in them. | |
601 | %magic : Information about IPython's 'magic' % functions. |
|
601 | %magic : Information about IPython's 'magic' % functions. | |
602 |
|
602 | |||
603 | Magic functions are prefixed by %, and typically take their arguments without |
|
603 | Magic functions are prefixed by %, and typically take their arguments without | |
604 | parentheses, quotes or even commas for convenience. |
|
604 | parentheses, quotes or even commas for convenience. | |
605 |
|
605 | |||
606 | Example magic function calls: |
|
606 | Example magic function calls: | |
607 |
|
607 | |||
608 | %alias d ls -F : 'd' is now an alias for 'ls -F' |
|
608 | %alias d ls -F : 'd' is now an alias for 'ls -F' | |
609 | alias d ls -F : Works if 'alias' not a python name |
|
609 | alias d ls -F : Works if 'alias' not a python name | |
610 | alist = %alias : Get list of aliases to 'alist' |
|
610 | alist = %alias : Get list of aliases to 'alist' | |
611 | cd /usr/share : Obvious. cd -<tab> to choose from visited dirs. |
|
611 | cd /usr/share : Obvious. cd -<tab> to choose from visited dirs. | |
612 | %cd?? : See help AND source for magic %cd |
|
612 | %cd?? : See help AND source for magic %cd | |
613 |
|
613 | |||
614 | System commands: |
|
614 | System commands: | |
615 |
|
615 | |||
616 | !cp a.txt b/ : System command escape, calls os.system() |
|
616 | !cp a.txt b/ : System command escape, calls os.system() | |
617 | cp a.txt b/ : after %rehashx, most system commands work without ! |
|
617 | cp a.txt b/ : after %rehashx, most system commands work without ! | |
618 | cp ${f}.txt $bar : Variable expansion in magics and system commands |
|
618 | cp ${f}.txt $bar : Variable expansion in magics and system commands | |
619 | files = !ls /usr : Capture sytem command output |
|
619 | files = !ls /usr : Capture sytem command output | |
620 | files.s, files.l, files.n: "a b c", ['a','b','c'], 'a\nb\nc' |
|
620 | files.s, files.l, files.n: "a b c", ['a','b','c'], 'a\nb\nc' | |
621 |
|
621 | |||
622 | History: |
|
622 | History: | |
623 |
|
623 | |||
624 | _i, _ii, _iii : Previous, next previous, next next previous input |
|
624 | _i, _ii, _iii : Previous, next previous, next next previous input | |
625 | _i4, _ih[2:5] : Input history line 4, lines 2-4 |
|
625 | _i4, _ih[2:5] : Input history line 4, lines 2-4 | |
626 | exec _i81 : Execute input history line #81 again |
|
626 | exec _i81 : Execute input history line #81 again | |
627 | %rep 81 : Edit input history line #81 |
|
627 | %rep 81 : Edit input history line #81 | |
628 | _, __, ___ : previous, next previous, next next previous output |
|
628 | _, __, ___ : previous, next previous, next next previous output | |
629 | _dh : Directory history |
|
629 | _dh : Directory history | |
630 | _oh : Output history |
|
630 | _oh : Output history | |
631 | %hist : Command history. '%hist -g foo' search history for 'foo' |
|
631 | %hist : Command history. '%hist -g foo' search history for 'foo' | |
632 |
|
632 | |||
633 | Autocall: |
|
633 | Autocall: | |
634 |
|
634 | |||
635 | f 1,2 : f(1,2) |
|
635 | f 1,2 : f(1,2) | |
636 | /f 1,2 : f(1,2) (forced autoparen) |
|
636 | /f 1,2 : f(1,2) (forced autoparen) | |
637 | ,f 1 2 : f("1","2") |
|
637 | ,f 1 2 : f("1","2") | |
638 | ;f 1 2 : f("1 2") |
|
638 | ;f 1 2 : f("1 2") | |
639 |
|
639 | |||
640 | Remember: TAB completion works in many contexts, not just file names |
|
640 | Remember: TAB completion works in many contexts, not just file names | |
641 | or python names. |
|
641 | or python names. | |
642 |
|
642 | |||
643 | The following magic functions are currently available: |
|
643 | The following magic functions are currently available: | |
644 |
|
644 | |||
645 | """ |
|
645 | """ |
General Comments 0
You need to be logged in to leave comments.
Login now