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