Show More
The requested changes are too big and content was truncated. Show full diff
@@ -0,0 +1,10 b'' | |||||
|
1 | #!/usr/bin/env python | |||
|
2 | # encoding: utf-8 | |||
|
3 | ||||
|
4 | def test_import_configloader(): | |||
|
5 | from IPython.config import configloader | |||
|
6 | ||||
|
7 | def test_import_userconfig(): | |||
|
8 | from IPython.config import userconfig | |||
|
9 | ||||
|
10 |
This diff has been collapsed as it changes many lines, (685 lines changed) Show them Hide them | |||||
@@ -0,0 +1,685 b'' | |||||
|
1 | """IPython customization API | |||
|
2 | ||||
|
3 | Your one-stop module for configuring & extending ipython | |||
|
4 | ||||
|
5 | The API will probably break when ipython 1.0 is released, but so | |||
|
6 | will the other configuration method (rc files). | |||
|
7 | ||||
|
8 | All names prefixed by underscores are for internal use, not part | |||
|
9 | of the public api. | |||
|
10 | ||||
|
11 | Below is an example that you can just put to a module and import from ipython. | |||
|
12 | ||||
|
13 | A good practice is to install the config script below as e.g. | |||
|
14 | ||||
|
15 | ~/.ipython/my_private_conf.py | |||
|
16 | ||||
|
17 | And do | |||
|
18 | ||||
|
19 | import_mod my_private_conf | |||
|
20 | ||||
|
21 | in ~/.ipython/ipythonrc | |||
|
22 | ||||
|
23 | That way the module is imported at startup and you can have all your | |||
|
24 | personal configuration (as opposed to boilerplate ipythonrc-PROFILENAME | |||
|
25 | stuff) in there. | |||
|
26 | ||||
|
27 | from IPython.core import ipapi | |||
|
28 | ip = ipapi.get() | |||
|
29 | ||||
|
30 | def ankka_f(self, arg): | |||
|
31 | print 'Ankka',self,'says uppercase:',arg.upper() | |||
|
32 | ||||
|
33 | ip.expose_magic('ankka',ankka_f) | |||
|
34 | ||||
|
35 | ip.magic('alias sayhi echo "Testing, hi ok"') | |||
|
36 | ip.magic('alias helloworld echo "Hello world"') | |||
|
37 | ip.system('pwd') | |||
|
38 | ||||
|
39 | ip.ex('import re') | |||
|
40 | ip.ex(''' | |||
|
41 | def funcci(a,b): | |||
|
42 | print a+b | |||
|
43 | print funcci(3,4) | |||
|
44 | ''') | |||
|
45 | ip.ex('funcci(348,9)') | |||
|
46 | ||||
|
47 | def jed_editor(self,filename, linenum=None): | |||
|
48 | print 'Calling my own editor, jed ... via hook!' | |||
|
49 | import os | |||
|
50 | if linenum is None: linenum = 0 | |||
|
51 | os.system('jed +%d %s' % (linenum, filename)) | |||
|
52 | print 'exiting jed' | |||
|
53 | ||||
|
54 | ip.set_hook('editor',jed_editor) | |||
|
55 | ||||
|
56 | o = ip.options | |||
|
57 | o.autocall = 2 # FULL autocall mode | |||
|
58 | ||||
|
59 | print 'done!' | |||
|
60 | """ | |||
|
61 | ||||
|
62 | #----------------------------------------------------------------------------- | |||
|
63 | # Modules and globals | |||
|
64 | ||||
|
65 | # stdlib imports | |||
|
66 | import __builtin__ | |||
|
67 | import sys | |||
|
68 | ||||
|
69 | # contains the most recently instantiated IPApi | |||
|
70 | _RECENT_IP = None | |||
|
71 | ||||
|
72 | #----------------------------------------------------------------------------- | |||
|
73 | # Code begins | |||
|
74 | ||||
|
75 | class TryNext(Exception): | |||
|
76 | """Try next hook exception. | |||
|
77 | ||||
|
78 | Raise this in your hook function to indicate that the next hook handler | |||
|
79 | should be used to handle the operation. If you pass arguments to the | |||
|
80 | constructor those arguments will be used by the next hook instead of the | |||
|
81 | original ones. | |||
|
82 | """ | |||
|
83 | ||||
|
84 | def __init__(self, *args, **kwargs): | |||
|
85 | self.args = args | |||
|
86 | self.kwargs = kwargs | |||
|
87 | ||||
|
88 | ||||
|
89 | class UsageError(Exception): | |||
|
90 | """ Error in magic function arguments, etc. | |||
|
91 | ||||
|
92 | Something that probably won't warrant a full traceback, but should | |||
|
93 | nevertheless interrupt a macro / batch file. | |||
|
94 | """ | |||
|
95 | ||||
|
96 | ||||
|
97 | class IPyAutocall: | |||
|
98 | """ Instances of this class are always autocalled | |||
|
99 | ||||
|
100 | This happens regardless of 'autocall' variable state. Use this to | |||
|
101 | develop macro-like mechanisms. | |||
|
102 | """ | |||
|
103 | ||||
|
104 | def set_ip(self,ip): | |||
|
105 | """ Will be used to set _ip point to current ipython instance b/f call | |||
|
106 | ||||
|
107 | Override this method if you don't want this to happen. | |||
|
108 | ||||
|
109 | """ | |||
|
110 | self._ip = ip | |||
|
111 | ||||
|
112 | ||||
|
113 | class IPythonNotRunning: | |||
|
114 | """Dummy do-nothing class. | |||
|
115 | ||||
|
116 | Instances of this class return a dummy attribute on all accesses, which | |||
|
117 | can be called and warns. This makes it easier to write scripts which use | |||
|
118 | the ipapi.get() object for informational purposes to operate both with and | |||
|
119 | without ipython. Obviously code which uses the ipython object for | |||
|
120 | computations will not work, but this allows a wider range of code to | |||
|
121 | transparently work whether ipython is being used or not.""" | |||
|
122 | ||||
|
123 | def __init__(self,warn=True): | |||
|
124 | if warn: | |||
|
125 | self.dummy = self._dummy_warn | |||
|
126 | else: | |||
|
127 | self.dummy = self._dummy_silent | |||
|
128 | ||||
|
129 | def __str__(self): | |||
|
130 | return "<IPythonNotRunning>" | |||
|
131 | ||||
|
132 | __repr__ = __str__ | |||
|
133 | ||||
|
134 | def __getattr__(self,name): | |||
|
135 | return self.dummy | |||
|
136 | ||||
|
137 | def _dummy_warn(self,*args,**kw): | |||
|
138 | """Dummy function, which doesn't do anything but warn.""" | |||
|
139 | ||||
|
140 | print ("IPython is not running, this is a dummy no-op function") | |||
|
141 | ||||
|
142 | def _dummy_silent(self,*args,**kw): | |||
|
143 | """Dummy function, which doesn't do anything and emits no warnings.""" | |||
|
144 | pass | |||
|
145 | ||||
|
146 | ||||
|
147 | def get(allow_dummy=False,dummy_warn=True): | |||
|
148 | """Get an IPApi object. | |||
|
149 | ||||
|
150 | If allow_dummy is true, returns an instance of IPythonNotRunning | |||
|
151 | instead of None if not running under IPython. | |||
|
152 | ||||
|
153 | If dummy_warn is false, the dummy instance will be completely silent. | |||
|
154 | ||||
|
155 | Running this should be the first thing you do when writing extensions that | |||
|
156 | can be imported as normal modules. You can then direct all the | |||
|
157 | configuration operations against the returned object. | |||
|
158 | """ | |||
|
159 | global _RECENT_IP | |||
|
160 | if allow_dummy and not _RECENT_IP: | |||
|
161 | _RECENT_IP = IPythonNotRunning(dummy_warn) | |||
|
162 | return _RECENT_IP | |||
|
163 | ||||
|
164 | ||||
|
165 | class IPApi(object): | |||
|
166 | """ The actual API class for configuring IPython | |||
|
167 | ||||
|
168 | You should do all of the IPython configuration by getting an IPApi object | |||
|
169 | with IPython.ipapi.get() and using the attributes and methods of the | |||
|
170 | returned object.""" | |||
|
171 | ||||
|
172 | def __init__(self,ip): | |||
|
173 | ||||
|
174 | global _RECENT_IP | |||
|
175 | ||||
|
176 | # All attributes exposed here are considered to be the public API of | |||
|
177 | # IPython. As needs dictate, some of these may be wrapped as | |||
|
178 | # properties. | |||
|
179 | ||||
|
180 | self.magic = ip.ipmagic | |||
|
181 | ||||
|
182 | self.system = ip.system | |||
|
183 | ||||
|
184 | self.set_hook = ip.set_hook | |||
|
185 | ||||
|
186 | self.set_custom_exc = ip.set_custom_exc | |||
|
187 | ||||
|
188 | self.user_ns = ip.user_ns | |||
|
189 | ||||
|
190 | self.set_crash_handler = ip.set_crash_handler | |||
|
191 | ||||
|
192 | # Session-specific data store, which can be used to store | |||
|
193 | # data that should persist through the ipython session. | |||
|
194 | self.meta = ip.meta | |||
|
195 | ||||
|
196 | # The ipython instance provided | |||
|
197 | self.IP = ip | |||
|
198 | ||||
|
199 | self.extensions = {} | |||
|
200 | ||||
|
201 | self.dbg = DebugTools(self) | |||
|
202 | ||||
|
203 | _RECENT_IP = self | |||
|
204 | ||||
|
205 | # Use a property for some things which are added to the instance very | |||
|
206 | # late. I don't have time right now to disentangle the initialization | |||
|
207 | # order issues, so a property lets us delay item extraction while | |||
|
208 | # providing a normal attribute API. | |||
|
209 | def get_db(self): | |||
|
210 | """A handle to persistent dict-like database (a PickleShareDB object)""" | |||
|
211 | return self.IP.db | |||
|
212 | ||||
|
213 | db = property(get_db,None,None,get_db.__doc__) | |||
|
214 | ||||
|
215 | def get_options(self): | |||
|
216 | """All configurable variables.""" | |||
|
217 | ||||
|
218 | # catch typos by disabling new attribute creation. If new attr creation | |||
|
219 | # is in fact wanted (e.g. when exposing new options), do | |||
|
220 | # allow_new_attr(True) for the received rc struct. | |||
|
221 | ||||
|
222 | self.IP.rc.allow_new_attr(False) | |||
|
223 | return self.IP.rc | |||
|
224 | ||||
|
225 | options = property(get_options,None,None,get_options.__doc__) | |||
|
226 | ||||
|
227 | def expose_magic(self,magicname, func): | |||
|
228 | """Expose own function as magic function for ipython | |||
|
229 | ||||
|
230 | def foo_impl(self,parameter_s=''): | |||
|
231 | 'My very own magic!. (Use docstrings, IPython reads them).' | |||
|
232 | print 'Magic function. Passed parameter is between < >:' | |||
|
233 | print '<%s>' % parameter_s | |||
|
234 | print 'The self object is:',self | |||
|
235 | ||||
|
236 | ipapi.expose_magic('foo',foo_impl) | |||
|
237 | """ | |||
|
238 | ||||
|
239 | import new | |||
|
240 | im = new.instancemethod(func,self.IP, self.IP.__class__) | |||
|
241 | old = getattr(self.IP, "magic_" + magicname, None) | |||
|
242 | if old: | |||
|
243 | self.dbg.debug_stack("Magic redefinition '%s', old %s" % | |||
|
244 | (magicname,old) ) | |||
|
245 | ||||
|
246 | setattr(self.IP, "magic_" + magicname, im) | |||
|
247 | ||||
|
248 | def ex(self,cmd): | |||
|
249 | """ Execute a normal python statement in user namespace """ | |||
|
250 | exec cmd in self.user_ns | |||
|
251 | ||||
|
252 | def ev(self,expr): | |||
|
253 | """ Evaluate python expression expr in user namespace | |||
|
254 | ||||
|
255 | Returns the result of evaluation""" | |||
|
256 | return eval(expr,self.user_ns) | |||
|
257 | ||||
|
258 | def runlines(self,lines): | |||
|
259 | """ Run the specified lines in interpreter, honoring ipython directives. | |||
|
260 | ||||
|
261 | This allows %magic and !shell escape notations. | |||
|
262 | ||||
|
263 | Takes either all lines in one string or list of lines. | |||
|
264 | """ | |||
|
265 | ||||
|
266 | def cleanup_ipy_script(script): | |||
|
267 | """ Make a script safe for _ip.runlines() | |||
|
268 | ||||
|
269 | - Removes empty lines Suffixes all indented blocks that end with | |||
|
270 | - unindented lines with empty lines | |||
|
271 | """ | |||
|
272 | ||||
|
273 | res = [] | |||
|
274 | lines = script.splitlines() | |||
|
275 | ||||
|
276 | level = 0 | |||
|
277 | for l in lines: | |||
|
278 | lstripped = l.lstrip() | |||
|
279 | stripped = l.strip() | |||
|
280 | if not stripped: | |||
|
281 | continue | |||
|
282 | newlevel = len(l) - len(lstripped) | |||
|
283 | def is_secondary_block_start(s): | |||
|
284 | if not s.endswith(':'): | |||
|
285 | return False | |||
|
286 | if (s.startswith('elif') or | |||
|
287 | s.startswith('else') or | |||
|
288 | s.startswith('except') or | |||
|
289 | s.startswith('finally')): | |||
|
290 | return True | |||
|
291 | ||||
|
292 | if level > 0 and newlevel == 0 and \ | |||
|
293 | not is_secondary_block_start(stripped): | |||
|
294 | # add empty line | |||
|
295 | res.append('') | |||
|
296 | ||||
|
297 | res.append(l) | |||
|
298 | level = newlevel | |||
|
299 | return '\n'.join(res) + '\n' | |||
|
300 | ||||
|
301 | if isinstance(lines,basestring): | |||
|
302 | script = lines | |||
|
303 | else: | |||
|
304 | script = '\n'.join(lines) | |||
|
305 | clean=cleanup_ipy_script(script) | |||
|
306 | # print "_ip.runlines() script:\n",clean # dbg | |||
|
307 | self.IP.runlines(clean) | |||
|
308 | ||||
|
309 | def to_user_ns(self,vars, interactive = True): | |||
|
310 | """Inject a group of variables into the IPython user namespace. | |||
|
311 | ||||
|
312 | Inputs: | |||
|
313 | ||||
|
314 | - vars: string with variable names separated by whitespace, or a | |||
|
315 | dict with name/value pairs. | |||
|
316 | ||||
|
317 | - interactive: if True (default), the var will be listed with | |||
|
318 | %whos et. al. | |||
|
319 | ||||
|
320 | This utility routine is meant to ease interactive debugging work, | |||
|
321 | where you want to easily propagate some internal variable in your code | |||
|
322 | up to the interactive namespace for further exploration. | |||
|
323 | ||||
|
324 | When you run code via %run, globals in your script become visible at | |||
|
325 | the interactive prompt, but this doesn't happen for locals inside your | |||
|
326 | own functions and methods. Yet when debugging, it is common to want | |||
|
327 | to explore some internal variables further at the interactive propmt. | |||
|
328 | ||||
|
329 | Examples: | |||
|
330 | ||||
|
331 | To use this, you first must obtain a handle on the ipython object as | |||
|
332 | indicated above, via: | |||
|
333 | ||||
|
334 | from IPython.core import ipapi | |||
|
335 | ip = ipapi.get() | |||
|
336 | ||||
|
337 | Once this is done, inside a routine foo() where you want to expose | |||
|
338 | variables x and y, you do the following: | |||
|
339 | ||||
|
340 | def foo(): | |||
|
341 | ... | |||
|
342 | x = your_computation() | |||
|
343 | y = something_else() | |||
|
344 | ||||
|
345 | # This pushes x and y to the interactive prompt immediately, even | |||
|
346 | # if this routine crashes on the next line after: | |||
|
347 | ip.to_user_ns('x y') | |||
|
348 | ... | |||
|
349 | ||||
|
350 | # To expose *ALL* the local variables from the function, use: | |||
|
351 | ip.to_user_ns(locals()) | |||
|
352 | ||||
|
353 | ... | |||
|
354 | # return | |||
|
355 | ||||
|
356 | ||||
|
357 | If you need to rename variables, the dict input makes it easy. For | |||
|
358 | example, this call exposes variables 'foo' as 'x' and 'bar' as 'y' | |||
|
359 | in IPython user namespace: | |||
|
360 | ||||
|
361 | ip.to_user_ns(dict(x=foo,y=bar)) | |||
|
362 | """ | |||
|
363 | ||||
|
364 | # print 'vars given:',vars # dbg | |||
|
365 | ||||
|
366 | # We need a dict of name/value pairs to do namespace updates. | |||
|
367 | if isinstance(vars,dict): | |||
|
368 | # If a dict was given, no need to change anything. | |||
|
369 | vdict = vars | |||
|
370 | elif isinstance(vars,basestring): | |||
|
371 | # If a string with names was given, get the caller's frame to | |||
|
372 | # evaluate the given names in | |||
|
373 | cf = sys._getframe(1) | |||
|
374 | vdict = {} | |||
|
375 | for name in vars.split(): | |||
|
376 | try: | |||
|
377 | vdict[name] = eval(name,cf.f_globals,cf.f_locals) | |||
|
378 | except: | |||
|
379 | print ('could not get var. %s from %s' % | |||
|
380 | (name,cf.f_code.co_name)) | |||
|
381 | else: | |||
|
382 | raise ValueError('vars must be a string or a dict') | |||
|
383 | ||||
|
384 | # Propagate variables to user namespace | |||
|
385 | self.user_ns.update(vdict) | |||
|
386 | ||||
|
387 | # And configure interactive visibility | |||
|
388 | config_ns = self.IP.user_config_ns | |||
|
389 | if interactive: | |||
|
390 | for name,val in vdict.iteritems(): | |||
|
391 | config_ns.pop(name,None) | |||
|
392 | else: | |||
|
393 | for name,val in vdict.iteritems(): | |||
|
394 | config_ns[name] = val | |||
|
395 | ||||
|
396 | def expand_alias(self,line): | |||
|
397 | """ Expand an alias in the command line | |||
|
398 | ||||
|
399 | Returns the provided command line, possibly with the first word | |||
|
400 | (command) translated according to alias expansion rules. | |||
|
401 | ||||
|
402 | [ipython]|16> _ip.expand_aliases("np myfile.txt") | |||
|
403 | <16> 'q:/opt/np/notepad++.exe myfile.txt' | |||
|
404 | """ | |||
|
405 | ||||
|
406 | pre,fn,rest = self.IP.split_user_input(line) | |||
|
407 | res = pre + self.IP.expand_aliases(fn,rest) | |||
|
408 | return res | |||
|
409 | ||||
|
410 | def itpl(self, s, depth = 1): | |||
|
411 | """ Expand Itpl format string s. | |||
|
412 | ||||
|
413 | Only callable from command line (i.e. prefilter results); | |||
|
414 | If you use in your scripts, you need to use a bigger depth! | |||
|
415 | """ | |||
|
416 | return self.IP.var_expand(s, depth) | |||
|
417 | ||||
|
418 | def defalias(self, name, cmd): | |||
|
419 | """ Define a new alias | |||
|
420 | ||||
|
421 | _ip.defalias('bb','bldmake bldfiles') | |||
|
422 | ||||
|
423 | Creates a new alias named 'bb' in ipython user namespace | |||
|
424 | """ | |||
|
425 | ||||
|
426 | self.dbg.check_hotname(name) | |||
|
427 | ||||
|
428 | if name in self.IP.alias_table: | |||
|
429 | self.dbg.debug_stack("Alias redefinition: '%s' => '%s' (old '%s')" | |||
|
430 | % (name, cmd, self.IP.alias_table[name])) | |||
|
431 | ||||
|
432 | if callable(cmd): | |||
|
433 | self.IP.alias_table[name] = cmd | |||
|
434 | from IPython.core import shadowns | |||
|
435 | setattr(shadowns, name,cmd) | |||
|
436 | return | |||
|
437 | ||||
|
438 | if isinstance(cmd,basestring): | |||
|
439 | nargs = cmd.count('%s') | |||
|
440 | if nargs>0 and cmd.find('%l')>=0: | |||
|
441 | raise Exception('The %s and %l specifiers are mutually ' | |||
|
442 | 'exclusive in alias definitions.') | |||
|
443 | ||||
|
444 | self.IP.alias_table[name] = (nargs,cmd) | |||
|
445 | return | |||
|
446 | ||||
|
447 | # just put it in - it's probably (0,'foo') | |||
|
448 | self.IP.alias_table[name] = cmd | |||
|
449 | ||||
|
450 | def defmacro(self, *args): | |||
|
451 | """ Define a new macro | |||
|
452 | ||||
|
453 | 2 forms of calling: | |||
|
454 | ||||
|
455 | mac = _ip.defmacro('print "hello"\nprint "world"') | |||
|
456 | ||||
|
457 | (doesn't put the created macro on user namespace) | |||
|
458 | ||||
|
459 | _ip.defmacro('build', 'bldmake bldfiles\nabld build winscw udeb') | |||
|
460 | ||||
|
461 | (creates a macro named 'build' in user namespace) | |||
|
462 | """ | |||
|
463 | ||||
|
464 | from IPython.core import macro | |||
|
465 | ||||
|
466 | if len(args) == 1: | |||
|
467 | return macro.Macro(args[0]) | |||
|
468 | elif len(args) == 2: | |||
|
469 | self.user_ns[args[0]] = macro.Macro(args[1]) | |||
|
470 | else: | |||
|
471 | return Exception("_ip.defmacro must be called with 1 or 2 arguments") | |||
|
472 | ||||
|
473 | def set_next_input(self, s): | |||
|
474 | """ Sets the 'default' input string for the next command line. | |||
|
475 | ||||
|
476 | Requires readline. | |||
|
477 | ||||
|
478 | Example: | |||
|
479 | ||||
|
480 | [D:\ipython]|1> _ip.set_next_input("Hello Word") | |||
|
481 | [D:\ipython]|2> Hello Word_ # cursor is here | |||
|
482 | """ | |||
|
483 | ||||
|
484 | self.IP.rl_next_input = s | |||
|
485 | ||||
|
486 | def load(self, mod): | |||
|
487 | """ Load an extension. | |||
|
488 | ||||
|
489 | Some modules should (or must) be 'load()':ed, rather than just imported. | |||
|
490 | ||||
|
491 | Loading will do: | |||
|
492 | ||||
|
493 | - run init_ipython(ip) | |||
|
494 | - run ipython_firstrun(ip) | |||
|
495 | """ | |||
|
496 | ||||
|
497 | if mod in self.extensions: | |||
|
498 | # just to make sure we don't init it twice | |||
|
499 | # note that if you 'load' a module that has already been | |||
|
500 | # imported, init_ipython gets run anyway | |||
|
501 | ||||
|
502 | return self.extensions[mod] | |||
|
503 | __import__(mod) | |||
|
504 | m = sys.modules[mod] | |||
|
505 | if hasattr(m,'init_ipython'): | |||
|
506 | m.init_ipython(self) | |||
|
507 | ||||
|
508 | if hasattr(m,'ipython_firstrun'): | |||
|
509 | already_loaded = self.db.get('firstrun_done', set()) | |||
|
510 | if mod not in already_loaded: | |||
|
511 | m.ipython_firstrun(self) | |||
|
512 | already_loaded.add(mod) | |||
|
513 | self.db['firstrun_done'] = already_loaded | |||
|
514 | ||||
|
515 | self.extensions[mod] = m | |||
|
516 | return m | |||
|
517 | ||||
|
518 | ||||
|
519 | class DebugTools: | |||
|
520 | """ Used for debugging mishaps in api usage | |||
|
521 | ||||
|
522 | So far, tracing redefinitions is supported. | |||
|
523 | """ | |||
|
524 | ||||
|
525 | def __init__(self, ip): | |||
|
526 | self.ip = ip | |||
|
527 | self.debugmode = False | |||
|
528 | self.hotnames = set() | |||
|
529 | ||||
|
530 | def hotname(self, name_to_catch): | |||
|
531 | self.hotnames.add(name_to_catch) | |||
|
532 | ||||
|
533 | def debug_stack(self, msg = None): | |||
|
534 | if not self.debugmode: | |||
|
535 | return | |||
|
536 | ||||
|
537 | import traceback | |||
|
538 | if msg is not None: | |||
|
539 | print '====== %s ========' % msg | |||
|
540 | traceback.print_stack() | |||
|
541 | ||||
|
542 | def check_hotname(self,name): | |||
|
543 | if name in self.hotnames: | |||
|
544 | self.debug_stack( "HotName '%s' caught" % name) | |||
|
545 | ||||
|
546 | ||||
|
547 | def launch_new_instance(user_ns = None,shellclass = None): | |||
|
548 | """ Make and start a new ipython instance. | |||
|
549 | ||||
|
550 | This can be called even without having an already initialized | |||
|
551 | ipython session running. | |||
|
552 | ||||
|
553 | This is also used as the egg entry point for the 'ipython' script. | |||
|
554 | ||||
|
555 | """ | |||
|
556 | ses = make_session(user_ns,shellclass) | |||
|
557 | ses.mainloop() | |||
|
558 | ||||
|
559 | ||||
|
560 | def make_user_ns(user_ns = None): | |||
|
561 | """Return a valid user interactive namespace. | |||
|
562 | ||||
|
563 | This builds a dict with the minimal information needed to operate as a | |||
|
564 | valid IPython user namespace, which you can pass to the various embedding | |||
|
565 | classes in ipython. | |||
|
566 | ||||
|
567 | This API is currently deprecated. Use ipapi.make_user_namespaces() instead | |||
|
568 | to make both the local and global namespace objects simultaneously. | |||
|
569 | ||||
|
570 | :Parameters: | |||
|
571 | user_ns : dict-like, optional | |||
|
572 | The current user namespace. The items in this namespace should be | |||
|
573 | included in the output. If None, an appropriate blank namespace | |||
|
574 | should be created. | |||
|
575 | ||||
|
576 | :Returns: | |||
|
577 | A dictionary-like object to be used as the local namespace of the | |||
|
578 | interpreter. | |||
|
579 | """ | |||
|
580 | ||||
|
581 | raise NotImplementedError | |||
|
582 | ||||
|
583 | ||||
|
584 | def make_user_global_ns(ns = None): | |||
|
585 | """Return a valid user global namespace. | |||
|
586 | ||||
|
587 | Similar to make_user_ns(), but global namespaces are really only needed in | |||
|
588 | embedded applications, where there is a distinction between the user's | |||
|
589 | interactive namespace and the global one where ipython is running. | |||
|
590 | ||||
|
591 | This API is currently deprecated. Use ipapi.make_user_namespaces() instead | |||
|
592 | to make both the local and global namespace objects simultaneously. | |||
|
593 | ||||
|
594 | :Parameters: | |||
|
595 | ns : dict, optional | |||
|
596 | The current user global namespace. The items in this namespace | |||
|
597 | should be included in the output. If None, an appropriate blank | |||
|
598 | namespace should be created. | |||
|
599 | ||||
|
600 | :Returns: | |||
|
601 | A true dict to be used as the global namespace of the interpreter. | |||
|
602 | """ | |||
|
603 | ||||
|
604 | raise NotImplementedError | |||
|
605 | ||||
|
606 | # Record the true objects in order to be able to test if the user has overridden | |||
|
607 | # these API functions. | |||
|
608 | _make_user_ns = make_user_ns | |||
|
609 | _make_user_global_ns = make_user_global_ns | |||
|
610 | ||||
|
611 | ||||
|
612 | def make_user_namespaces(user_ns = None,user_global_ns = None): | |||
|
613 | """Return a valid local and global user interactive namespaces. | |||
|
614 | ||||
|
615 | This builds a dict with the minimal information needed to operate as a | |||
|
616 | valid IPython user namespace, which you can pass to the various embedding | |||
|
617 | classes in ipython. The default implementation returns the same dict for | |||
|
618 | both the locals and the globals to allow functions to refer to variables in | |||
|
619 | the namespace. Customized implementations can return different dicts. The | |||
|
620 | locals dictionary can actually be anything following the basic mapping | |||
|
621 | protocol of a dict, but the globals dict must be a true dict, not even | |||
|
622 | a subclass. It is recommended that any custom object for the locals | |||
|
623 | namespace synchronize with the globals dict somehow. | |||
|
624 | ||||
|
625 | Raises TypeError if the provided globals namespace is not a true dict. | |||
|
626 | ||||
|
627 | :Parameters: | |||
|
628 | user_ns : dict-like, optional | |||
|
629 | The current user namespace. The items in this namespace should be | |||
|
630 | included in the output. If None, an appropriate blank namespace | |||
|
631 | should be created. | |||
|
632 | user_global_ns : dict, optional | |||
|
633 | The current user global namespace. The items in this namespace | |||
|
634 | should be included in the output. If None, an appropriate blank | |||
|
635 | namespace should be created. | |||
|
636 | ||||
|
637 | :Returns: | |||
|
638 | A tuple pair of dictionary-like object to be used as the local namespace | |||
|
639 | of the interpreter and a dict to be used as the global namespace. | |||
|
640 | """ | |||
|
641 | ||||
|
642 | if user_ns is None: | |||
|
643 | if make_user_ns is not _make_user_ns: | |||
|
644 | # Old API overridden. | |||
|
645 | # FIXME: Issue DeprecationWarning, or just let the old API live on? | |||
|
646 | user_ns = make_user_ns(user_ns) | |||
|
647 | else: | |||
|
648 | # Set __name__ to __main__ to better match the behavior of the | |||
|
649 | # normal interpreter. | |||
|
650 | user_ns = {'__name__' :'__main__', | |||
|
651 | '__builtins__' : __builtin__, | |||
|
652 | } | |||
|
653 | else: | |||
|
654 | user_ns.setdefault('__name__','__main__') | |||
|
655 | user_ns.setdefault('__builtins__',__builtin__) | |||
|
656 | ||||
|
657 | if user_global_ns is None: | |||
|
658 | if make_user_global_ns is not _make_user_global_ns: | |||
|
659 | # Old API overridden. | |||
|
660 | user_global_ns = make_user_global_ns(user_global_ns) | |||
|
661 | else: | |||
|
662 | user_global_ns = user_ns | |||
|
663 | if type(user_global_ns) is not dict: | |||
|
664 | raise TypeError("user_global_ns must be a true dict; got %r" | |||
|
665 | % type(user_global_ns)) | |||
|
666 | ||||
|
667 | return user_ns, user_global_ns | |||
|
668 | ||||
|
669 | ||||
|
670 | def make_session(user_ns = None, shellclass = None): | |||
|
671 | """Makes, but does not launch an IPython session. | |||
|
672 | ||||
|
673 | Later on you can call obj.mainloop() on the returned object. | |||
|
674 | ||||
|
675 | Inputs: | |||
|
676 | ||||
|
677 | - user_ns(None): a dict to be used as the user's namespace with initial | |||
|
678 | data. | |||
|
679 | ||||
|
680 | WARNING: This should *not* be run when a session exists already.""" | |||
|
681 | ||||
|
682 | import IPython.core.shell | |||
|
683 | if shellclass is None: | |||
|
684 | return IPython.core.shell.start(user_ns) | |||
|
685 | return shellclass(user_ns = user_ns) |
This diff has been collapsed as it changes many lines, (2865 lines changed) Show them Hide them | |||||
@@ -0,0 +1,2865 b'' | |||||
|
1 | # -*- coding: utf-8 -*- | |||
|
2 | """ | |||
|
3 | IPython -- An enhanced Interactive Python | |||
|
4 | ||||
|
5 | Requires Python 2.4 or newer. | |||
|
6 | ||||
|
7 | This file contains all the classes and helper functions specific to IPython. | |||
|
8 | """ | |||
|
9 | ||||
|
10 | #***************************************************************************** | |||
|
11 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and | |||
|
12 | # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu> | |||
|
13 | # | |||
|
14 | # Distributed under the terms of the BSD License. The full license is in | |||
|
15 | # the file COPYING, distributed as part of this software. | |||
|
16 | # | |||
|
17 | # Note: this code originally subclassed code.InteractiveConsole from the | |||
|
18 | # Python standard library. Over time, all of that class has been copied | |||
|
19 | # verbatim here for modifications which could not be accomplished by | |||
|
20 | # subclassing. At this point, there are no dependencies at all on the code | |||
|
21 | # module anymore (it is not even imported). The Python License (sec. 2) | |||
|
22 | # allows for this, but it's always nice to acknowledge credit where credit is | |||
|
23 | # due. | |||
|
24 | #***************************************************************************** | |||
|
25 | ||||
|
26 | #**************************************************************************** | |||
|
27 | # Modules and globals | |||
|
28 | ||||
|
29 | # Python standard modules | |||
|
30 | import __main__ | |||
|
31 | import __builtin__ | |||
|
32 | import StringIO | |||
|
33 | import bdb | |||
|
34 | import codeop | |||
|
35 | import exceptions | |||
|
36 | import glob | |||
|
37 | import keyword | |||
|
38 | import new | |||
|
39 | import os | |||
|
40 | import re | |||
|
41 | import shutil | |||
|
42 | import string | |||
|
43 | import sys | |||
|
44 | import tempfile | |||
|
45 | ||||
|
46 | # IPython's own modules | |||
|
47 | #import IPython | |||
|
48 | from IPython.core import ultratb | |||
|
49 | from IPython.utils import PyColorize | |||
|
50 | from IPython.core import debugger, oinspect | |||
|
51 | from IPython.extensions import pickleshare | |||
|
52 | from IPython.core.fakemodule import FakeModule, init_fakemod_dict | |||
|
53 | from IPython.external.Itpl import ItplNS | |||
|
54 | from IPython.core.logger import Logger | |||
|
55 | from IPython.core.magic import Magic | |||
|
56 | from IPython.core.prompts import CachedOutput | |||
|
57 | from IPython.utils.ipstruct import Struct | |||
|
58 | from IPython.lib.backgroundjobs import BackgroundJobManager | |||
|
59 | from IPython.utils.genutils import * | |||
|
60 | from IPython.utils.strdispatch import StrDispatch | |||
|
61 | from IPython.core import ipapi | |||
|
62 | import IPython.core.history | |||
|
63 | import IPython.core.prefilter as prefilter | |||
|
64 | from IPython.core import shadowns | |||
|
65 | # Globals | |||
|
66 | ||||
|
67 | # store the builtin raw_input globally, and use this always, in case user code | |||
|
68 | # overwrites it (like wx.py.PyShell does) | |||
|
69 | raw_input_original = raw_input | |||
|
70 | ||||
|
71 | # compiled regexps for autoindent management | |||
|
72 | dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass') | |||
|
73 | ||||
|
74 | ||||
|
75 | #**************************************************************************** | |||
|
76 | # Some utility function definitions | |||
|
77 | ||||
|
78 | ini_spaces_re = re.compile(r'^(\s+)') | |||
|
79 | ||||
|
80 | def num_ini_spaces(strng): | |||
|
81 | """Return the number of initial spaces in a string""" | |||
|
82 | ||||
|
83 | ini_spaces = ini_spaces_re.match(strng) | |||
|
84 | if ini_spaces: | |||
|
85 | return ini_spaces.end() | |||
|
86 | else: | |||
|
87 | return 0 | |||
|
88 | ||||
|
89 | def softspace(file, newvalue): | |||
|
90 | """Copied from code.py, to remove the dependency""" | |||
|
91 | ||||
|
92 | oldvalue = 0 | |||
|
93 | try: | |||
|
94 | oldvalue = file.softspace | |||
|
95 | except AttributeError: | |||
|
96 | pass | |||
|
97 | try: | |||
|
98 | file.softspace = newvalue | |||
|
99 | except (AttributeError, TypeError): | |||
|
100 | # "attribute-less object" or "read-only attributes" | |||
|
101 | pass | |||
|
102 | return oldvalue | |||
|
103 | ||||
|
104 | ||||
|
105 | def user_setup(ipythondir,rc_suffix,mode='install',interactive=True): | |||
|
106 | """Install or upgrade the user configuration directory. | |||
|
107 | ||||
|
108 | Can be called when running for the first time or to upgrade the user's | |||
|
109 | .ipython/ directory. | |||
|
110 | ||||
|
111 | Parameters | |||
|
112 | ---------- | |||
|
113 | ipythondir : path | |||
|
114 | The directory to be used for installation/upgrade. In 'install' mode, | |||
|
115 | if this path already exists, the function exits immediately. | |||
|
116 | ||||
|
117 | rc_suffix : str | |||
|
118 | Extension for the config files. On *nix platforms it is typically the | |||
|
119 | empty string, while Windows normally uses '.ini'. | |||
|
120 | ||||
|
121 | mode : str, optional | |||
|
122 | Valid modes are 'install' and 'upgrade'. | |||
|
123 | ||||
|
124 | interactive : bool, optional | |||
|
125 | If False, do not wait for user input on any errors. Normally after | |||
|
126 | printing its status information, this function waits for the user to | |||
|
127 | hit Return before proceeding. This is because the default use case is | |||
|
128 | when first installing the IPython configuration, so we want the user to | |||
|
129 | acknowledge the initial message, which contains some useful | |||
|
130 | information. | |||
|
131 | """ | |||
|
132 | ||||
|
133 | # For automatic use, deactivate all i/o | |||
|
134 | if interactive: | |||
|
135 | def wait(): | |||
|
136 | try: | |||
|
137 | raw_input("Please press <RETURN> to start IPython.") | |||
|
138 | except EOFError: | |||
|
139 | print >> Term.cout | |||
|
140 | print '*'*70 | |||
|
141 | ||||
|
142 | def printf(s): | |||
|
143 | print s | |||
|
144 | else: | |||
|
145 | wait = lambda : None | |||
|
146 | printf = lambda s : None | |||
|
147 | ||||
|
148 | # Install mode should be re-entrant: if the install dir already exists, | |||
|
149 | # bail out cleanly. | |||
|
150 | # XXX. This is too hasty to return. We need to check to make sure that | |||
|
151 | # all the expected config files and directories are actually there. We | |||
|
152 | # currently have a failure mode if someone deletes a needed config file | |||
|
153 | # but still has the ipythondir. | |||
|
154 | if mode == 'install' and os.path.isdir(ipythondir): | |||
|
155 | return | |||
|
156 | ||||
|
157 | cwd = os.getcwd() # remember where we started | |||
|
158 | glb = glob.glob | |||
|
159 | ||||
|
160 | printf('*'*70) | |||
|
161 | if mode == 'install': | |||
|
162 | printf( | |||
|
163 | """Welcome to IPython. I will try to create a personal configuration directory | |||
|
164 | where you can customize many aspects of IPython's functionality in:\n""") | |||
|
165 | else: | |||
|
166 | printf('I am going to upgrade your configuration in:') | |||
|
167 | ||||
|
168 | printf(ipythondir) | |||
|
169 | ||||
|
170 | rcdirend = os.path.join('IPython','config','userconfig') | |||
|
171 | cfg = lambda d: os.path.join(d,rcdirend) | |||
|
172 | try: | |||
|
173 | rcdir = filter(os.path.isdir,map(cfg,sys.path))[0] | |||
|
174 | printf("Initializing from configuration: %s" % rcdir) | |||
|
175 | except IndexError: | |||
|
176 | warning = """ | |||
|
177 | Installation error. IPython's directory was not found. | |||
|
178 | ||||
|
179 | Check the following: | |||
|
180 | ||||
|
181 | The ipython/IPython directory should be in a directory belonging to your | |||
|
182 | PYTHONPATH environment variable (that is, it should be in a directory | |||
|
183 | belonging to sys.path). You can copy it explicitly there or just link to it. | |||
|
184 | ||||
|
185 | IPython will create a minimal default configuration for you. | |||
|
186 | ||||
|
187 | """ | |||
|
188 | warn(warning) | |||
|
189 | wait() | |||
|
190 | ||||
|
191 | if sys.platform =='win32': | |||
|
192 | inif = 'ipythonrc.ini' | |||
|
193 | else: | |||
|
194 | inif = 'ipythonrc' | |||
|
195 | minimal_setup = {'ipy_user_conf.py' : 'import ipy_defaults', | |||
|
196 | inif : '# intentionally left blank' } | |||
|
197 | os.makedirs(ipythondir, mode = 0777) | |||
|
198 | for f, cont in minimal_setup.items(): | |||
|
199 | # In 2.5, this can be more cleanly done using 'with' | |||
|
200 | fobj = file(ipythondir + '/' + f,'w') | |||
|
201 | fobj.write(cont) | |||
|
202 | fobj.close() | |||
|
203 | ||||
|
204 | return | |||
|
205 | ||||
|
206 | if mode == 'install': | |||
|
207 | try: | |||
|
208 | shutil.copytree(rcdir,ipythondir) | |||
|
209 | os.chdir(ipythondir) | |||
|
210 | rc_files = glb("ipythonrc*") | |||
|
211 | for rc_file in rc_files: | |||
|
212 | os.rename(rc_file,rc_file+rc_suffix) | |||
|
213 | except: | |||
|
214 | warning = """ | |||
|
215 | ||||
|
216 | There was a problem with the installation: | |||
|
217 | %s | |||
|
218 | Try to correct it or contact the developers if you think it's a bug. | |||
|
219 | IPython will proceed with builtin defaults.""" % sys.exc_info()[1] | |||
|
220 | warn(warning) | |||
|
221 | wait() | |||
|
222 | return | |||
|
223 | ||||
|
224 | elif mode == 'upgrade': | |||
|
225 | try: | |||
|
226 | os.chdir(ipythondir) | |||
|
227 | except: | |||
|
228 | printf(""" | |||
|
229 | Can not upgrade: changing to directory %s failed. Details: | |||
|
230 | %s | |||
|
231 | """ % (ipythondir,sys.exc_info()[1]) ) | |||
|
232 | wait() | |||
|
233 | return | |||
|
234 | else: | |||
|
235 | sources = glb(os.path.join(rcdir,'[A-Za-z]*')) | |||
|
236 | for new_full_path in sources: | |||
|
237 | new_filename = os.path.basename(new_full_path) | |||
|
238 | if new_filename.startswith('ipythonrc'): | |||
|
239 | new_filename = new_filename + rc_suffix | |||
|
240 | # The config directory should only contain files, skip any | |||
|
241 | # directories which may be there (like CVS) | |||
|
242 | if os.path.isdir(new_full_path): | |||
|
243 | continue | |||
|
244 | if os.path.exists(new_filename): | |||
|
245 | old_file = new_filename+'.old' | |||
|
246 | if os.path.exists(old_file): | |||
|
247 | os.remove(old_file) | |||
|
248 | os.rename(new_filename,old_file) | |||
|
249 | shutil.copy(new_full_path,new_filename) | |||
|
250 | else: | |||
|
251 | raise ValueError('unrecognized mode for install: %r' % mode) | |||
|
252 | ||||
|
253 | # Fix line-endings to those native to each platform in the config | |||
|
254 | # directory. | |||
|
255 | try: | |||
|
256 | os.chdir(ipythondir) | |||
|
257 | except: | |||
|
258 | printf(""" | |||
|
259 | Problem: changing to directory %s failed. | |||
|
260 | Details: | |||
|
261 | %s | |||
|
262 | ||||
|
263 | Some configuration files may have incorrect line endings. This should not | |||
|
264 | cause any problems during execution. """ % (ipythondir,sys.exc_info()[1]) ) | |||
|
265 | wait() | |||
|
266 | else: | |||
|
267 | for fname in glb('ipythonrc*'): | |||
|
268 | try: | |||
|
269 | native_line_ends(fname,backup=0) | |||
|
270 | except IOError: | |||
|
271 | pass | |||
|
272 | ||||
|
273 | if mode == 'install': | |||
|
274 | printf(""" | |||
|
275 | Successful installation! | |||
|
276 | ||||
|
277 | Please read the sections 'Initial Configuration' and 'Quick Tips' in the | |||
|
278 | IPython manual (there are both HTML and PDF versions supplied with the | |||
|
279 | distribution) to make sure that your system environment is properly configured | |||
|
280 | to take advantage of IPython's features. | |||
|
281 | ||||
|
282 | Important note: the configuration system has changed! The old system is | |||
|
283 | still in place, but its setting may be partly overridden by the settings in | |||
|
284 | "~/.ipython/ipy_user_conf.py" config file. Please take a look at the file | |||
|
285 | if some of the new settings bother you. | |||
|
286 | ||||
|
287 | """) | |||
|
288 | else: | |||
|
289 | printf(""" | |||
|
290 | Successful upgrade! | |||
|
291 | ||||
|
292 | All files in your directory: | |||
|
293 | %(ipythondir)s | |||
|
294 | which would have been overwritten by the upgrade were backed up with a .old | |||
|
295 | extension. If you had made particular customizations in those files you may | |||
|
296 | want to merge them back into the new files.""" % locals() ) | |||
|
297 | wait() | |||
|
298 | os.chdir(cwd) | |||
|
299 | ||||
|
300 | #**************************************************************************** | |||
|
301 | # Local use exceptions | |||
|
302 | class SpaceInInput(exceptions.Exception): pass | |||
|
303 | ||||
|
304 | ||||
|
305 | #**************************************************************************** | |||
|
306 | # Local use classes | |||
|
307 | class Bunch: pass | |||
|
308 | ||||
|
309 | class Undefined: pass | |||
|
310 | ||||
|
311 | class Quitter(object): | |||
|
312 | """Simple class to handle exit, similar to Python 2.5's. | |||
|
313 | ||||
|
314 | It handles exiting in an ipython-safe manner, which the one in Python 2.5 | |||
|
315 | doesn't do (obviously, since it doesn't know about ipython).""" | |||
|
316 | ||||
|
317 | def __init__(self,shell,name): | |||
|
318 | self.shell = shell | |||
|
319 | self.name = name | |||
|
320 | ||||
|
321 | def __repr__(self): | |||
|
322 | return 'Type %s() to exit.' % self.name | |||
|
323 | __str__ = __repr__ | |||
|
324 | ||||
|
325 | def __call__(self): | |||
|
326 | self.shell.exit() | |||
|
327 | ||||
|
328 | class InputList(list): | |||
|
329 | """Class to store user input. | |||
|
330 | ||||
|
331 | It's basically a list, but slices return a string instead of a list, thus | |||
|
332 | allowing things like (assuming 'In' is an instance): | |||
|
333 | ||||
|
334 | exec In[4:7] | |||
|
335 | ||||
|
336 | or | |||
|
337 | ||||
|
338 | exec In[5:9] + In[14] + In[21:25]""" | |||
|
339 | ||||
|
340 | def __getslice__(self,i,j): | |||
|
341 | return ''.join(list.__getslice__(self,i,j)) | |||
|
342 | ||||
|
343 | class SyntaxTB(ultratb.ListTB): | |||
|
344 | """Extension which holds some state: the last exception value""" | |||
|
345 | ||||
|
346 | def __init__(self,color_scheme = 'NoColor'): | |||
|
347 | ultratb.ListTB.__init__(self,color_scheme) | |||
|
348 | self.last_syntax_error = None | |||
|
349 | ||||
|
350 | def __call__(self, etype, value, elist): | |||
|
351 | self.last_syntax_error = value | |||
|
352 | ultratb.ListTB.__call__(self,etype,value,elist) | |||
|
353 | ||||
|
354 | def clear_err_state(self): | |||
|
355 | """Return the current error state and clear it""" | |||
|
356 | e = self.last_syntax_error | |||
|
357 | self.last_syntax_error = None | |||
|
358 | return e | |||
|
359 | ||||
|
360 | #**************************************************************************** | |||
|
361 | # Main IPython class | |||
|
362 | ||||
|
363 | # FIXME: the Magic class is a mixin for now, and will unfortunately remain so | |||
|
364 | # until a full rewrite is made. I've cleaned all cross-class uses of | |||
|
365 | # attributes and methods, but too much user code out there relies on the | |||
|
366 | # equlity %foo == __IP.magic_foo, so I can't actually remove the mixin usage. | |||
|
367 | # | |||
|
368 | # But at least now, all the pieces have been separated and we could, in | |||
|
369 | # principle, stop using the mixin. This will ease the transition to the | |||
|
370 | # chainsaw branch. | |||
|
371 | ||||
|
372 | # For reference, the following is the list of 'self.foo' uses in the Magic | |||
|
373 | # class as of 2005-12-28. These are names we CAN'T use in the main ipython | |||
|
374 | # class, to prevent clashes. | |||
|
375 | ||||
|
376 | # ['self.__class__', 'self.__dict__', 'self._inspect', 'self._ofind', | |||
|
377 | # 'self.arg_err', 'self.extract_input', 'self.format_', 'self.lsmagic', | |||
|
378 | # 'self.magic_', 'self.options_table', 'self.parse', 'self.shell', | |||
|
379 | # 'self.value'] | |||
|
380 | ||||
|
381 | class InteractiveShell(object,Magic): | |||
|
382 | """An enhanced console for Python.""" | |||
|
383 | ||||
|
384 | # class attribute to indicate whether the class supports threads or not. | |||
|
385 | # Subclasses with thread support should override this as needed. | |||
|
386 | isthreaded = False | |||
|
387 | ||||
|
388 | def __init__(self,name,usage=None,rc=Struct(opts=None,args=None), | |||
|
389 | user_ns=None,user_global_ns=None,banner2='', | |||
|
390 | custom_exceptions=((),None),embedded=False): | |||
|
391 | ||||
|
392 | # log system | |||
|
393 | self.logger = Logger(self,logfname='ipython_log.py',logmode='rotate') | |||
|
394 | ||||
|
395 | # Job manager (for jobs run as background threads) | |||
|
396 | self.jobs = BackgroundJobManager() | |||
|
397 | ||||
|
398 | # Store the actual shell's name | |||
|
399 | self.name = name | |||
|
400 | self.more = False | |||
|
401 | ||||
|
402 | # We need to know whether the instance is meant for embedding, since | |||
|
403 | # global/local namespaces need to be handled differently in that case | |||
|
404 | self.embedded = embedded | |||
|
405 | if embedded: | |||
|
406 | # Control variable so users can, from within the embedded instance, | |||
|
407 | # permanently deactivate it. | |||
|
408 | self.embedded_active = True | |||
|
409 | ||||
|
410 | # command compiler | |||
|
411 | self.compile = codeop.CommandCompiler() | |||
|
412 | ||||
|
413 | # User input buffer | |||
|
414 | self.buffer = [] | |||
|
415 | ||||
|
416 | # Default name given in compilation of code | |||
|
417 | self.filename = '<ipython console>' | |||
|
418 | ||||
|
419 | # Install our own quitter instead of the builtins. For python2.3-2.4, | |||
|
420 | # this brings in behavior like 2.5, and for 2.5 it's identical. | |||
|
421 | __builtin__.exit = Quitter(self,'exit') | |||
|
422 | __builtin__.quit = Quitter(self,'quit') | |||
|
423 | ||||
|
424 | # Make an empty namespace, which extension writers can rely on both | |||
|
425 | # existing and NEVER being used by ipython itself. This gives them a | |||
|
426 | # convenient location for storing additional information and state | |||
|
427 | # their extensions may require, without fear of collisions with other | |||
|
428 | # ipython names that may develop later. | |||
|
429 | self.meta = Struct() | |||
|
430 | ||||
|
431 | # Create the namespace where the user will operate. user_ns is | |||
|
432 | # normally the only one used, and it is passed to the exec calls as | |||
|
433 | # the locals argument. But we do carry a user_global_ns namespace | |||
|
434 | # given as the exec 'globals' argument, This is useful in embedding | |||
|
435 | # situations where the ipython shell opens in a context where the | |||
|
436 | # distinction between locals and globals is meaningful. For | |||
|
437 | # non-embedded contexts, it is just the same object as the user_ns dict. | |||
|
438 | ||||
|
439 | # FIXME. For some strange reason, __builtins__ is showing up at user | |||
|
440 | # level as a dict instead of a module. This is a manual fix, but I | |||
|
441 | # should really track down where the problem is coming from. Alex | |||
|
442 | # Schmolck reported this problem first. | |||
|
443 | ||||
|
444 | # A useful post by Alex Martelli on this topic: | |||
|
445 | # Re: inconsistent value from __builtins__ | |||
|
446 | # Von: Alex Martelli <aleaxit@yahoo.com> | |||
|
447 | # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends | |||
|
448 | # Gruppen: comp.lang.python | |||
|
449 | ||||
|
450 | # Michael Hohn <hohn@hooknose.lbl.gov> wrote: | |||
|
451 | # > >>> print type(builtin_check.get_global_binding('__builtins__')) | |||
|
452 | # > <type 'dict'> | |||
|
453 | # > >>> print type(__builtins__) | |||
|
454 | # > <type 'module'> | |||
|
455 | # > Is this difference in return value intentional? | |||
|
456 | ||||
|
457 | # Well, it's documented that '__builtins__' can be either a dictionary | |||
|
458 | # or a module, and it's been that way for a long time. Whether it's | |||
|
459 | # intentional (or sensible), I don't know. In any case, the idea is | |||
|
460 | # that if you need to access the built-in namespace directly, you | |||
|
461 | # should start with "import __builtin__" (note, no 's') which will | |||
|
462 | # definitely give you a module. Yeah, it's somewhat confusing:-(. | |||
|
463 | ||||
|
464 | # These routines return properly built dicts as needed by the rest of | |||
|
465 | # the code, and can also be used by extension writers to generate | |||
|
466 | # properly initialized namespaces. | |||
|
467 | user_ns, user_global_ns = ipapi.make_user_namespaces(user_ns, | |||
|
468 | user_global_ns) | |||
|
469 | ||||
|
470 | # Assign namespaces | |||
|
471 | # This is the namespace where all normal user variables live | |||
|
472 | self.user_ns = user_ns | |||
|
473 | self.user_global_ns = user_global_ns | |||
|
474 | ||||
|
475 | # An auxiliary namespace that checks what parts of the user_ns were | |||
|
476 | # loaded at startup, so we can list later only variables defined in | |||
|
477 | # actual interactive use. Since it is always a subset of user_ns, it | |||
|
478 | # doesn't need to be seaparately tracked in the ns_table | |||
|
479 | self.user_config_ns = {} | |||
|
480 | ||||
|
481 | # A namespace to keep track of internal data structures to prevent | |||
|
482 | # them from cluttering user-visible stuff. Will be updated later | |||
|
483 | self.internal_ns = {} | |||
|
484 | ||||
|
485 | # Namespace of system aliases. Each entry in the alias | |||
|
486 | # table must be a 2-tuple of the form (N,name), where N is the number | |||
|
487 | # of positional arguments of the alias. | |||
|
488 | self.alias_table = {} | |||
|
489 | ||||
|
490 | # Now that FakeModule produces a real module, we've run into a nasty | |||
|
491 | # problem: after script execution (via %run), the module where the user | |||
|
492 | # code ran is deleted. Now that this object is a true module (needed | |||
|
493 | # so docetst and other tools work correctly), the Python module | |||
|
494 | # teardown mechanism runs over it, and sets to None every variable | |||
|
495 | # present in that module. Top-level references to objects from the | |||
|
496 | # script survive, because the user_ns is updated with them. However, | |||
|
497 | # calling functions defined in the script that use other things from | |||
|
498 | # the script will fail, because the function's closure had references | |||
|
499 | # to the original objects, which are now all None. So we must protect | |||
|
500 | # these modules from deletion by keeping a cache. | |||
|
501 | # | |||
|
502 | # To avoid keeping stale modules around (we only need the one from the | |||
|
503 | # last run), we use a dict keyed with the full path to the script, so | |||
|
504 | # only the last version of the module is held in the cache. Note, | |||
|
505 | # however, that we must cache the module *namespace contents* (their | |||
|
506 | # __dict__). Because if we try to cache the actual modules, old ones | |||
|
507 | # (uncached) could be destroyed while still holding references (such as | |||
|
508 | # those held by GUI objects that tend to be long-lived)> | |||
|
509 | # | |||
|
510 | # The %reset command will flush this cache. See the cache_main_mod() | |||
|
511 | # and clear_main_mod_cache() methods for details on use. | |||
|
512 | ||||
|
513 | # This is the cache used for 'main' namespaces | |||
|
514 | self._main_ns_cache = {} | |||
|
515 | # And this is the single instance of FakeModule whose __dict__ we keep | |||
|
516 | # copying and clearing for reuse on each %run | |||
|
517 | self._user_main_module = FakeModule() | |||
|
518 | ||||
|
519 | # A table holding all the namespaces IPython deals with, so that | |||
|
520 | # introspection facilities can search easily. | |||
|
521 | self.ns_table = {'user':user_ns, | |||
|
522 | 'user_global':user_global_ns, | |||
|
523 | 'alias':self.alias_table, | |||
|
524 | 'internal':self.internal_ns, | |||
|
525 | 'builtin':__builtin__.__dict__ | |||
|
526 | } | |||
|
527 | ||||
|
528 | # Similarly, track all namespaces where references can be held and that | |||
|
529 | # we can safely clear (so it can NOT include builtin). This one can be | |||
|
530 | # a simple list. | |||
|
531 | self.ns_refs_table = [ user_ns, user_global_ns, self.user_config_ns, | |||
|
532 | self.alias_table, self.internal_ns, | |||
|
533 | self._main_ns_cache ] | |||
|
534 | ||||
|
535 | # We need to insert into sys.modules something that looks like a | |||
|
536 | # module but which accesses the IPython namespace, for shelve and | |||
|
537 | # pickle to work interactively. Normally they rely on getting | |||
|
538 | # everything out of __main__, but for embedding purposes each IPython | |||
|
539 | # instance has its own private namespace, so we can't go shoving | |||
|
540 | # everything into __main__. | |||
|
541 | ||||
|
542 | # note, however, that we should only do this for non-embedded | |||
|
543 | # ipythons, which really mimic the __main__.__dict__ with their own | |||
|
544 | # namespace. Embedded instances, on the other hand, should not do | |||
|
545 | # this because they need to manage the user local/global namespaces | |||
|
546 | # only, but they live within a 'normal' __main__ (meaning, they | |||
|
547 | # shouldn't overtake the execution environment of the script they're | |||
|
548 | # embedded in). | |||
|
549 | ||||
|
550 | if not embedded: | |||
|
551 | try: | |||
|
552 | main_name = self.user_ns['__name__'] | |||
|
553 | except KeyError: | |||
|
554 | raise KeyError,'user_ns dictionary MUST have a "__name__" key' | |||
|
555 | else: | |||
|
556 | #print "pickle hack in place" # dbg | |||
|
557 | #print 'main_name:',main_name # dbg | |||
|
558 | sys.modules[main_name] = FakeModule(self.user_ns) | |||
|
559 | ||||
|
560 | # List of input with multi-line handling. | |||
|
561 | self.input_hist = InputList() | |||
|
562 | # This one will hold the 'raw' input history, without any | |||
|
563 | # pre-processing. This will allow users to retrieve the input just as | |||
|
564 | # it was exactly typed in by the user, with %hist -r. | |||
|
565 | self.input_hist_raw = InputList() | |||
|
566 | ||||
|
567 | # list of visited directories | |||
|
568 | try: | |||
|
569 | self.dir_hist = [os.getcwd()] | |||
|
570 | except OSError: | |||
|
571 | self.dir_hist = [] | |||
|
572 | ||||
|
573 | # dict of output history | |||
|
574 | self.output_hist = {} | |||
|
575 | ||||
|
576 | # Get system encoding at startup time. Certain terminals (like Emacs | |||
|
577 | # under Win32 have it set to None, and we need to have a known valid | |||
|
578 | # encoding to use in the raw_input() method | |||
|
579 | try: | |||
|
580 | self.stdin_encoding = sys.stdin.encoding or 'ascii' | |||
|
581 | except AttributeError: | |||
|
582 | self.stdin_encoding = 'ascii' | |||
|
583 | ||||
|
584 | # dict of things NOT to alias (keywords, builtins and some magics) | |||
|
585 | no_alias = {} | |||
|
586 | no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias'] | |||
|
587 | for key in keyword.kwlist + no_alias_magics: | |||
|
588 | no_alias[key] = 1 | |||
|
589 | no_alias.update(__builtin__.__dict__) | |||
|
590 | self.no_alias = no_alias | |||
|
591 | ||||
|
592 | # Object variable to store code object waiting execution. This is | |||
|
593 | # used mainly by the multithreaded shells, but it can come in handy in | |||
|
594 | # other situations. No need to use a Queue here, since it's a single | |||
|
595 | # item which gets cleared once run. | |||
|
596 | self.code_to_run = None | |||
|
597 | ||||
|
598 | # escapes for automatic behavior on the command line | |||
|
599 | self.ESC_SHELL = '!' | |||
|
600 | self.ESC_SH_CAP = '!!' | |||
|
601 | self.ESC_HELP = '?' | |||
|
602 | self.ESC_MAGIC = '%' | |||
|
603 | self.ESC_QUOTE = ',' | |||
|
604 | self.ESC_QUOTE2 = ';' | |||
|
605 | self.ESC_PAREN = '/' | |||
|
606 | ||||
|
607 | # And their associated handlers | |||
|
608 | self.esc_handlers = {self.ESC_PAREN : self.handle_auto, | |||
|
609 | self.ESC_QUOTE : self.handle_auto, | |||
|
610 | self.ESC_QUOTE2 : self.handle_auto, | |||
|
611 | self.ESC_MAGIC : self.handle_magic, | |||
|
612 | self.ESC_HELP : self.handle_help, | |||
|
613 | self.ESC_SHELL : self.handle_shell_escape, | |||
|
614 | self.ESC_SH_CAP : self.handle_shell_escape, | |||
|
615 | } | |||
|
616 | ||||
|
617 | # class initializations | |||
|
618 | Magic.__init__(self,self) | |||
|
619 | ||||
|
620 | # Python source parser/formatter for syntax highlighting | |||
|
621 | pyformat = PyColorize.Parser().format | |||
|
622 | self.pycolorize = lambda src: pyformat(src,'str',self.rc['colors']) | |||
|
623 | ||||
|
624 | # hooks holds pointers used for user-side customizations | |||
|
625 | self.hooks = Struct() | |||
|
626 | ||||
|
627 | self.strdispatchers = {} | |||
|
628 | ||||
|
629 | # Set all default hooks, defined in the IPython.hooks module. | |||
|
630 | import IPython.core.hooks | |||
|
631 | hooks = IPython.core.hooks | |||
|
632 | for hook_name in hooks.__all__: | |||
|
633 | # default hooks have priority 100, i.e. low; user hooks should have | |||
|
634 | # 0-100 priority | |||
|
635 | self.set_hook(hook_name,getattr(hooks,hook_name), 100) | |||
|
636 | #print "bound hook",hook_name | |||
|
637 | ||||
|
638 | # Flag to mark unconditional exit | |||
|
639 | self.exit_now = False | |||
|
640 | ||||
|
641 | self.usage_min = """\ | |||
|
642 | An enhanced console for Python. | |||
|
643 | Some of its features are: | |||
|
644 | - Readline support if the readline library is present. | |||
|
645 | - Tab completion in the local namespace. | |||
|
646 | - Logging of input, see command-line options. | |||
|
647 | - System shell escape via ! , eg !ls. | |||
|
648 | - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.) | |||
|
649 | - Keeps track of locally defined variables via %who, %whos. | |||
|
650 | - Show object information with a ? eg ?x or x? (use ?? for more info). | |||
|
651 | """ | |||
|
652 | if usage: self.usage = usage | |||
|
653 | else: self.usage = self.usage_min | |||
|
654 | ||||
|
655 | # Storage | |||
|
656 | self.rc = rc # This will hold all configuration information | |||
|
657 | self.pager = 'less' | |||
|
658 | # temporary files used for various purposes. Deleted at exit. | |||
|
659 | self.tempfiles = [] | |||
|
660 | ||||
|
661 | # Keep track of readline usage (later set by init_readline) | |||
|
662 | self.has_readline = False | |||
|
663 | ||||
|
664 | # template for logfile headers. It gets resolved at runtime by the | |||
|
665 | # logstart method. | |||
|
666 | self.loghead_tpl = \ | |||
|
667 | """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE *** | |||
|
668 | #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW | |||
|
669 | #log# opts = %s | |||
|
670 | #log# args = %s | |||
|
671 | #log# It is safe to make manual edits below here. | |||
|
672 | #log#----------------------------------------------------------------------- | |||
|
673 | """ | |||
|
674 | # for pushd/popd management | |||
|
675 | try: | |||
|
676 | self.home_dir = get_home_dir() | |||
|
677 | except HomeDirError,msg: | |||
|
678 | fatal(msg) | |||
|
679 | ||||
|
680 | self.dir_stack = [] | |||
|
681 | ||||
|
682 | # Functions to call the underlying shell. | |||
|
683 | ||||
|
684 | # The first is similar to os.system, but it doesn't return a value, | |||
|
685 | # and it allows interpolation of variables in the user's namespace. | |||
|
686 | self.system = lambda cmd: \ | |||
|
687 | self.hooks.shell_hook(self.var_expand(cmd,depth=2)) | |||
|
688 | ||||
|
689 | # These are for getoutput and getoutputerror: | |||
|
690 | self.getoutput = lambda cmd: \ | |||
|
691 | getoutput(self.var_expand(cmd,depth=2), | |||
|
692 | header=self.rc.system_header, | |||
|
693 | verbose=self.rc.system_verbose) | |||
|
694 | ||||
|
695 | self.getoutputerror = lambda cmd: \ | |||
|
696 | getoutputerror(self.var_expand(cmd,depth=2), | |||
|
697 | header=self.rc.system_header, | |||
|
698 | verbose=self.rc.system_verbose) | |||
|
699 | ||||
|
700 | ||||
|
701 | # keep track of where we started running (mainly for crash post-mortem) | |||
|
702 | self.starting_dir = os.getcwd() | |||
|
703 | ||||
|
704 | # Various switches which can be set | |||
|
705 | self.CACHELENGTH = 5000 # this is cheap, it's just text | |||
|
706 | self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__ | |||
|
707 | self.banner2 = banner2 | |||
|
708 | ||||
|
709 | # TraceBack handlers: | |||
|
710 | ||||
|
711 | # Syntax error handler. | |||
|
712 | self.SyntaxTB = SyntaxTB(color_scheme='NoColor') | |||
|
713 | ||||
|
714 | # The interactive one is initialized with an offset, meaning we always | |||
|
715 | # want to remove the topmost item in the traceback, which is our own | |||
|
716 | # internal code. Valid modes: ['Plain','Context','Verbose'] | |||
|
717 | self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain', | |||
|
718 | color_scheme='NoColor', | |||
|
719 | tb_offset = 1) | |||
|
720 | ||||
|
721 | # IPython itself shouldn't crash. This will produce a detailed | |||
|
722 | # post-mortem if it does. But we only install the crash handler for | |||
|
723 | # non-threaded shells, the threaded ones use a normal verbose reporter | |||
|
724 | # and lose the crash handler. This is because exceptions in the main | |||
|
725 | # thread (such as in GUI code) propagate directly to sys.excepthook, | |||
|
726 | # and there's no point in printing crash dumps for every user exception. | |||
|
727 | if self.isthreaded: | |||
|
728 | ipCrashHandler = ultratb.FormattedTB() | |||
|
729 | else: | |||
|
730 | from IPython.core import crashhandler | |||
|
731 | ipCrashHandler = crashhandler.IPythonCrashHandler(self) | |||
|
732 | self.set_crash_handler(ipCrashHandler) | |||
|
733 | ||||
|
734 | # and add any custom exception handlers the user may have specified | |||
|
735 | self.set_custom_exc(*custom_exceptions) | |||
|
736 | ||||
|
737 | # indentation management | |||
|
738 | self.autoindent = False | |||
|
739 | self.indent_current_nsp = 0 | |||
|
740 | ||||
|
741 | # Make some aliases automatically | |||
|
742 | # Prepare list of shell aliases to auto-define | |||
|
743 | if os.name == 'posix': | |||
|
744 | auto_alias = ('mkdir mkdir', 'rmdir rmdir', | |||
|
745 | 'mv mv -i','rm rm -i','cp cp -i', | |||
|
746 | 'cat cat','less less','clear clear', | |||
|
747 | # a better ls | |||
|
748 | 'ls ls -F', | |||
|
749 | # long ls | |||
|
750 | 'll ls -lF') | |||
|
751 | # Extra ls aliases with color, which need special treatment on BSD | |||
|
752 | # variants | |||
|
753 | ls_extra = ( # color ls | |||
|
754 | 'lc ls -F -o --color', | |||
|
755 | # ls normal files only | |||
|
756 | 'lf ls -F -o --color %l | grep ^-', | |||
|
757 | # ls symbolic links | |||
|
758 | 'lk ls -F -o --color %l | grep ^l', | |||
|
759 | # directories or links to directories, | |||
|
760 | 'ldir ls -F -o --color %l | grep /$', | |||
|
761 | # things which are executable | |||
|
762 | 'lx ls -F -o --color %l | grep ^-..x', | |||
|
763 | ) | |||
|
764 | # The BSDs don't ship GNU ls, so they don't understand the | |||
|
765 | # --color switch out of the box | |||
|
766 | if 'bsd' in sys.platform: | |||
|
767 | ls_extra = ( # ls normal files only | |||
|
768 | 'lf ls -lF | grep ^-', | |||
|
769 | # ls symbolic links | |||
|
770 | 'lk ls -lF | grep ^l', | |||
|
771 | # directories or links to directories, | |||
|
772 | 'ldir ls -lF | grep /$', | |||
|
773 | # things which are executable | |||
|
774 | 'lx ls -lF | grep ^-..x', | |||
|
775 | ) | |||
|
776 | auto_alias = auto_alias + ls_extra | |||
|
777 | elif os.name in ['nt','dos']: | |||
|
778 | auto_alias = ('ls dir /on', | |||
|
779 | 'ddir dir /ad /on', 'ldir dir /ad /on', | |||
|
780 | 'mkdir mkdir','rmdir rmdir','echo echo', | |||
|
781 | 'ren ren','cls cls','copy copy') | |||
|
782 | else: | |||
|
783 | auto_alias = () | |||
|
784 | self.auto_alias = [s.split(None,1) for s in auto_alias] | |||
|
785 | ||||
|
786 | # Produce a public API instance | |||
|
787 | self.api = ipapi.IPApi(self) | |||
|
788 | ||||
|
789 | # Initialize all user-visible namespaces | |||
|
790 | self.init_namespaces() | |||
|
791 | ||||
|
792 | # Call the actual (public) initializer | |||
|
793 | self.init_auto_alias() | |||
|
794 | ||||
|
795 | # track which builtins we add, so we can clean up later | |||
|
796 | self.builtins_added = {} | |||
|
797 | # This method will add the necessary builtins for operation, but | |||
|
798 | # tracking what it did via the builtins_added dict. | |||
|
799 | ||||
|
800 | #TODO: remove this, redundant | |||
|
801 | self.add_builtins() | |||
|
802 | # end __init__ | |||
|
803 | ||||
|
804 | def var_expand(self,cmd,depth=0): | |||
|
805 | """Expand python variables in a string. | |||
|
806 | ||||
|
807 | The depth argument indicates how many frames above the caller should | |||
|
808 | be walked to look for the local namespace where to expand variables. | |||
|
809 | ||||
|
810 | The global namespace for expansion is always the user's interactive | |||
|
811 | namespace. | |||
|
812 | """ | |||
|
813 | ||||
|
814 | return str(ItplNS(cmd, | |||
|
815 | self.user_ns, # globals | |||
|
816 | # Skip our own frame in searching for locals: | |||
|
817 | sys._getframe(depth+1).f_locals # locals | |||
|
818 | )) | |||
|
819 | ||||
|
820 | def pre_config_initialization(self): | |||
|
821 | """Pre-configuration init method | |||
|
822 | ||||
|
823 | This is called before the configuration files are processed to | |||
|
824 | prepare the services the config files might need. | |||
|
825 | ||||
|
826 | self.rc already has reasonable default values at this point. | |||
|
827 | """ | |||
|
828 | rc = self.rc | |||
|
829 | try: | |||
|
830 | self.db = pickleshare.PickleShareDB(rc.ipythondir + "/db") | |||
|
831 | except exceptions.UnicodeDecodeError: | |||
|
832 | print "Your ipythondir can't be decoded to unicode!" | |||
|
833 | print "Please set HOME environment variable to something that" | |||
|
834 | print r"only has ASCII characters, e.g. c:\home" | |||
|
835 | print "Now it is",rc.ipythondir | |||
|
836 | sys.exit() | |||
|
837 | self.shadowhist = IPython.core.history.ShadowHist(self.db) | |||
|
838 | ||||
|
839 | def post_config_initialization(self): | |||
|
840 | """Post configuration init method | |||
|
841 | ||||
|
842 | This is called after the configuration files have been processed to | |||
|
843 | 'finalize' the initialization.""" | |||
|
844 | ||||
|
845 | rc = self.rc | |||
|
846 | ||||
|
847 | # Object inspector | |||
|
848 | self.inspector = oinspect.Inspector(oinspect.InspectColors, | |||
|
849 | PyColorize.ANSICodeColors, | |||
|
850 | 'NoColor', | |||
|
851 | rc.object_info_string_level) | |||
|
852 | ||||
|
853 | self.rl_next_input = None | |||
|
854 | self.rl_do_indent = False | |||
|
855 | # Load readline proper | |||
|
856 | if rc.readline: | |||
|
857 | self.init_readline() | |||
|
858 | ||||
|
859 | # local shortcut, this is used a LOT | |||
|
860 | self.log = self.logger.log | |||
|
861 | ||||
|
862 | # Initialize cache, set in/out prompts and printing system | |||
|
863 | self.outputcache = CachedOutput(self, | |||
|
864 | rc.cache_size, | |||
|
865 | rc.pprint, | |||
|
866 | input_sep = rc.separate_in, | |||
|
867 | output_sep = rc.separate_out, | |||
|
868 | output_sep2 = rc.separate_out2, | |||
|
869 | ps1 = rc.prompt_in1, | |||
|
870 | ps2 = rc.prompt_in2, | |||
|
871 | ps_out = rc.prompt_out, | |||
|
872 | pad_left = rc.prompts_pad_left) | |||
|
873 | ||||
|
874 | # user may have over-ridden the default print hook: | |||
|
875 | try: | |||
|
876 | self.outputcache.__class__.display = self.hooks.display | |||
|
877 | except AttributeError: | |||
|
878 | pass | |||
|
879 | ||||
|
880 | # I don't like assigning globally to sys, because it means when | |||
|
881 | # embedding instances, each embedded instance overrides the previous | |||
|
882 | # choice. But sys.displayhook seems to be called internally by exec, | |||
|
883 | # so I don't see a way around it. We first save the original and then | |||
|
884 | # overwrite it. | |||
|
885 | self.sys_displayhook = sys.displayhook | |||
|
886 | sys.displayhook = self.outputcache | |||
|
887 | ||||
|
888 | # Do a proper resetting of doctest, including the necessary displayhook | |||
|
889 | # monkeypatching | |||
|
890 | try: | |||
|
891 | doctest_reload() | |||
|
892 | except ImportError: | |||
|
893 | warn("doctest module does not exist.") | |||
|
894 | ||||
|
895 | # Set user colors (don't do it in the constructor above so that it | |||
|
896 | # doesn't crash if colors option is invalid) | |||
|
897 | self.magic_colors(rc.colors) | |||
|
898 | ||||
|
899 | # Set calling of pdb on exceptions | |||
|
900 | self.call_pdb = rc.pdb | |||
|
901 | ||||
|
902 | # Load user aliases | |||
|
903 | for alias in rc.alias: | |||
|
904 | self.magic_alias(alias) | |||
|
905 | ||||
|
906 | self.hooks.late_startup_hook() | |||
|
907 | ||||
|
908 | for cmd in self.rc.autoexec: | |||
|
909 | #print "autoexec>",cmd #dbg | |||
|
910 | self.api.runlines(cmd) | |||
|
911 | ||||
|
912 | batchrun = False | |||
|
913 | for batchfile in [path(arg) for arg in self.rc.args | |||
|
914 | if arg.lower().endswith('.ipy')]: | |||
|
915 | if not batchfile.isfile(): | |||
|
916 | print "No such batch file:", batchfile | |||
|
917 | continue | |||
|
918 | self.api.runlines(batchfile.text()) | |||
|
919 | batchrun = True | |||
|
920 | # without -i option, exit after running the batch file | |||
|
921 | if batchrun and not self.rc.interact: | |||
|
922 | self.ask_exit() | |||
|
923 | ||||
|
924 | def init_namespaces(self): | |||
|
925 | """Initialize all user-visible namespaces to their minimum defaults. | |||
|
926 | ||||
|
927 | Certain history lists are also initialized here, as they effectively | |||
|
928 | act as user namespaces. | |||
|
929 | ||||
|
930 | Notes | |||
|
931 | ----- | |||
|
932 | All data structures here are only filled in, they are NOT reset by this | |||
|
933 | method. If they were not empty before, data will simply be added to | |||
|
934 | therm. | |||
|
935 | """ | |||
|
936 | # The user namespace MUST have a pointer to the shell itself. | |||
|
937 | self.user_ns[self.name] = self | |||
|
938 | ||||
|
939 | # Store the public api instance | |||
|
940 | self.user_ns['_ip'] = self.api | |||
|
941 | ||||
|
942 | # make global variables for user access to the histories | |||
|
943 | self.user_ns['_ih'] = self.input_hist | |||
|
944 | self.user_ns['_oh'] = self.output_hist | |||
|
945 | self.user_ns['_dh'] = self.dir_hist | |||
|
946 | ||||
|
947 | # user aliases to input and output histories | |||
|
948 | self.user_ns['In'] = self.input_hist | |||
|
949 | self.user_ns['Out'] = self.output_hist | |||
|
950 | ||||
|
951 | self.user_ns['_sh'] = shadowns | |||
|
952 | ||||
|
953 | # Fill the history zero entry, user counter starts at 1 | |||
|
954 | self.input_hist.append('\n') | |||
|
955 | self.input_hist_raw.append('\n') | |||
|
956 | ||||
|
957 | def add_builtins(self): | |||
|
958 | """Store ipython references into the builtin namespace. | |||
|
959 | ||||
|
960 | Some parts of ipython operate via builtins injected here, which hold a | |||
|
961 | reference to IPython itself.""" | |||
|
962 | ||||
|
963 | # TODO: deprecate all of these, they are unsafe | |||
|
964 | builtins_new = dict(__IPYTHON__ = self, | |||
|
965 | ip_set_hook = self.set_hook, | |||
|
966 | jobs = self.jobs, | |||
|
967 | ipmagic = wrap_deprecated(self.ipmagic,'_ip.magic()'), | |||
|
968 | ipalias = wrap_deprecated(self.ipalias), | |||
|
969 | ipsystem = wrap_deprecated(self.ipsystem,'_ip.system()'), | |||
|
970 | #_ip = self.api | |||
|
971 | ) | |||
|
972 | for biname,bival in builtins_new.items(): | |||
|
973 | try: | |||
|
974 | # store the orignal value so we can restore it | |||
|
975 | self.builtins_added[biname] = __builtin__.__dict__[biname] | |||
|
976 | except KeyError: | |||
|
977 | # or mark that it wasn't defined, and we'll just delete it at | |||
|
978 | # cleanup | |||
|
979 | self.builtins_added[biname] = Undefined | |||
|
980 | __builtin__.__dict__[biname] = bival | |||
|
981 | ||||
|
982 | # Keep in the builtins a flag for when IPython is active. We set it | |||
|
983 | # with setdefault so that multiple nested IPythons don't clobber one | |||
|
984 | # another. Each will increase its value by one upon being activated, | |||
|
985 | # which also gives us a way to determine the nesting level. | |||
|
986 | __builtin__.__dict__.setdefault('__IPYTHON__active',0) | |||
|
987 | ||||
|
988 | def clean_builtins(self): | |||
|
989 | """Remove any builtins which might have been added by add_builtins, or | |||
|
990 | restore overwritten ones to their previous values.""" | |||
|
991 | for biname,bival in self.builtins_added.items(): | |||
|
992 | if bival is Undefined: | |||
|
993 | del __builtin__.__dict__[biname] | |||
|
994 | else: | |||
|
995 | __builtin__.__dict__[biname] = bival | |||
|
996 | self.builtins_added.clear() | |||
|
997 | ||||
|
998 | def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None): | |||
|
999 | """set_hook(name,hook) -> sets an internal IPython hook. | |||
|
1000 | ||||
|
1001 | IPython exposes some of its internal API as user-modifiable hooks. By | |||
|
1002 | adding your function to one of these hooks, you can modify IPython's | |||
|
1003 | behavior to call at runtime your own routines.""" | |||
|
1004 | ||||
|
1005 | # At some point in the future, this should validate the hook before it | |||
|
1006 | # accepts it. Probably at least check that the hook takes the number | |||
|
1007 | # of args it's supposed to. | |||
|
1008 | ||||
|
1009 | f = new.instancemethod(hook,self,self.__class__) | |||
|
1010 | ||||
|
1011 | # check if the hook is for strdispatcher first | |||
|
1012 | if str_key is not None: | |||
|
1013 | sdp = self.strdispatchers.get(name, StrDispatch()) | |||
|
1014 | sdp.add_s(str_key, f, priority ) | |||
|
1015 | self.strdispatchers[name] = sdp | |||
|
1016 | return | |||
|
1017 | if re_key is not None: | |||
|
1018 | sdp = self.strdispatchers.get(name, StrDispatch()) | |||
|
1019 | sdp.add_re(re.compile(re_key), f, priority ) | |||
|
1020 | self.strdispatchers[name] = sdp | |||
|
1021 | return | |||
|
1022 | ||||
|
1023 | dp = getattr(self.hooks, name, None) | |||
|
1024 | if name not in IPython.core.hooks.__all__: | |||
|
1025 | print "Warning! Hook '%s' is not one of %s" % (name, IPython.core.hooks.__all__ ) | |||
|
1026 | if not dp: | |||
|
1027 | dp = IPython.core.hooks.CommandChainDispatcher() | |||
|
1028 | ||||
|
1029 | try: | |||
|
1030 | dp.add(f,priority) | |||
|
1031 | except AttributeError: | |||
|
1032 | # it was not commandchain, plain old func - replace | |||
|
1033 | dp = f | |||
|
1034 | ||||
|
1035 | setattr(self.hooks,name, dp) | |||
|
1036 | ||||
|
1037 | ||||
|
1038 | #setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__)) | |||
|
1039 | ||||
|
1040 | def set_crash_handler(self,crashHandler): | |||
|
1041 | """Set the IPython crash handler. | |||
|
1042 | ||||
|
1043 | This must be a callable with a signature suitable for use as | |||
|
1044 | sys.excepthook.""" | |||
|
1045 | ||||
|
1046 | # Install the given crash handler as the Python exception hook | |||
|
1047 | sys.excepthook = crashHandler | |||
|
1048 | ||||
|
1049 | # The instance will store a pointer to this, so that runtime code | |||
|
1050 | # (such as magics) can access it. This is because during the | |||
|
1051 | # read-eval loop, it gets temporarily overwritten (to deal with GUI | |||
|
1052 | # frameworks). | |||
|
1053 | self.sys_excepthook = sys.excepthook | |||
|
1054 | ||||
|
1055 | ||||
|
1056 | def set_custom_exc(self,exc_tuple,handler): | |||
|
1057 | """set_custom_exc(exc_tuple,handler) | |||
|
1058 | ||||
|
1059 | Set a custom exception handler, which will be called if any of the | |||
|
1060 | exceptions in exc_tuple occur in the mainloop (specifically, in the | |||
|
1061 | runcode() method. | |||
|
1062 | ||||
|
1063 | Inputs: | |||
|
1064 | ||||
|
1065 | - exc_tuple: a *tuple* of valid exceptions to call the defined | |||
|
1066 | handler for. It is very important that you use a tuple, and NOT A | |||
|
1067 | LIST here, because of the way Python's except statement works. If | |||
|
1068 | you only want to trap a single exception, use a singleton tuple: | |||
|
1069 | ||||
|
1070 | exc_tuple == (MyCustomException,) | |||
|
1071 | ||||
|
1072 | - handler: this must be defined as a function with the following | |||
|
1073 | basic interface: def my_handler(self,etype,value,tb). | |||
|
1074 | ||||
|
1075 | This will be made into an instance method (via new.instancemethod) | |||
|
1076 | of IPython itself, and it will be called if any of the exceptions | |||
|
1077 | listed in the exc_tuple are caught. If the handler is None, an | |||
|
1078 | internal basic one is used, which just prints basic info. | |||
|
1079 | ||||
|
1080 | WARNING: by putting in your own exception handler into IPython's main | |||
|
1081 | execution loop, you run a very good chance of nasty crashes. This | |||
|
1082 | facility should only be used if you really know what you are doing.""" | |||
|
1083 | ||||
|
1084 | assert type(exc_tuple)==type(()) , \ | |||
|
1085 | "The custom exceptions must be given AS A TUPLE." | |||
|
1086 | ||||
|
1087 | def dummy_handler(self,etype,value,tb): | |||
|
1088 | print '*** Simple custom exception handler ***' | |||
|
1089 | print 'Exception type :',etype | |||
|
1090 | print 'Exception value:',value | |||
|
1091 | print 'Traceback :',tb | |||
|
1092 | print 'Source code :','\n'.join(self.buffer) | |||
|
1093 | ||||
|
1094 | if handler is None: handler = dummy_handler | |||
|
1095 | ||||
|
1096 | self.CustomTB = new.instancemethod(handler,self,self.__class__) | |||
|
1097 | self.custom_exceptions = exc_tuple | |||
|
1098 | ||||
|
1099 | def set_custom_completer(self,completer,pos=0): | |||
|
1100 | """set_custom_completer(completer,pos=0) | |||
|
1101 | ||||
|
1102 | Adds a new custom completer function. | |||
|
1103 | ||||
|
1104 | The position argument (defaults to 0) is the index in the completers | |||
|
1105 | list where you want the completer to be inserted.""" | |||
|
1106 | ||||
|
1107 | newcomp = new.instancemethod(completer,self.Completer, | |||
|
1108 | self.Completer.__class__) | |||
|
1109 | self.Completer.matchers.insert(pos,newcomp) | |||
|
1110 | ||||
|
1111 | def set_completer(self): | |||
|
1112 | """reset readline's completer to be our own.""" | |||
|
1113 | self.readline.set_completer(self.Completer.complete) | |||
|
1114 | ||||
|
1115 | def _get_call_pdb(self): | |||
|
1116 | return self._call_pdb | |||
|
1117 | ||||
|
1118 | def _set_call_pdb(self,val): | |||
|
1119 | ||||
|
1120 | if val not in (0,1,False,True): | |||
|
1121 | raise ValueError,'new call_pdb value must be boolean' | |||
|
1122 | ||||
|
1123 | # store value in instance | |||
|
1124 | self._call_pdb = val | |||
|
1125 | ||||
|
1126 | # notify the actual exception handlers | |||
|
1127 | self.InteractiveTB.call_pdb = val | |||
|
1128 | if self.isthreaded: | |||
|
1129 | try: | |||
|
1130 | self.sys_excepthook.call_pdb = val | |||
|
1131 | except: | |||
|
1132 | warn('Failed to activate pdb for threaded exception handler') | |||
|
1133 | ||||
|
1134 | call_pdb = property(_get_call_pdb,_set_call_pdb,None, | |||
|
1135 | 'Control auto-activation of pdb at exceptions') | |||
|
1136 | ||||
|
1137 | # These special functions get installed in the builtin namespace, to | |||
|
1138 | # provide programmatic (pure python) access to magics, aliases and system | |||
|
1139 | # calls. This is important for logging, user scripting, and more. | |||
|
1140 | ||||
|
1141 | # We are basically exposing, via normal python functions, the three | |||
|
1142 | # mechanisms in which ipython offers special call modes (magics for | |||
|
1143 | # internal control, aliases for direct system access via pre-selected | |||
|
1144 | # names, and !cmd for calling arbitrary system commands). | |||
|
1145 | ||||
|
1146 | def ipmagic(self,arg_s): | |||
|
1147 | """Call a magic function by name. | |||
|
1148 | ||||
|
1149 | Input: a string containing the name of the magic function to call and any | |||
|
1150 | additional arguments to be passed to the magic. | |||
|
1151 | ||||
|
1152 | ipmagic('name -opt foo bar') is equivalent to typing at the ipython | |||
|
1153 | prompt: | |||
|
1154 | ||||
|
1155 | In[1]: %name -opt foo bar | |||
|
1156 | ||||
|
1157 | To call a magic without arguments, simply use ipmagic('name'). | |||
|
1158 | ||||
|
1159 | This provides a proper Python function to call IPython's magics in any | |||
|
1160 | valid Python code you can type at the interpreter, including loops and | |||
|
1161 | compound statements. It is added by IPython to the Python builtin | |||
|
1162 | namespace upon initialization.""" | |||
|
1163 | ||||
|
1164 | args = arg_s.split(' ',1) | |||
|
1165 | magic_name = args[0] | |||
|
1166 | magic_name = magic_name.lstrip(self.ESC_MAGIC) | |||
|
1167 | ||||
|
1168 | try: | |||
|
1169 | magic_args = args[1] | |||
|
1170 | except IndexError: | |||
|
1171 | magic_args = '' | |||
|
1172 | fn = getattr(self,'magic_'+magic_name,None) | |||
|
1173 | if fn is None: | |||
|
1174 | error("Magic function `%s` not found." % magic_name) | |||
|
1175 | else: | |||
|
1176 | magic_args = self.var_expand(magic_args,1) | |||
|
1177 | return fn(magic_args) | |||
|
1178 | ||||
|
1179 | def ipalias(self,arg_s): | |||
|
1180 | """Call an alias by name. | |||
|
1181 | ||||
|
1182 | Input: a string containing the name of the alias to call and any | |||
|
1183 | additional arguments to be passed to the magic. | |||
|
1184 | ||||
|
1185 | ipalias('name -opt foo bar') is equivalent to typing at the ipython | |||
|
1186 | prompt: | |||
|
1187 | ||||
|
1188 | In[1]: name -opt foo bar | |||
|
1189 | ||||
|
1190 | To call an alias without arguments, simply use ipalias('name'). | |||
|
1191 | ||||
|
1192 | This provides a proper Python function to call IPython's aliases in any | |||
|
1193 | valid Python code you can type at the interpreter, including loops and | |||
|
1194 | compound statements. It is added by IPython to the Python builtin | |||
|
1195 | namespace upon initialization.""" | |||
|
1196 | ||||
|
1197 | args = arg_s.split(' ',1) | |||
|
1198 | alias_name = args[0] | |||
|
1199 | try: | |||
|
1200 | alias_args = args[1] | |||
|
1201 | except IndexError: | |||
|
1202 | alias_args = '' | |||
|
1203 | if alias_name in self.alias_table: | |||
|
1204 | self.call_alias(alias_name,alias_args) | |||
|
1205 | else: | |||
|
1206 | error("Alias `%s` not found." % alias_name) | |||
|
1207 | ||||
|
1208 | def ipsystem(self,arg_s): | |||
|
1209 | """Make a system call, using IPython.""" | |||
|
1210 | ||||
|
1211 | self.system(arg_s) | |||
|
1212 | ||||
|
1213 | def complete(self,text): | |||
|
1214 | """Return a sorted list of all possible completions on text. | |||
|
1215 | ||||
|
1216 | Inputs: | |||
|
1217 | ||||
|
1218 | - text: a string of text to be completed on. | |||
|
1219 | ||||
|
1220 | This is a wrapper around the completion mechanism, similar to what | |||
|
1221 | readline does at the command line when the TAB key is hit. By | |||
|
1222 | exposing it as a method, it can be used by other non-readline | |||
|
1223 | environments (such as GUIs) for text completion. | |||
|
1224 | ||||
|
1225 | Simple usage example: | |||
|
1226 | ||||
|
1227 | In [7]: x = 'hello' | |||
|
1228 | ||||
|
1229 | In [8]: x | |||
|
1230 | Out[8]: 'hello' | |||
|
1231 | ||||
|
1232 | In [9]: print x | |||
|
1233 | hello | |||
|
1234 | ||||
|
1235 | In [10]: _ip.IP.complete('x.l') | |||
|
1236 | Out[10]: ['x.ljust', 'x.lower', 'x.lstrip'] | |||
|
1237 | """ | |||
|
1238 | ||||
|
1239 | complete = self.Completer.complete | |||
|
1240 | state = 0 | |||
|
1241 | # use a dict so we get unique keys, since ipyhton's multiple | |||
|
1242 | # completers can return duplicates. When we make 2.4 a requirement, | |||
|
1243 | # start using sets instead, which are faster. | |||
|
1244 | comps = {} | |||
|
1245 | while True: | |||
|
1246 | newcomp = complete(text,state,line_buffer=text) | |||
|
1247 | if newcomp is None: | |||
|
1248 | break | |||
|
1249 | comps[newcomp] = 1 | |||
|
1250 | state += 1 | |||
|
1251 | outcomps = comps.keys() | |||
|
1252 | outcomps.sort() | |||
|
1253 | #print "T:",text,"OC:",outcomps # dbg | |||
|
1254 | #print "vars:",self.user_ns.keys() | |||
|
1255 | return outcomps | |||
|
1256 | ||||
|
1257 | def set_completer_frame(self, frame=None): | |||
|
1258 | if frame: | |||
|
1259 | self.Completer.namespace = frame.f_locals | |||
|
1260 | self.Completer.global_namespace = frame.f_globals | |||
|
1261 | else: | |||
|
1262 | self.Completer.namespace = self.user_ns | |||
|
1263 | self.Completer.global_namespace = self.user_global_ns | |||
|
1264 | ||||
|
1265 | def init_auto_alias(self): | |||
|
1266 | """Define some aliases automatically. | |||
|
1267 | ||||
|
1268 | These are ALL parameter-less aliases""" | |||
|
1269 | ||||
|
1270 | for alias,cmd in self.auto_alias: | |||
|
1271 | self.getapi().defalias(alias,cmd) | |||
|
1272 | ||||
|
1273 | ||||
|
1274 | def alias_table_validate(self,verbose=0): | |||
|
1275 | """Update information about the alias table. | |||
|
1276 | ||||
|
1277 | In particular, make sure no Python keywords/builtins are in it.""" | |||
|
1278 | ||||
|
1279 | no_alias = self.no_alias | |||
|
1280 | for k in self.alias_table.keys(): | |||
|
1281 | if k in no_alias: | |||
|
1282 | del self.alias_table[k] | |||
|
1283 | if verbose: | |||
|
1284 | print ("Deleting alias <%s>, it's a Python " | |||
|
1285 | "keyword or builtin." % k) | |||
|
1286 | ||||
|
1287 | def set_autoindent(self,value=None): | |||
|
1288 | """Set the autoindent flag, checking for readline support. | |||
|
1289 | ||||
|
1290 | If called with no arguments, it acts as a toggle.""" | |||
|
1291 | ||||
|
1292 | if not self.has_readline: | |||
|
1293 | if os.name == 'posix': | |||
|
1294 | warn("The auto-indent feature requires the readline library") | |||
|
1295 | self.autoindent = 0 | |||
|
1296 | return | |||
|
1297 | if value is None: | |||
|
1298 | self.autoindent = not self.autoindent | |||
|
1299 | else: | |||
|
1300 | self.autoindent = value | |||
|
1301 | ||||
|
1302 | def rc_set_toggle(self,rc_field,value=None): | |||
|
1303 | """Set or toggle a field in IPython's rc config. structure. | |||
|
1304 | ||||
|
1305 | If called with no arguments, it acts as a toggle. | |||
|
1306 | ||||
|
1307 | If called with a non-existent field, the resulting AttributeError | |||
|
1308 | exception will propagate out.""" | |||
|
1309 | ||||
|
1310 | rc_val = getattr(self.rc,rc_field) | |||
|
1311 | if value is None: | |||
|
1312 | value = not rc_val | |||
|
1313 | setattr(self.rc,rc_field,value) | |||
|
1314 | ||||
|
1315 | def user_setup(self,ipythondir,rc_suffix,mode='install'): | |||
|
1316 | """Install the user configuration directory. | |||
|
1317 | ||||
|
1318 | Notes | |||
|
1319 | ----- | |||
|
1320 | DEPRECATED: use the top-level user_setup() function instead. | |||
|
1321 | """ | |||
|
1322 | return user_setup(ipythondir,rc_suffix,mode) | |||
|
1323 | ||||
|
1324 | def atexit_operations(self): | |||
|
1325 | """This will be executed at the time of exit. | |||
|
1326 | ||||
|
1327 | Saving of persistent data should be performed here. """ | |||
|
1328 | ||||
|
1329 | #print '*** IPython exit cleanup ***' # dbg | |||
|
1330 | # input history | |||
|
1331 | self.savehist() | |||
|
1332 | ||||
|
1333 | # Cleanup all tempfiles left around | |||
|
1334 | for tfile in self.tempfiles: | |||
|
1335 | try: | |||
|
1336 | os.unlink(tfile) | |||
|
1337 | except OSError: | |||
|
1338 | pass | |||
|
1339 | ||||
|
1340 | # Clear all user namespaces to release all references cleanly. | |||
|
1341 | self.reset() | |||
|
1342 | ||||
|
1343 | # Run user hooks | |||
|
1344 | self.hooks.shutdown_hook() | |||
|
1345 | ||||
|
1346 | def reset(self): | |||
|
1347 | """Clear all internal namespaces. | |||
|
1348 | ||||
|
1349 | Note that this is much more aggressive than %reset, since it clears | |||
|
1350 | fully all namespaces, as well as all input/output lists. | |||
|
1351 | """ | |||
|
1352 | for ns in self.ns_refs_table: | |||
|
1353 | ns.clear() | |||
|
1354 | ||||
|
1355 | # Clear input and output histories | |||
|
1356 | self.input_hist[:] = [] | |||
|
1357 | self.input_hist_raw[:] = [] | |||
|
1358 | self.output_hist.clear() | |||
|
1359 | # Restore the user namespaces to minimal usability | |||
|
1360 | self.init_namespaces() | |||
|
1361 | ||||
|
1362 | def savehist(self): | |||
|
1363 | """Save input history to a file (via readline library).""" | |||
|
1364 | ||||
|
1365 | if not self.has_readline: | |||
|
1366 | return | |||
|
1367 | ||||
|
1368 | try: | |||
|
1369 | self.readline.write_history_file(self.histfile) | |||
|
1370 | except: | |||
|
1371 | print 'Unable to save IPython command history to file: ' + \ | |||
|
1372 | `self.histfile` | |||
|
1373 | ||||
|
1374 | def reloadhist(self): | |||
|
1375 | """Reload the input history from disk file.""" | |||
|
1376 | ||||
|
1377 | if self.has_readline: | |||
|
1378 | try: | |||
|
1379 | self.readline.clear_history() | |||
|
1380 | self.readline.read_history_file(self.shell.histfile) | |||
|
1381 | except AttributeError: | |||
|
1382 | pass | |||
|
1383 | ||||
|
1384 | ||||
|
1385 | def history_saving_wrapper(self, func): | |||
|
1386 | """ Wrap func for readline history saving | |||
|
1387 | ||||
|
1388 | Convert func into callable that saves & restores | |||
|
1389 | history around the call """ | |||
|
1390 | ||||
|
1391 | if not self.has_readline: | |||
|
1392 | return func | |||
|
1393 | ||||
|
1394 | def wrapper(): | |||
|
1395 | self.savehist() | |||
|
1396 | try: | |||
|
1397 | func() | |||
|
1398 | finally: | |||
|
1399 | readline.read_history_file(self.histfile) | |||
|
1400 | return wrapper | |||
|
1401 | ||||
|
1402 | def pre_readline(self): | |||
|
1403 | """readline hook to be used at the start of each line. | |||
|
1404 | ||||
|
1405 | Currently it handles auto-indent only.""" | |||
|
1406 | ||||
|
1407 | #debugx('self.indent_current_nsp','pre_readline:') | |||
|
1408 | ||||
|
1409 | if self.rl_do_indent: | |||
|
1410 | self.readline.insert_text(self.indent_current_str()) | |||
|
1411 | if self.rl_next_input is not None: | |||
|
1412 | self.readline.insert_text(self.rl_next_input) | |||
|
1413 | self.rl_next_input = None | |||
|
1414 | ||||
|
1415 | def init_readline(self): | |||
|
1416 | """Command history completion/saving/reloading.""" | |||
|
1417 | ||||
|
1418 | ||||
|
1419 | import IPython.utils.rlineimpl as readline | |||
|
1420 | ||||
|
1421 | if not readline.have_readline: | |||
|
1422 | self.has_readline = 0 | |||
|
1423 | self.readline = None | |||
|
1424 | # no point in bugging windows users with this every time: | |||
|
1425 | warn('Readline services not available on this platform.') | |||
|
1426 | else: | |||
|
1427 | sys.modules['readline'] = readline | |||
|
1428 | import atexit | |||
|
1429 | from IPython.core.completer import IPCompleter | |||
|
1430 | self.Completer = IPCompleter(self, | |||
|
1431 | self.user_ns, | |||
|
1432 | self.user_global_ns, | |||
|
1433 | self.rc.readline_omit__names, | |||
|
1434 | self.alias_table) | |||
|
1435 | sdisp = self.strdispatchers.get('complete_command', StrDispatch()) | |||
|
1436 | self.strdispatchers['complete_command'] = sdisp | |||
|
1437 | self.Completer.custom_completers = sdisp | |||
|
1438 | # Platform-specific configuration | |||
|
1439 | if os.name == 'nt': | |||
|
1440 | self.readline_startup_hook = readline.set_pre_input_hook | |||
|
1441 | else: | |||
|
1442 | self.readline_startup_hook = readline.set_startup_hook | |||
|
1443 | ||||
|
1444 | # Load user's initrc file (readline config) | |||
|
1445 | # Or if libedit is used, load editrc. | |||
|
1446 | inputrc_name = os.environ.get('INPUTRC') | |||
|
1447 | if inputrc_name is None: | |||
|
1448 | home_dir = get_home_dir() | |||
|
1449 | if home_dir is not None: | |||
|
1450 | inputrc_name = '.inputrc' | |||
|
1451 | if readline.uses_libedit: | |||
|
1452 | inputrc_name = '.editrc' | |||
|
1453 | inputrc_name = os.path.join(home_dir, inputrc_name) | |||
|
1454 | if os.path.isfile(inputrc_name): | |||
|
1455 | try: | |||
|
1456 | readline.read_init_file(inputrc_name) | |||
|
1457 | except: | |||
|
1458 | warn('Problems reading readline initialization file <%s>' | |||
|
1459 | % inputrc_name) | |||
|
1460 | ||||
|
1461 | self.has_readline = 1 | |||
|
1462 | self.readline = readline | |||
|
1463 | # save this in sys so embedded copies can restore it properly | |||
|
1464 | sys.ipcompleter = self.Completer.complete | |||
|
1465 | self.set_completer() | |||
|
1466 | ||||
|
1467 | # Configure readline according to user's prefs | |||
|
1468 | # This is only done if GNU readline is being used. If libedit | |||
|
1469 | # is being used (as on Leopard) the readline config is | |||
|
1470 | # not run as the syntax for libedit is different. | |||
|
1471 | if not readline.uses_libedit: | |||
|
1472 | for rlcommand in self.rc.readline_parse_and_bind: | |||
|
1473 | #print "loading rl:",rlcommand # dbg | |||
|
1474 | readline.parse_and_bind(rlcommand) | |||
|
1475 | ||||
|
1476 | # Remove some chars from the delimiters list. If we encounter | |||
|
1477 | # unicode chars, discard them. | |||
|
1478 | delims = readline.get_completer_delims().encode("ascii", "ignore") | |||
|
1479 | delims = delims.translate(string._idmap, | |||
|
1480 | self.rc.readline_remove_delims) | |||
|
1481 | readline.set_completer_delims(delims) | |||
|
1482 | # otherwise we end up with a monster history after a while: | |||
|
1483 | readline.set_history_length(1000) | |||
|
1484 | try: | |||
|
1485 | #print '*** Reading readline history' # dbg | |||
|
1486 | readline.read_history_file(self.histfile) | |||
|
1487 | except IOError: | |||
|
1488 | pass # It doesn't exist yet. | |||
|
1489 | ||||
|
1490 | atexit.register(self.atexit_operations) | |||
|
1491 | del atexit | |||
|
1492 | ||||
|
1493 | # Configure auto-indent for all platforms | |||
|
1494 | self.set_autoindent(self.rc.autoindent) | |||
|
1495 | ||||
|
1496 | def ask_yes_no(self,prompt,default=True): | |||
|
1497 | if self.rc.quiet: | |||
|
1498 | return True | |||
|
1499 | return ask_yes_no(prompt,default) | |||
|
1500 | ||||
|
1501 | def new_main_mod(self,ns=None): | |||
|
1502 | """Return a new 'main' module object for user code execution. | |||
|
1503 | """ | |||
|
1504 | main_mod = self._user_main_module | |||
|
1505 | init_fakemod_dict(main_mod,ns) | |||
|
1506 | return main_mod | |||
|
1507 | ||||
|
1508 | def cache_main_mod(self,ns,fname): | |||
|
1509 | """Cache a main module's namespace. | |||
|
1510 | ||||
|
1511 | When scripts are executed via %run, we must keep a reference to the | |||
|
1512 | namespace of their __main__ module (a FakeModule instance) around so | |||
|
1513 | that Python doesn't clear it, rendering objects defined therein | |||
|
1514 | useless. | |||
|
1515 | ||||
|
1516 | This method keeps said reference in a private dict, keyed by the | |||
|
1517 | absolute path of the module object (which corresponds to the script | |||
|
1518 | path). This way, for multiple executions of the same script we only | |||
|
1519 | keep one copy of the namespace (the last one), thus preventing memory | |||
|
1520 | leaks from old references while allowing the objects from the last | |||
|
1521 | execution to be accessible. | |||
|
1522 | ||||
|
1523 | Note: we can not allow the actual FakeModule instances to be deleted, | |||
|
1524 | because of how Python tears down modules (it hard-sets all their | |||
|
1525 | references to None without regard for reference counts). This method | |||
|
1526 | must therefore make a *copy* of the given namespace, to allow the | |||
|
1527 | original module's __dict__ to be cleared and reused. | |||
|
1528 | ||||
|
1529 | ||||
|
1530 | Parameters | |||
|
1531 | ---------- | |||
|
1532 | ns : a namespace (a dict, typically) | |||
|
1533 | ||||
|
1534 | fname : str | |||
|
1535 | Filename associated with the namespace. | |||
|
1536 | ||||
|
1537 | Examples | |||
|
1538 | -------- | |||
|
1539 | ||||
|
1540 | In [10]: import IPython | |||
|
1541 | ||||
|
1542 | In [11]: _ip.IP.cache_main_mod(IPython.__dict__,IPython.__file__) | |||
|
1543 | ||||
|
1544 | In [12]: IPython.__file__ in _ip.IP._main_ns_cache | |||
|
1545 | Out[12]: True | |||
|
1546 | """ | |||
|
1547 | self._main_ns_cache[os.path.abspath(fname)] = ns.copy() | |||
|
1548 | ||||
|
1549 | def clear_main_mod_cache(self): | |||
|
1550 | """Clear the cache of main modules. | |||
|
1551 | ||||
|
1552 | Mainly for use by utilities like %reset. | |||
|
1553 | ||||
|
1554 | Examples | |||
|
1555 | -------- | |||
|
1556 | ||||
|
1557 | In [15]: import IPython | |||
|
1558 | ||||
|
1559 | In [16]: _ip.IP.cache_main_mod(IPython.__dict__,IPython.__file__) | |||
|
1560 | ||||
|
1561 | In [17]: len(_ip.IP._main_ns_cache) > 0 | |||
|
1562 | Out[17]: True | |||
|
1563 | ||||
|
1564 | In [18]: _ip.IP.clear_main_mod_cache() | |||
|
1565 | ||||
|
1566 | In [19]: len(_ip.IP._main_ns_cache) == 0 | |||
|
1567 | Out[19]: True | |||
|
1568 | """ | |||
|
1569 | self._main_ns_cache.clear() | |||
|
1570 | ||||
|
1571 | def _should_recompile(self,e): | |||
|
1572 | """Utility routine for edit_syntax_error""" | |||
|
1573 | ||||
|
1574 | if e.filename in ('<ipython console>','<input>','<string>', | |||
|
1575 | '<console>','<BackgroundJob compilation>', | |||
|
1576 | None): | |||
|
1577 | ||||
|
1578 | return False | |||
|
1579 | try: | |||
|
1580 | if (self.rc.autoedit_syntax and | |||
|
1581 | not self.ask_yes_no('Return to editor to correct syntax error? ' | |||
|
1582 | '[Y/n] ','y')): | |||
|
1583 | return False | |||
|
1584 | except EOFError: | |||
|
1585 | return False | |||
|
1586 | ||||
|
1587 | def int0(x): | |||
|
1588 | try: | |||
|
1589 | return int(x) | |||
|
1590 | except TypeError: | |||
|
1591 | return 0 | |||
|
1592 | # always pass integer line and offset values to editor hook | |||
|
1593 | try: | |||
|
1594 | self.hooks.fix_error_editor(e.filename, | |||
|
1595 | int0(e.lineno),int0(e.offset),e.msg) | |||
|
1596 | except ipapi.TryNext: | |||
|
1597 | warn('Could not open editor') | |||
|
1598 | return False | |||
|
1599 | return True | |||
|
1600 | ||||
|
1601 | def edit_syntax_error(self): | |||
|
1602 | """The bottom half of the syntax error handler called in the main loop. | |||
|
1603 | ||||
|
1604 | Loop until syntax error is fixed or user cancels. | |||
|
1605 | """ | |||
|
1606 | ||||
|
1607 | while self.SyntaxTB.last_syntax_error: | |||
|
1608 | # copy and clear last_syntax_error | |||
|
1609 | err = self.SyntaxTB.clear_err_state() | |||
|
1610 | if not self._should_recompile(err): | |||
|
1611 | return | |||
|
1612 | try: | |||
|
1613 | # may set last_syntax_error again if a SyntaxError is raised | |||
|
1614 | self.safe_execfile(err.filename,self.user_ns) | |||
|
1615 | except: | |||
|
1616 | self.showtraceback() | |||
|
1617 | else: | |||
|
1618 | try: | |||
|
1619 | f = file(err.filename) | |||
|
1620 | try: | |||
|
1621 | sys.displayhook(f.read()) | |||
|
1622 | finally: | |||
|
1623 | f.close() | |||
|
1624 | except: | |||
|
1625 | self.showtraceback() | |||
|
1626 | ||||
|
1627 | def showsyntaxerror(self, filename=None): | |||
|
1628 | """Display the syntax error that just occurred. | |||
|
1629 | ||||
|
1630 | This doesn't display a stack trace because there isn't one. | |||
|
1631 | ||||
|
1632 | If a filename is given, it is stuffed in the exception instead | |||
|
1633 | of what was there before (because Python's parser always uses | |||
|
1634 | "<string>" when reading from a string). | |||
|
1635 | """ | |||
|
1636 | etype, value, last_traceback = sys.exc_info() | |||
|
1637 | ||||
|
1638 | # See note about these variables in showtraceback() below | |||
|
1639 | sys.last_type = etype | |||
|
1640 | sys.last_value = value | |||
|
1641 | sys.last_traceback = last_traceback | |||
|
1642 | ||||
|
1643 | if filename and etype is SyntaxError: | |||
|
1644 | # Work hard to stuff the correct filename in the exception | |||
|
1645 | try: | |||
|
1646 | msg, (dummy_filename, lineno, offset, line) = value | |||
|
1647 | except: | |||
|
1648 | # Not the format we expect; leave it alone | |||
|
1649 | pass | |||
|
1650 | else: | |||
|
1651 | # Stuff in the right filename | |||
|
1652 | try: | |||
|
1653 | # Assume SyntaxError is a class exception | |||
|
1654 | value = SyntaxError(msg, (filename, lineno, offset, line)) | |||
|
1655 | except: | |||
|
1656 | # If that failed, assume SyntaxError is a string | |||
|
1657 | value = msg, (filename, lineno, offset, line) | |||
|
1658 | self.SyntaxTB(etype,value,[]) | |||
|
1659 | ||||
|
1660 | def debugger(self,force=False): | |||
|
1661 | """Call the pydb/pdb debugger. | |||
|
1662 | ||||
|
1663 | Keywords: | |||
|
1664 | ||||
|
1665 | - force(False): by default, this routine checks the instance call_pdb | |||
|
1666 | flag and does not actually invoke the debugger if the flag is false. | |||
|
1667 | The 'force' option forces the debugger to activate even if the flag | |||
|
1668 | is false. | |||
|
1669 | """ | |||
|
1670 | ||||
|
1671 | if not (force or self.call_pdb): | |||
|
1672 | return | |||
|
1673 | ||||
|
1674 | if not hasattr(sys,'last_traceback'): | |||
|
1675 | error('No traceback has been produced, nothing to debug.') | |||
|
1676 | return | |||
|
1677 | ||||
|
1678 | # use pydb if available | |||
|
1679 | if debugger.has_pydb: | |||
|
1680 | from pydb import pm | |||
|
1681 | else: | |||
|
1682 | # fallback to our internal debugger | |||
|
1683 | pm = lambda : self.InteractiveTB.debugger(force=True) | |||
|
1684 | self.history_saving_wrapper(pm)() | |||
|
1685 | ||||
|
1686 | def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None): | |||
|
1687 | """Display the exception that just occurred. | |||
|
1688 | ||||
|
1689 | If nothing is known about the exception, this is the method which | |||
|
1690 | should be used throughout the code for presenting user tracebacks, | |||
|
1691 | rather than directly invoking the InteractiveTB object. | |||
|
1692 | ||||
|
1693 | A specific showsyntaxerror() also exists, but this method can take | |||
|
1694 | care of calling it if needed, so unless you are explicitly catching a | |||
|
1695 | SyntaxError exception, don't try to analyze the stack manually and | |||
|
1696 | simply call this method.""" | |||
|
1697 | ||||
|
1698 | ||||
|
1699 | # Though this won't be called by syntax errors in the input line, | |||
|
1700 | # there may be SyntaxError cases whith imported code. | |||
|
1701 | ||||
|
1702 | try: | |||
|
1703 | if exc_tuple is None: | |||
|
1704 | etype, value, tb = sys.exc_info() | |||
|
1705 | else: | |||
|
1706 | etype, value, tb = exc_tuple | |||
|
1707 | ||||
|
1708 | if etype is SyntaxError: | |||
|
1709 | self.showsyntaxerror(filename) | |||
|
1710 | elif etype is ipapi.UsageError: | |||
|
1711 | print "UsageError:", value | |||
|
1712 | else: | |||
|
1713 | # WARNING: these variables are somewhat deprecated and not | |||
|
1714 | # necessarily safe to use in a threaded environment, but tools | |||
|
1715 | # like pdb depend on their existence, so let's set them. If we | |||
|
1716 | # find problems in the field, we'll need to revisit their use. | |||
|
1717 | sys.last_type = etype | |||
|
1718 | sys.last_value = value | |||
|
1719 | sys.last_traceback = tb | |||
|
1720 | ||||
|
1721 | if etype in self.custom_exceptions: | |||
|
1722 | self.CustomTB(etype,value,tb) | |||
|
1723 | else: | |||
|
1724 | self.InteractiveTB(etype,value,tb,tb_offset=tb_offset) | |||
|
1725 | if self.InteractiveTB.call_pdb and self.has_readline: | |||
|
1726 | # pdb mucks up readline, fix it back | |||
|
1727 | self.set_completer() | |||
|
1728 | except KeyboardInterrupt: | |||
|
1729 | self.write("\nKeyboardInterrupt\n") | |||
|
1730 | ||||
|
1731 | def mainloop(self,banner=None): | |||
|
1732 | """Creates the local namespace and starts the mainloop. | |||
|
1733 | ||||
|
1734 | If an optional banner argument is given, it will override the | |||
|
1735 | internally created default banner.""" | |||
|
1736 | ||||
|
1737 | if self.rc.c: # Emulate Python's -c option | |||
|
1738 | self.exec_init_cmd() | |||
|
1739 | if banner is None: | |||
|
1740 | if not self.rc.banner: | |||
|
1741 | banner = '' | |||
|
1742 | # banner is string? Use it directly! | |||
|
1743 | elif isinstance(self.rc.banner,basestring): | |||
|
1744 | banner = self.rc.banner | |||
|
1745 | else: | |||
|
1746 | banner = self.BANNER+self.banner2 | |||
|
1747 | ||||
|
1748 | # if you run stuff with -c <cmd>, raw hist is not updated | |||
|
1749 | # ensure that it's in sync | |||
|
1750 | if len(self.input_hist) != len (self.input_hist_raw): | |||
|
1751 | self.input_hist_raw = InputList(self.input_hist) | |||
|
1752 | ||||
|
1753 | while 1: | |||
|
1754 | try: | |||
|
1755 | self.interact(banner) | |||
|
1756 | #self.interact_with_readline() | |||
|
1757 | ||||
|
1758 | # XXX for testing of a readline-decoupled repl loop, call | |||
|
1759 | # interact_with_readline above | |||
|
1760 | ||||
|
1761 | break | |||
|
1762 | except KeyboardInterrupt: | |||
|
1763 | # this should not be necessary, but KeyboardInterrupt | |||
|
1764 | # handling seems rather unpredictable... | |||
|
1765 | self.write("\nKeyboardInterrupt in interact()\n") | |||
|
1766 | ||||
|
1767 | def exec_init_cmd(self): | |||
|
1768 | """Execute a command given at the command line. | |||
|
1769 | ||||
|
1770 | This emulates Python's -c option.""" | |||
|
1771 | ||||
|
1772 | #sys.argv = ['-c'] | |||
|
1773 | self.push(self.prefilter(self.rc.c, False)) | |||
|
1774 | if not self.rc.interact: | |||
|
1775 | self.ask_exit() | |||
|
1776 | ||||
|
1777 | def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0): | |||
|
1778 | """Embeds IPython into a running python program. | |||
|
1779 | ||||
|
1780 | Input: | |||
|
1781 | ||||
|
1782 | - header: An optional header message can be specified. | |||
|
1783 | ||||
|
1784 | - local_ns, global_ns: working namespaces. If given as None, the | |||
|
1785 | IPython-initialized one is updated with __main__.__dict__, so that | |||
|
1786 | program variables become visible but user-specific configuration | |||
|
1787 | remains possible. | |||
|
1788 | ||||
|
1789 | - stack_depth: specifies how many levels in the stack to go to | |||
|
1790 | looking for namespaces (when local_ns and global_ns are None). This | |||
|
1791 | allows an intermediate caller to make sure that this function gets | |||
|
1792 | the namespace from the intended level in the stack. By default (0) | |||
|
1793 | it will get its locals and globals from the immediate caller. | |||
|
1794 | ||||
|
1795 | Warning: it's possible to use this in a program which is being run by | |||
|
1796 | IPython itself (via %run), but some funny things will happen (a few | |||
|
1797 | globals get overwritten). In the future this will be cleaned up, as | |||
|
1798 | there is no fundamental reason why it can't work perfectly.""" | |||
|
1799 | ||||
|
1800 | # Get locals and globals from caller | |||
|
1801 | if local_ns is None or global_ns is None: | |||
|
1802 | call_frame = sys._getframe(stack_depth).f_back | |||
|
1803 | ||||
|
1804 | if local_ns is None: | |||
|
1805 | local_ns = call_frame.f_locals | |||
|
1806 | if global_ns is None: | |||
|
1807 | global_ns = call_frame.f_globals | |||
|
1808 | ||||
|
1809 | # Update namespaces and fire up interpreter | |||
|
1810 | ||||
|
1811 | # The global one is easy, we can just throw it in | |||
|
1812 | self.user_global_ns = global_ns | |||
|
1813 | ||||
|
1814 | # but the user/local one is tricky: ipython needs it to store internal | |||
|
1815 | # data, but we also need the locals. We'll copy locals in the user | |||
|
1816 | # one, but will track what got copied so we can delete them at exit. | |||
|
1817 | # This is so that a later embedded call doesn't see locals from a | |||
|
1818 | # previous call (which most likely existed in a separate scope). | |||
|
1819 | local_varnames = local_ns.keys() | |||
|
1820 | self.user_ns.update(local_ns) | |||
|
1821 | #self.user_ns['local_ns'] = local_ns # dbg | |||
|
1822 | ||||
|
1823 | # Patch for global embedding to make sure that things don't overwrite | |||
|
1824 | # user globals accidentally. Thanks to Richard <rxe@renre-europe.com> | |||
|
1825 | # FIXME. Test this a bit more carefully (the if.. is new) | |||
|
1826 | if local_ns is None and global_ns is None: | |||
|
1827 | self.user_global_ns.update(__main__.__dict__) | |||
|
1828 | ||||
|
1829 | # make sure the tab-completer has the correct frame information, so it | |||
|
1830 | # actually completes using the frame's locals/globals | |||
|
1831 | self.set_completer_frame() | |||
|
1832 | ||||
|
1833 | # before activating the interactive mode, we need to make sure that | |||
|
1834 | # all names in the builtin namespace needed by ipython point to | |||
|
1835 | # ourselves, and not to other instances. | |||
|
1836 | self.add_builtins() | |||
|
1837 | ||||
|
1838 | self.interact(header) | |||
|
1839 | ||||
|
1840 | # now, purge out the user namespace from anything we might have added | |||
|
1841 | # from the caller's local namespace | |||
|
1842 | delvar = self.user_ns.pop | |||
|
1843 | for var in local_varnames: | |||
|
1844 | delvar(var,None) | |||
|
1845 | # and clean builtins we may have overridden | |||
|
1846 | self.clean_builtins() | |||
|
1847 | ||||
|
1848 | def interact_prompt(self): | |||
|
1849 | """ Print the prompt (in read-eval-print loop) | |||
|
1850 | ||||
|
1851 | Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not | |||
|
1852 | used in standard IPython flow. | |||
|
1853 | """ | |||
|
1854 | if self.more: | |||
|
1855 | try: | |||
|
1856 | prompt = self.hooks.generate_prompt(True) | |||
|
1857 | except: | |||
|
1858 | self.showtraceback() | |||
|
1859 | if self.autoindent: | |||
|
1860 | self.rl_do_indent = True | |||
|
1861 | ||||
|
1862 | else: | |||
|
1863 | try: | |||
|
1864 | prompt = self.hooks.generate_prompt(False) | |||
|
1865 | except: | |||
|
1866 | self.showtraceback() | |||
|
1867 | self.write(prompt) | |||
|
1868 | ||||
|
1869 | def interact_handle_input(self,line): | |||
|
1870 | """ Handle the input line (in read-eval-print loop) | |||
|
1871 | ||||
|
1872 | Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not | |||
|
1873 | used in standard IPython flow. | |||
|
1874 | """ | |||
|
1875 | if line.lstrip() == line: | |||
|
1876 | self.shadowhist.add(line.strip()) | |||
|
1877 | lineout = self.prefilter(line,self.more) | |||
|
1878 | ||||
|
1879 | if line.strip(): | |||
|
1880 | if self.more: | |||
|
1881 | self.input_hist_raw[-1] += '%s\n' % line | |||
|
1882 | else: | |||
|
1883 | self.input_hist_raw.append('%s\n' % line) | |||
|
1884 | ||||
|
1885 | ||||
|
1886 | self.more = self.push(lineout) | |||
|
1887 | if (self.SyntaxTB.last_syntax_error and | |||
|
1888 | self.rc.autoedit_syntax): | |||
|
1889 | self.edit_syntax_error() | |||
|
1890 | ||||
|
1891 | def interact_with_readline(self): | |||
|
1892 | """ Demo of using interact_handle_input, interact_prompt | |||
|
1893 | ||||
|
1894 | This is the main read-eval-print loop. If you need to implement your own (e.g. for GUI), | |||
|
1895 | it should work like this. | |||
|
1896 | """ | |||
|
1897 | self.readline_startup_hook(self.pre_readline) | |||
|
1898 | while not self.exit_now: | |||
|
1899 | self.interact_prompt() | |||
|
1900 | if self.more: | |||
|
1901 | self.rl_do_indent = True | |||
|
1902 | else: | |||
|
1903 | self.rl_do_indent = False | |||
|
1904 | line = raw_input_original().decode(self.stdin_encoding) | |||
|
1905 | self.interact_handle_input(line) | |||
|
1906 | ||||
|
1907 | ||||
|
1908 | def interact(self, banner=None): | |||
|
1909 | """Closely emulate the interactive Python console. | |||
|
1910 | ||||
|
1911 | The optional banner argument specify the banner to print | |||
|
1912 | before the first interaction; by default it prints a banner | |||
|
1913 | similar to the one printed by the real Python interpreter, | |||
|
1914 | followed by the current class name in parentheses (so as not | |||
|
1915 | to confuse this with the real interpreter -- since it's so | |||
|
1916 | close!). | |||
|
1917 | ||||
|
1918 | """ | |||
|
1919 | ||||
|
1920 | if self.exit_now: | |||
|
1921 | # batch run -> do not interact | |||
|
1922 | return | |||
|
1923 | cprt = 'Type "copyright", "credits" or "license" for more information.' | |||
|
1924 | if banner is None: | |||
|
1925 | self.write("Python %s on %s\n%s\n(%s)\n" % | |||
|
1926 | (sys.version, sys.platform, cprt, | |||
|
1927 | self.__class__.__name__)) | |||
|
1928 | else: | |||
|
1929 | self.write(banner) | |||
|
1930 | ||||
|
1931 | more = 0 | |||
|
1932 | ||||
|
1933 | # Mark activity in the builtins | |||
|
1934 | __builtin__.__dict__['__IPYTHON__active'] += 1 | |||
|
1935 | ||||
|
1936 | if self.has_readline: | |||
|
1937 | self.readline_startup_hook(self.pre_readline) | |||
|
1938 | # exit_now is set by a call to %Exit or %Quit, through the | |||
|
1939 | # ask_exit callback. | |||
|
1940 | ||||
|
1941 | while not self.exit_now: | |||
|
1942 | self.hooks.pre_prompt_hook() | |||
|
1943 | if more: | |||
|
1944 | try: | |||
|
1945 | prompt = self.hooks.generate_prompt(True) | |||
|
1946 | except: | |||
|
1947 | self.showtraceback() | |||
|
1948 | if self.autoindent: | |||
|
1949 | self.rl_do_indent = True | |||
|
1950 | ||||
|
1951 | else: | |||
|
1952 | try: | |||
|
1953 | prompt = self.hooks.generate_prompt(False) | |||
|
1954 | except: | |||
|
1955 | self.showtraceback() | |||
|
1956 | try: | |||
|
1957 | line = self.raw_input(prompt,more) | |||
|
1958 | if self.exit_now: | |||
|
1959 | # quick exit on sys.std[in|out] close | |||
|
1960 | break | |||
|
1961 | if self.autoindent: | |||
|
1962 | self.rl_do_indent = False | |||
|
1963 | ||||
|
1964 | except KeyboardInterrupt: | |||
|
1965 | #double-guard against keyboardinterrupts during kbdint handling | |||
|
1966 | try: | |||
|
1967 | self.write('\nKeyboardInterrupt\n') | |||
|
1968 | self.resetbuffer() | |||
|
1969 | # keep cache in sync with the prompt counter: | |||
|
1970 | self.outputcache.prompt_count -= 1 | |||
|
1971 | ||||
|
1972 | if self.autoindent: | |||
|
1973 | self.indent_current_nsp = 0 | |||
|
1974 | more = 0 | |||
|
1975 | except KeyboardInterrupt: | |||
|
1976 | pass | |||
|
1977 | except EOFError: | |||
|
1978 | if self.autoindent: | |||
|
1979 | self.rl_do_indent = False | |||
|
1980 | self.readline_startup_hook(None) | |||
|
1981 | self.write('\n') | |||
|
1982 | self.exit() | |||
|
1983 | except bdb.BdbQuit: | |||
|
1984 | warn('The Python debugger has exited with a BdbQuit exception.\n' | |||
|
1985 | 'Because of how pdb handles the stack, it is impossible\n' | |||
|
1986 | 'for IPython to properly format this particular exception.\n' | |||
|
1987 | 'IPython will resume normal operation.') | |||
|
1988 | except: | |||
|
1989 | # exceptions here are VERY RARE, but they can be triggered | |||
|
1990 | # asynchronously by signal handlers, for example. | |||
|
1991 | self.showtraceback() | |||
|
1992 | else: | |||
|
1993 | more = self.push(line) | |||
|
1994 | if (self.SyntaxTB.last_syntax_error and | |||
|
1995 | self.rc.autoedit_syntax): | |||
|
1996 | self.edit_syntax_error() | |||
|
1997 | ||||
|
1998 | # We are off again... | |||
|
1999 | __builtin__.__dict__['__IPYTHON__active'] -= 1 | |||
|
2000 | ||||
|
2001 | def excepthook(self, etype, value, tb): | |||
|
2002 | """One more defense for GUI apps that call sys.excepthook. | |||
|
2003 | ||||
|
2004 | GUI frameworks like wxPython trap exceptions and call | |||
|
2005 | sys.excepthook themselves. I guess this is a feature that | |||
|
2006 | enables them to keep running after exceptions that would | |||
|
2007 | otherwise kill their mainloop. This is a bother for IPython | |||
|
2008 | which excepts to catch all of the program exceptions with a try: | |||
|
2009 | except: statement. | |||
|
2010 | ||||
|
2011 | Normally, IPython sets sys.excepthook to a CrashHandler instance, so if | |||
|
2012 | any app directly invokes sys.excepthook, it will look to the user like | |||
|
2013 | IPython crashed. In order to work around this, we can disable the | |||
|
2014 | CrashHandler and replace it with this excepthook instead, which prints a | |||
|
2015 | regular traceback using our InteractiveTB. In this fashion, apps which | |||
|
2016 | call sys.excepthook will generate a regular-looking exception from | |||
|
2017 | IPython, and the CrashHandler will only be triggered by real IPython | |||
|
2018 | crashes. | |||
|
2019 | ||||
|
2020 | This hook should be used sparingly, only in places which are not likely | |||
|
2021 | to be true IPython errors. | |||
|
2022 | """ | |||
|
2023 | self.showtraceback((etype,value,tb),tb_offset=0) | |||
|
2024 | ||||
|
2025 | def expand_aliases(self,fn,rest): | |||
|
2026 | """ Expand multiple levels of aliases: | |||
|
2027 | ||||
|
2028 | if: | |||
|
2029 | ||||
|
2030 | alias foo bar /tmp | |||
|
2031 | alias baz foo | |||
|
2032 | ||||
|
2033 | then: | |||
|
2034 | ||||
|
2035 | baz huhhahhei -> bar /tmp huhhahhei | |||
|
2036 | ||||
|
2037 | """ | |||
|
2038 | line = fn + " " + rest | |||
|
2039 | ||||
|
2040 | done = set() | |||
|
2041 | while 1: | |||
|
2042 | pre,fn,rest = prefilter.splitUserInput(line, | |||
|
2043 | prefilter.shell_line_split) | |||
|
2044 | if fn in self.alias_table: | |||
|
2045 | if fn in done: | |||
|
2046 | warn("Cyclic alias definition, repeated '%s'" % fn) | |||
|
2047 | return "" | |||
|
2048 | done.add(fn) | |||
|
2049 | ||||
|
2050 | l2 = self.transform_alias(fn,rest) | |||
|
2051 | # dir -> dir | |||
|
2052 | # print "alias",line, "->",l2 #dbg | |||
|
2053 | if l2 == line: | |||
|
2054 | break | |||
|
2055 | # ls -> ls -F should not recurse forever | |||
|
2056 | if l2.split(None,1)[0] == line.split(None,1)[0]: | |||
|
2057 | line = l2 | |||
|
2058 | break | |||
|
2059 | ||||
|
2060 | line=l2 | |||
|
2061 | ||||
|
2062 | ||||
|
2063 | # print "al expand to",line #dbg | |||
|
2064 | else: | |||
|
2065 | break | |||
|
2066 | ||||
|
2067 | return line | |||
|
2068 | ||||
|
2069 | def transform_alias(self, alias,rest=''): | |||
|
2070 | """ Transform alias to system command string. | |||
|
2071 | """ | |||
|
2072 | trg = self.alias_table[alias] | |||
|
2073 | ||||
|
2074 | nargs,cmd = trg | |||
|
2075 | # print trg #dbg | |||
|
2076 | if ' ' in cmd and os.path.isfile(cmd): | |||
|
2077 | cmd = '"%s"' % cmd | |||
|
2078 | ||||
|
2079 | # Expand the %l special to be the user's input line | |||
|
2080 | if cmd.find('%l') >= 0: | |||
|
2081 | cmd = cmd.replace('%l',rest) | |||
|
2082 | rest = '' | |||
|
2083 | if nargs==0: | |||
|
2084 | # Simple, argument-less aliases | |||
|
2085 | cmd = '%s %s' % (cmd,rest) | |||
|
2086 | else: | |||
|
2087 | # Handle aliases with positional arguments | |||
|
2088 | args = rest.split(None,nargs) | |||
|
2089 | if len(args)< nargs: | |||
|
2090 | error('Alias <%s> requires %s arguments, %s given.' % | |||
|
2091 | (alias,nargs,len(args))) | |||
|
2092 | return None | |||
|
2093 | cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:])) | |||
|
2094 | # Now call the macro, evaluating in the user's namespace | |||
|
2095 | #print 'new command: <%r>' % cmd # dbg | |||
|
2096 | return cmd | |||
|
2097 | ||||
|
2098 | def call_alias(self,alias,rest=''): | |||
|
2099 | """Call an alias given its name and the rest of the line. | |||
|
2100 | ||||
|
2101 | This is only used to provide backwards compatibility for users of | |||
|
2102 | ipalias(), use of which is not recommended for anymore.""" | |||
|
2103 | ||||
|
2104 | # Now call the macro, evaluating in the user's namespace | |||
|
2105 | cmd = self.transform_alias(alias, rest) | |||
|
2106 | try: | |||
|
2107 | self.system(cmd) | |||
|
2108 | except: | |||
|
2109 | self.showtraceback() | |||
|
2110 | ||||
|
2111 | def indent_current_str(self): | |||
|
2112 | """return the current level of indentation as a string""" | |||
|
2113 | return self.indent_current_nsp * ' ' | |||
|
2114 | ||||
|
2115 | def autoindent_update(self,line): | |||
|
2116 | """Keep track of the indent level.""" | |||
|
2117 | ||||
|
2118 | #debugx('line') | |||
|
2119 | #debugx('self.indent_current_nsp') | |||
|
2120 | if self.autoindent: | |||
|
2121 | if line: | |||
|
2122 | inisp = num_ini_spaces(line) | |||
|
2123 | if inisp < self.indent_current_nsp: | |||
|
2124 | self.indent_current_nsp = inisp | |||
|
2125 | ||||
|
2126 | if line[-1] == ':': | |||
|
2127 | self.indent_current_nsp += 4 | |||
|
2128 | elif dedent_re.match(line): | |||
|
2129 | self.indent_current_nsp -= 4 | |||
|
2130 | else: | |||
|
2131 | self.indent_current_nsp = 0 | |||
|
2132 | ||||
|
2133 | def runlines(self,lines): | |||
|
2134 | """Run a string of one or more lines of source. | |||
|
2135 | ||||
|
2136 | This method is capable of running a string containing multiple source | |||
|
2137 | lines, as if they had been entered at the IPython prompt. Since it | |||
|
2138 | exposes IPython's processing machinery, the given strings can contain | |||
|
2139 | magic calls (%magic), special shell access (!cmd), etc.""" | |||
|
2140 | ||||
|
2141 | # We must start with a clean buffer, in case this is run from an | |||
|
2142 | # interactive IPython session (via a magic, for example). | |||
|
2143 | self.resetbuffer() | |||
|
2144 | lines = lines.split('\n') | |||
|
2145 | more = 0 | |||
|
2146 | ||||
|
2147 | for line in lines: | |||
|
2148 | # skip blank lines so we don't mess up the prompt counter, but do | |||
|
2149 | # NOT skip even a blank line if we are in a code block (more is | |||
|
2150 | # true) | |||
|
2151 | ||||
|
2152 | if line or more: | |||
|
2153 | # push to raw history, so hist line numbers stay in sync | |||
|
2154 | self.input_hist_raw.append("# " + line + "\n") | |||
|
2155 | more = self.push(self.prefilter(line,more)) | |||
|
2156 | # IPython's runsource returns None if there was an error | |||
|
2157 | # compiling the code. This allows us to stop processing right | |||
|
2158 | # away, so the user gets the error message at the right place. | |||
|
2159 | if more is None: | |||
|
2160 | break | |||
|
2161 | else: | |||
|
2162 | self.input_hist_raw.append("\n") | |||
|
2163 | # final newline in case the input didn't have it, so that the code | |||
|
2164 | # actually does get executed | |||
|
2165 | if more: | |||
|
2166 | self.push('\n') | |||
|
2167 | ||||
|
2168 | def runsource(self, source, filename='<input>', symbol='single'): | |||
|
2169 | """Compile and run some source in the interpreter. | |||
|
2170 | ||||
|
2171 | Arguments are as for compile_command(). | |||
|
2172 | ||||
|
2173 | One several things can happen: | |||
|
2174 | ||||
|
2175 | 1) The input is incorrect; compile_command() raised an | |||
|
2176 | exception (SyntaxError or OverflowError). A syntax traceback | |||
|
2177 | will be printed by calling the showsyntaxerror() method. | |||
|
2178 | ||||
|
2179 | 2) The input is incomplete, and more input is required; | |||
|
2180 | compile_command() returned None. Nothing happens. | |||
|
2181 | ||||
|
2182 | 3) The input is complete; compile_command() returned a code | |||
|
2183 | object. The code is executed by calling self.runcode() (which | |||
|
2184 | also handles run-time exceptions, except for SystemExit). | |||
|
2185 | ||||
|
2186 | The return value is: | |||
|
2187 | ||||
|
2188 | - True in case 2 | |||
|
2189 | ||||
|
2190 | - False in the other cases, unless an exception is raised, where | |||
|
2191 | None is returned instead. This can be used by external callers to | |||
|
2192 | know whether to continue feeding input or not. | |||
|
2193 | ||||
|
2194 | The return value can be used to decide whether to use sys.ps1 or | |||
|
2195 | sys.ps2 to prompt the next line.""" | |||
|
2196 | ||||
|
2197 | # if the source code has leading blanks, add 'if 1:\n' to it | |||
|
2198 | # this allows execution of indented pasted code. It is tempting | |||
|
2199 | # to add '\n' at the end of source to run commands like ' a=1' | |||
|
2200 | # directly, but this fails for more complicated scenarios | |||
|
2201 | source=source.encode(self.stdin_encoding) | |||
|
2202 | if source[:1] in [' ', '\t']: | |||
|
2203 | source = 'if 1:\n%s' % source | |||
|
2204 | ||||
|
2205 | try: | |||
|
2206 | code = self.compile(source,filename,symbol) | |||
|
2207 | except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError): | |||
|
2208 | # Case 1 | |||
|
2209 | self.showsyntaxerror(filename) | |||
|
2210 | return None | |||
|
2211 | ||||
|
2212 | if code is None: | |||
|
2213 | # Case 2 | |||
|
2214 | return True | |||
|
2215 | ||||
|
2216 | # Case 3 | |||
|
2217 | # We store the code object so that threaded shells and | |||
|
2218 | # custom exception handlers can access all this info if needed. | |||
|
2219 | # The source corresponding to this can be obtained from the | |||
|
2220 | # buffer attribute as '\n'.join(self.buffer). | |||
|
2221 | self.code_to_run = code | |||
|
2222 | # now actually execute the code object | |||
|
2223 | if self.runcode(code) == 0: | |||
|
2224 | return False | |||
|
2225 | else: | |||
|
2226 | return None | |||
|
2227 | ||||
|
2228 | def runcode(self,code_obj): | |||
|
2229 | """Execute a code object. | |||
|
2230 | ||||
|
2231 | When an exception occurs, self.showtraceback() is called to display a | |||
|
2232 | traceback. | |||
|
2233 | ||||
|
2234 | Return value: a flag indicating whether the code to be run completed | |||
|
2235 | successfully: | |||
|
2236 | ||||
|
2237 | - 0: successful execution. | |||
|
2238 | - 1: an error occurred. | |||
|
2239 | """ | |||
|
2240 | ||||
|
2241 | # Set our own excepthook in case the user code tries to call it | |||
|
2242 | # directly, so that the IPython crash handler doesn't get triggered | |||
|
2243 | old_excepthook,sys.excepthook = sys.excepthook, self.excepthook | |||
|
2244 | ||||
|
2245 | # we save the original sys.excepthook in the instance, in case config | |||
|
2246 | # code (such as magics) needs access to it. | |||
|
2247 | self.sys_excepthook = old_excepthook | |||
|
2248 | outflag = 1 # happens in more places, so it's easier as default | |||
|
2249 | try: | |||
|
2250 | try: | |||
|
2251 | self.hooks.pre_runcode_hook() | |||
|
2252 | exec code_obj in self.user_global_ns, self.user_ns | |||
|
2253 | finally: | |||
|
2254 | # Reset our crash handler in place | |||
|
2255 | sys.excepthook = old_excepthook | |||
|
2256 | except SystemExit: | |||
|
2257 | self.resetbuffer() | |||
|
2258 | self.showtraceback() | |||
|
2259 | warn("Type %exit or %quit to exit IPython " | |||
|
2260 | "(%Exit or %Quit do so unconditionally).",level=1) | |||
|
2261 | except self.custom_exceptions: | |||
|
2262 | etype,value,tb = sys.exc_info() | |||
|
2263 | self.CustomTB(etype,value,tb) | |||
|
2264 | except: | |||
|
2265 | self.showtraceback() | |||
|
2266 | else: | |||
|
2267 | outflag = 0 | |||
|
2268 | if softspace(sys.stdout, 0): | |||
|
2269 | ||||
|
2270 | # Flush out code object which has been run (and source) | |||
|
2271 | self.code_to_run = None | |||
|
2272 | return outflag | |||
|
2273 | ||||
|
2274 | def push(self, line): | |||
|
2275 | """Push a line to the interpreter. | |||
|
2276 | ||||
|
2277 | The line should not have a trailing newline; it may have | |||
|
2278 | internal newlines. The line is appended to a buffer and the | |||
|
2279 | interpreter's runsource() method is called with the | |||
|
2280 | concatenated contents of the buffer as source. If this | |||
|
2281 | indicates that the command was executed or invalid, the buffer | |||
|
2282 | is reset; otherwise, the command is incomplete, and the buffer | |||
|
2283 | is left as it was after the line was appended. The return | |||
|
2284 | value is 1 if more input is required, 0 if the line was dealt | |||
|
2285 | with in some way (this is the same as runsource()). | |||
|
2286 | """ | |||
|
2287 | ||||
|
2288 | # autoindent management should be done here, and not in the | |||
|
2289 | # interactive loop, since that one is only seen by keyboard input. We | |||
|
2290 | # need this done correctly even for code run via runlines (which uses | |||
|
2291 | # push). | |||
|
2292 | ||||
|
2293 | #print 'push line: <%s>' % line # dbg | |||
|
2294 | for subline in line.splitlines(): | |||
|
2295 | self.autoindent_update(subline) | |||
|
2296 | self.buffer.append(line) | |||
|
2297 | more = self.runsource('\n'.join(self.buffer), self.filename) | |||
|
2298 | if not more: | |||
|
2299 | self.resetbuffer() | |||
|
2300 | return more | |||
|
2301 | ||||
|
2302 | def split_user_input(self, line): | |||
|
2303 | # This is really a hold-over to support ipapi and some extensions | |||
|
2304 | return prefilter.splitUserInput(line) | |||
|
2305 | ||||
|
2306 | def resetbuffer(self): | |||
|
2307 | """Reset the input buffer.""" | |||
|
2308 | self.buffer[:] = [] | |||
|
2309 | ||||
|
2310 | def raw_input(self,prompt='',continue_prompt=False): | |||
|
2311 | """Write a prompt and read a line. | |||
|
2312 | ||||
|
2313 | The returned line does not include the trailing newline. | |||
|
2314 | When the user enters the EOF key sequence, EOFError is raised. | |||
|
2315 | ||||
|
2316 | Optional inputs: | |||
|
2317 | ||||
|
2318 | - prompt(''): a string to be printed to prompt the user. | |||
|
2319 | ||||
|
2320 | - continue_prompt(False): whether this line is the first one or a | |||
|
2321 | continuation in a sequence of inputs. | |||
|
2322 | """ | |||
|
2323 | ||||
|
2324 | # Code run by the user may have modified the readline completer state. | |||
|
2325 | # We must ensure that our completer is back in place. | |||
|
2326 | if self.has_readline: | |||
|
2327 | self.set_completer() | |||
|
2328 | ||||
|
2329 | try: | |||
|
2330 | line = raw_input_original(prompt).decode(self.stdin_encoding) | |||
|
2331 | except ValueError: | |||
|
2332 | warn("\n********\nYou or a %run:ed script called sys.stdin.close()" | |||
|
2333 | " or sys.stdout.close()!\nExiting IPython!") | |||
|
2334 | self.ask_exit() | |||
|
2335 | return "" | |||
|
2336 | ||||
|
2337 | # Try to be reasonably smart about not re-indenting pasted input more | |||
|
2338 | # than necessary. We do this by trimming out the auto-indent initial | |||
|
2339 | # spaces, if the user's actual input started itself with whitespace. | |||
|
2340 | #debugx('self.buffer[-1]') | |||
|
2341 | ||||
|
2342 | if self.autoindent: | |||
|
2343 | if num_ini_spaces(line) > self.indent_current_nsp: | |||
|
2344 | line = line[self.indent_current_nsp:] | |||
|
2345 | self.indent_current_nsp = 0 | |||
|
2346 | ||||
|
2347 | # store the unfiltered input before the user has any chance to modify | |||
|
2348 | # it. | |||
|
2349 | if line.strip(): | |||
|
2350 | if continue_prompt: | |||
|
2351 | self.input_hist_raw[-1] += '%s\n' % line | |||
|
2352 | if self.has_readline: # and some config option is set? | |||
|
2353 | try: | |||
|
2354 | histlen = self.readline.get_current_history_length() | |||
|
2355 | if histlen > 1: | |||
|
2356 | newhist = self.input_hist_raw[-1].rstrip() | |||
|
2357 | self.readline.remove_history_item(histlen-1) | |||
|
2358 | self.readline.replace_history_item(histlen-2, | |||
|
2359 | newhist.encode(self.stdin_encoding)) | |||
|
2360 | except AttributeError: | |||
|
2361 | pass # re{move,place}_history_item are new in 2.4. | |||
|
2362 | else: | |||
|
2363 | self.input_hist_raw.append('%s\n' % line) | |||
|
2364 | # only entries starting at first column go to shadow history | |||
|
2365 | if line.lstrip() == line: | |||
|
2366 | self.shadowhist.add(line.strip()) | |||
|
2367 | elif not continue_prompt: | |||
|
2368 | self.input_hist_raw.append('\n') | |||
|
2369 | try: | |||
|
2370 | lineout = self.prefilter(line,continue_prompt) | |||
|
2371 | except: | |||
|
2372 | # blanket except, in case a user-defined prefilter crashes, so it | |||
|
2373 | # can't take all of ipython with it. | |||
|
2374 | self.showtraceback() | |||
|
2375 | return '' | |||
|
2376 | else: | |||
|
2377 | return lineout | |||
|
2378 | ||||
|
2379 | def _prefilter(self, line, continue_prompt): | |||
|
2380 | """Calls different preprocessors, depending on the form of line.""" | |||
|
2381 | ||||
|
2382 | # All handlers *must* return a value, even if it's blank (''). | |||
|
2383 | ||||
|
2384 | # Lines are NOT logged here. Handlers should process the line as | |||
|
2385 | # needed, update the cache AND log it (so that the input cache array | |||
|
2386 | # stays synced). | |||
|
2387 | ||||
|
2388 | #..................................................................... | |||
|
2389 | # Code begins | |||
|
2390 | ||||
|
2391 | #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg | |||
|
2392 | ||||
|
2393 | # save the line away in case we crash, so the post-mortem handler can | |||
|
2394 | # record it | |||
|
2395 | self._last_input_line = line | |||
|
2396 | ||||
|
2397 | #print '***line: <%s>' % line # dbg | |||
|
2398 | ||||
|
2399 | if not line: | |||
|
2400 | # Return immediately on purely empty lines, so that if the user | |||
|
2401 | # previously typed some whitespace that started a continuation | |||
|
2402 | # prompt, he can break out of that loop with just an empty line. | |||
|
2403 | # This is how the default python prompt works. | |||
|
2404 | ||||
|
2405 | # Only return if the accumulated input buffer was just whitespace! | |||
|
2406 | if ''.join(self.buffer).isspace(): | |||
|
2407 | self.buffer[:] = [] | |||
|
2408 | return '' | |||
|
2409 | ||||
|
2410 | line_info = prefilter.LineInfo(line, continue_prompt) | |||
|
2411 | ||||
|
2412 | # the input history needs to track even empty lines | |||
|
2413 | stripped = line.strip() | |||
|
2414 | ||||
|
2415 | if not stripped: | |||
|
2416 | if not continue_prompt: | |||
|
2417 | self.outputcache.prompt_count -= 1 | |||
|
2418 | return self.handle_normal(line_info) | |||
|
2419 | ||||
|
2420 | # print '***cont',continue_prompt # dbg | |||
|
2421 | # special handlers are only allowed for single line statements | |||
|
2422 | if continue_prompt and not self.rc.multi_line_specials: | |||
|
2423 | return self.handle_normal(line_info) | |||
|
2424 | ||||
|
2425 | ||||
|
2426 | # See whether any pre-existing handler can take care of it | |||
|
2427 | rewritten = self.hooks.input_prefilter(stripped) | |||
|
2428 | if rewritten != stripped: # ok, some prefilter did something | |||
|
2429 | rewritten = line_info.pre + rewritten # add indentation | |||
|
2430 | return self.handle_normal(prefilter.LineInfo(rewritten, | |||
|
2431 | continue_prompt)) | |||
|
2432 | ||||
|
2433 | #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg | |||
|
2434 | ||||
|
2435 | return prefilter.prefilter(line_info, self) | |||
|
2436 | ||||
|
2437 | ||||
|
2438 | def _prefilter_dumb(self, line, continue_prompt): | |||
|
2439 | """simple prefilter function, for debugging""" | |||
|
2440 | return self.handle_normal(line,continue_prompt) | |||
|
2441 | ||||
|
2442 | ||||
|
2443 | def multiline_prefilter(self, line, continue_prompt): | |||
|
2444 | """ Run _prefilter for each line of input | |||
|
2445 | ||||
|
2446 | Covers cases where there are multiple lines in the user entry, | |||
|
2447 | which is the case when the user goes back to a multiline history | |||
|
2448 | entry and presses enter. | |||
|
2449 | ||||
|
2450 | """ | |||
|
2451 | out = [] | |||
|
2452 | for l in line.rstrip('\n').split('\n'): | |||
|
2453 | out.append(self._prefilter(l, continue_prompt)) | |||
|
2454 | return '\n'.join(out) | |||
|
2455 | ||||
|
2456 | # Set the default prefilter() function (this can be user-overridden) | |||
|
2457 | prefilter = multiline_prefilter | |||
|
2458 | ||||
|
2459 | def handle_normal(self,line_info): | |||
|
2460 | """Handle normal input lines. Use as a template for handlers.""" | |||
|
2461 | ||||
|
2462 | # With autoindent on, we need some way to exit the input loop, and I | |||
|
2463 | # don't want to force the user to have to backspace all the way to | |||
|
2464 | # clear the line. The rule will be in this case, that either two | |||
|
2465 | # lines of pure whitespace in a row, or a line of pure whitespace but | |||
|
2466 | # of a size different to the indent level, will exit the input loop. | |||
|
2467 | line = line_info.line | |||
|
2468 | continue_prompt = line_info.continue_prompt | |||
|
2469 | ||||
|
2470 | if (continue_prompt and self.autoindent and line.isspace() and | |||
|
2471 | (0 < abs(len(line) - self.indent_current_nsp) <= 2 or | |||
|
2472 | (self.buffer[-1]).isspace() )): | |||
|
2473 | line = '' | |||
|
2474 | ||||
|
2475 | self.log(line,line,continue_prompt) | |||
|
2476 | return line | |||
|
2477 | ||||
|
2478 | def handle_alias(self,line_info): | |||
|
2479 | """Handle alias input lines. """ | |||
|
2480 | tgt = self.alias_table[line_info.iFun] | |||
|
2481 | # print "=>",tgt #dbg | |||
|
2482 | if callable(tgt): | |||
|
2483 | if '$' in line_info.line: | |||
|
2484 | call_meth = '(_ip, _ip.itpl(%s))' | |||
|
2485 | else: | |||
|
2486 | call_meth = '(_ip,%s)' | |||
|
2487 | line_out = ("%s_sh.%s" + call_meth) % (line_info.preWhitespace, | |||
|
2488 | line_info.iFun, | |||
|
2489 | make_quoted_expr(line_info.line)) | |||
|
2490 | else: | |||
|
2491 | transformed = self.expand_aliases(line_info.iFun,line_info.theRest) | |||
|
2492 | ||||
|
2493 | # pre is needed, because it carries the leading whitespace. Otherwise | |||
|
2494 | # aliases won't work in indented sections. | |||
|
2495 | line_out = '%s_ip.system(%s)' % (line_info.preWhitespace, | |||
|
2496 | make_quoted_expr( transformed )) | |||
|
2497 | ||||
|
2498 | self.log(line_info.line,line_out,line_info.continue_prompt) | |||
|
2499 | #print 'line out:',line_out # dbg | |||
|
2500 | return line_out | |||
|
2501 | ||||
|
2502 | def handle_shell_escape(self, line_info): | |||
|
2503 | """Execute the line in a shell, empty return value""" | |||
|
2504 | #print 'line in :', `line` # dbg | |||
|
2505 | line = line_info.line | |||
|
2506 | if line.lstrip().startswith('!!'): | |||
|
2507 | # rewrite LineInfo's line, iFun and theRest to properly hold the | |||
|
2508 | # call to %sx and the actual command to be executed, so | |||
|
2509 | # handle_magic can work correctly. Note that this works even if | |||
|
2510 | # the line is indented, so it handles multi_line_specials | |||
|
2511 | # properly. | |||
|
2512 | new_rest = line.lstrip()[2:] | |||
|
2513 | line_info.line = '%ssx %s' % (self.ESC_MAGIC,new_rest) | |||
|
2514 | line_info.iFun = 'sx' | |||
|
2515 | line_info.theRest = new_rest | |||
|
2516 | return self.handle_magic(line_info) | |||
|
2517 | else: | |||
|
2518 | cmd = line.lstrip().lstrip('!') | |||
|
2519 | line_out = '%s_ip.system(%s)' % (line_info.preWhitespace, | |||
|
2520 | make_quoted_expr(cmd)) | |||
|
2521 | # update cache/log and return | |||
|
2522 | self.log(line,line_out,line_info.continue_prompt) | |||
|
2523 | return line_out | |||
|
2524 | ||||
|
2525 | def handle_magic(self, line_info): | |||
|
2526 | """Execute magic functions.""" | |||
|
2527 | iFun = line_info.iFun | |||
|
2528 | theRest = line_info.theRest | |||
|
2529 | cmd = '%s_ip.magic(%s)' % (line_info.preWhitespace, | |||
|
2530 | make_quoted_expr(iFun + " " + theRest)) | |||
|
2531 | self.log(line_info.line,cmd,line_info.continue_prompt) | |||
|
2532 | #print 'in handle_magic, cmd=<%s>' % cmd # dbg | |||
|
2533 | return cmd | |||
|
2534 | ||||
|
2535 | def handle_auto(self, line_info): | |||
|
2536 | """Hande lines which can be auto-executed, quoting if requested.""" | |||
|
2537 | ||||
|
2538 | line = line_info.line | |||
|
2539 | iFun = line_info.iFun | |||
|
2540 | theRest = line_info.theRest | |||
|
2541 | pre = line_info.pre | |||
|
2542 | continue_prompt = line_info.continue_prompt | |||
|
2543 | obj = line_info.ofind(self)['obj'] | |||
|
2544 | ||||
|
2545 | #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg | |||
|
2546 | ||||
|
2547 | # This should only be active for single-line input! | |||
|
2548 | if continue_prompt: | |||
|
2549 | self.log(line,line,continue_prompt) | |||
|
2550 | return line | |||
|
2551 | ||||
|
2552 | force_auto = isinstance(obj, ipapi.IPyAutocall) | |||
|
2553 | auto_rewrite = True | |||
|
2554 | ||||
|
2555 | if pre == self.ESC_QUOTE: | |||
|
2556 | # Auto-quote splitting on whitespace | |||
|
2557 | newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) ) | |||
|
2558 | elif pre == self.ESC_QUOTE2: | |||
|
2559 | # Auto-quote whole string | |||
|
2560 | newcmd = '%s("%s")' % (iFun,theRest) | |||
|
2561 | elif pre == self.ESC_PAREN: | |||
|
2562 | newcmd = '%s(%s)' % (iFun,",".join(theRest.split())) | |||
|
2563 | else: | |||
|
2564 | # Auto-paren. | |||
|
2565 | # We only apply it to argument-less calls if the autocall | |||
|
2566 | # parameter is set to 2. We only need to check that autocall is < | |||
|
2567 | # 2, since this function isn't called unless it's at least 1. | |||
|
2568 | if not theRest and (self.rc.autocall < 2) and not force_auto: | |||
|
2569 | newcmd = '%s %s' % (iFun,theRest) | |||
|
2570 | auto_rewrite = False | |||
|
2571 | else: | |||
|
2572 | if not force_auto and theRest.startswith('['): | |||
|
2573 | if hasattr(obj,'__getitem__'): | |||
|
2574 | # Don't autocall in this case: item access for an object | |||
|
2575 | # which is BOTH callable and implements __getitem__. | |||
|
2576 | newcmd = '%s %s' % (iFun,theRest) | |||
|
2577 | auto_rewrite = False | |||
|
2578 | else: | |||
|
2579 | # if the object doesn't support [] access, go ahead and | |||
|
2580 | # autocall | |||
|
2581 | newcmd = '%s(%s)' % (iFun.rstrip(),theRest) | |||
|
2582 | elif theRest.endswith(';'): | |||
|
2583 | newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1]) | |||
|
2584 | else: | |||
|
2585 | newcmd = '%s(%s)' % (iFun.rstrip(), theRest) | |||
|
2586 | ||||
|
2587 | if auto_rewrite: | |||
|
2588 | rw = self.outputcache.prompt1.auto_rewrite() + newcmd | |||
|
2589 | ||||
|
2590 | try: | |||
|
2591 | # plain ascii works better w/ pyreadline, on some machines, so | |||
|
2592 | # we use it and only print uncolored rewrite if we have unicode | |||
|
2593 | rw = str(rw) | |||
|
2594 | print >>Term.cout, rw | |||
|
2595 | except UnicodeEncodeError: | |||
|
2596 | print "-------------->" + newcmd | |||
|
2597 | ||||
|
2598 | # log what is now valid Python, not the actual user input (without the | |||
|
2599 | # final newline) | |||
|
2600 | self.log(line,newcmd,continue_prompt) | |||
|
2601 | return newcmd | |||
|
2602 | ||||
|
2603 | def handle_help(self, line_info): | |||
|
2604 | """Try to get some help for the object. | |||
|
2605 | ||||
|
2606 | obj? or ?obj -> basic information. | |||
|
2607 | obj?? or ??obj -> more details. | |||
|
2608 | """ | |||
|
2609 | ||||
|
2610 | line = line_info.line | |||
|
2611 | # We need to make sure that we don't process lines which would be | |||
|
2612 | # otherwise valid python, such as "x=1 # what?" | |||
|
2613 | try: | |||
|
2614 | codeop.compile_command(line) | |||
|
2615 | except SyntaxError: | |||
|
2616 | # We should only handle as help stuff which is NOT valid syntax | |||
|
2617 | if line[0]==self.ESC_HELP: | |||
|
2618 | line = line[1:] | |||
|
2619 | elif line[-1]==self.ESC_HELP: | |||
|
2620 | line = line[:-1] | |||
|
2621 | self.log(line,'#?'+line,line_info.continue_prompt) | |||
|
2622 | if line: | |||
|
2623 | #print 'line:<%r>' % line # dbg | |||
|
2624 | self.magic_pinfo(line) | |||
|
2625 | else: | |||
|
2626 | page(self.usage,screen_lines=self.rc.screen_length) | |||
|
2627 | return '' # Empty string is needed here! | |||
|
2628 | except: | |||
|
2629 | # Pass any other exceptions through to the normal handler | |||
|
2630 | return self.handle_normal(line_info) | |||
|
2631 | else: | |||
|
2632 | # If the code compiles ok, we should handle it normally | |||
|
2633 | return self.handle_normal(line_info) | |||
|
2634 | ||||
|
2635 | def getapi(self): | |||
|
2636 | """ Get an IPApi object for this shell instance | |||
|
2637 | ||||
|
2638 | Getting an IPApi object is always preferable to accessing the shell | |||
|
2639 | directly, but this holds true especially for extensions. | |||
|
2640 | ||||
|
2641 | It should always be possible to implement an extension with IPApi | |||
|
2642 | alone. If not, contact maintainer to request an addition. | |||
|
2643 | ||||
|
2644 | """ | |||
|
2645 | return self.api | |||
|
2646 | ||||
|
2647 | def handle_emacs(self, line_info): | |||
|
2648 | """Handle input lines marked by python-mode.""" | |||
|
2649 | ||||
|
2650 | # Currently, nothing is done. Later more functionality can be added | |||
|
2651 | # here if needed. | |||
|
2652 | ||||
|
2653 | # The input cache shouldn't be updated | |||
|
2654 | return line_info.line | |||
|
2655 | ||||
|
2656 | ||||
|
2657 | def mktempfile(self,data=None): | |||
|
2658 | """Make a new tempfile and return its filename. | |||
|
2659 | ||||
|
2660 | This makes a call to tempfile.mktemp, but it registers the created | |||
|
2661 | filename internally so ipython cleans it up at exit time. | |||
|
2662 | ||||
|
2663 | Optional inputs: | |||
|
2664 | ||||
|
2665 | - data(None): if data is given, it gets written out to the temp file | |||
|
2666 | immediately, and the file is closed again.""" | |||
|
2667 | ||||
|
2668 | filename = tempfile.mktemp('.py','ipython_edit_') | |||
|
2669 | self.tempfiles.append(filename) | |||
|
2670 | ||||
|
2671 | if data: | |||
|
2672 | tmp_file = open(filename,'w') | |||
|
2673 | tmp_file.write(data) | |||
|
2674 | tmp_file.close() | |||
|
2675 | return filename | |||
|
2676 | ||||
|
2677 | def write(self,data): | |||
|
2678 | """Write a string to the default output""" | |||
|
2679 | Term.cout.write(data) | |||
|
2680 | ||||
|
2681 | def write_err(self,data): | |||
|
2682 | """Write a string to the default error output""" | |||
|
2683 | Term.cerr.write(data) | |||
|
2684 | ||||
|
2685 | def ask_exit(self): | |||
|
2686 | """ Call for exiting. Can be overiden and used as a callback. """ | |||
|
2687 | self.exit_now = True | |||
|
2688 | ||||
|
2689 | def exit(self): | |||
|
2690 | """Handle interactive exit. | |||
|
2691 | ||||
|
2692 | This method calls the ask_exit callback.""" | |||
|
2693 | ||||
|
2694 | if self.rc.confirm_exit: | |||
|
2695 | if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'): | |||
|
2696 | self.ask_exit() | |||
|
2697 | else: | |||
|
2698 | self.ask_exit() | |||
|
2699 | ||||
|
2700 | def safe_execfile(self,fname,*where,**kw): | |||
|
2701 | """A safe version of the builtin execfile(). | |||
|
2702 | ||||
|
2703 | This version will never throw an exception, and knows how to handle | |||
|
2704 | ipython logs as well. | |||
|
2705 | ||||
|
2706 | :Parameters: | |||
|
2707 | fname : string | |||
|
2708 | Name of the file to be executed. | |||
|
2709 | ||||
|
2710 | where : tuple | |||
|
2711 | One or two namespaces, passed to execfile() as (globals,locals). | |||
|
2712 | If only one is given, it is passed as both. | |||
|
2713 | ||||
|
2714 | :Keywords: | |||
|
2715 | islog : boolean (False) | |||
|
2716 | ||||
|
2717 | quiet : boolean (True) | |||
|
2718 | ||||
|
2719 | exit_ignore : boolean (False) | |||
|
2720 | """ | |||
|
2721 | ||||
|
2722 | def syspath_cleanup(): | |||
|
2723 | """Internal cleanup routine for sys.path.""" | |||
|
2724 | if add_dname: | |||
|
2725 | try: | |||
|
2726 | sys.path.remove(dname) | |||
|
2727 | except ValueError: | |||
|
2728 | # For some reason the user has already removed it, ignore. | |||
|
2729 | pass | |||
|
2730 | ||||
|
2731 | fname = os.path.expanduser(fname) | |||
|
2732 | ||||
|
2733 | # Find things also in current directory. This is needed to mimic the | |||
|
2734 | # behavior of running a script from the system command line, where | |||
|
2735 | # Python inserts the script's directory into sys.path | |||
|
2736 | dname = os.path.dirname(os.path.abspath(fname)) | |||
|
2737 | add_dname = False | |||
|
2738 | if dname not in sys.path: | |||
|
2739 | sys.path.insert(0,dname) | |||
|
2740 | add_dname = True | |||
|
2741 | ||||
|
2742 | try: | |||
|
2743 | xfile = open(fname) | |||
|
2744 | except: | |||
|
2745 | print >> Term.cerr, \ | |||
|
2746 | 'Could not open file <%s> for safe execution.' % fname | |||
|
2747 | syspath_cleanup() | |||
|
2748 | return None | |||
|
2749 | ||||
|
2750 | kw.setdefault('islog',0) | |||
|
2751 | kw.setdefault('quiet',1) | |||
|
2752 | kw.setdefault('exit_ignore',0) | |||
|
2753 | ||||
|
2754 | first = xfile.readline() | |||
|
2755 | loghead = str(self.loghead_tpl).split('\n',1)[0].strip() | |||
|
2756 | xfile.close() | |||
|
2757 | # line by line execution | |||
|
2758 | if first.startswith(loghead) or kw['islog']: | |||
|
2759 | print 'Loading log file <%s> one line at a time...' % fname | |||
|
2760 | if kw['quiet']: | |||
|
2761 | stdout_save = sys.stdout | |||
|
2762 | sys.stdout = StringIO.StringIO() | |||
|
2763 | try: | |||
|
2764 | globs,locs = where[0:2] | |||
|
2765 | except: | |||
|
2766 | try: | |||
|
2767 | globs = locs = where[0] | |||
|
2768 | except: | |||
|
2769 | globs = locs = globals() | |||
|
2770 | badblocks = [] | |||
|
2771 | ||||
|
2772 | # we also need to identify indented blocks of code when replaying | |||
|
2773 | # logs and put them together before passing them to an exec | |||
|
2774 | # statement. This takes a bit of regexp and look-ahead work in the | |||
|
2775 | # file. It's easiest if we swallow the whole thing in memory | |||
|
2776 | # first, and manually walk through the lines list moving the | |||
|
2777 | # counter ourselves. | |||
|
2778 | indent_re = re.compile('\s+\S') | |||
|
2779 | xfile = open(fname) | |||
|
2780 | filelines = xfile.readlines() | |||
|
2781 | xfile.close() | |||
|
2782 | nlines = len(filelines) | |||
|
2783 | lnum = 0 | |||
|
2784 | while lnum < nlines: | |||
|
2785 | line = filelines[lnum] | |||
|
2786 | lnum += 1 | |||
|
2787 | # don't re-insert logger status info into cache | |||
|
2788 | if line.startswith('#log#'): | |||
|
2789 | continue | |||
|
2790 | else: | |||
|
2791 | # build a block of code (maybe a single line) for execution | |||
|
2792 | block = line | |||
|
2793 | try: | |||
|
2794 | next = filelines[lnum] # lnum has already incremented | |||
|
2795 | except: | |||
|
2796 | next = None | |||
|
2797 | while next and indent_re.match(next): | |||
|
2798 | block += next | |||
|
2799 | lnum += 1 | |||
|
2800 | try: | |||
|
2801 | next = filelines[lnum] | |||
|
2802 | except: | |||
|
2803 | next = None | |||
|
2804 | # now execute the block of one or more lines | |||
|
2805 | try: | |||
|
2806 | exec block in globs,locs | |||
|
2807 | except SystemExit: | |||
|
2808 | pass | |||
|
2809 | except: | |||
|
2810 | badblocks.append(block.rstrip()) | |||
|
2811 | if kw['quiet']: # restore stdout | |||
|
2812 | sys.stdout.close() | |||
|
2813 | sys.stdout = stdout_save | |||
|
2814 | print 'Finished replaying log file <%s>' % fname | |||
|
2815 | if badblocks: | |||
|
2816 | print >> sys.stderr, ('\nThe following lines/blocks in file ' | |||
|
2817 | '<%s> reported errors:' % fname) | |||
|
2818 | ||||
|
2819 | for badline in badblocks: | |||
|
2820 | print >> sys.stderr, badline | |||
|
2821 | else: # regular file execution | |||
|
2822 | try: | |||
|
2823 | if sys.platform == 'win32' and sys.version_info < (2,5,1): | |||
|
2824 | # Work around a bug in Python for Windows. The bug was | |||
|
2825 | # fixed in in Python 2.5 r54159 and 54158, but that's still | |||
|
2826 | # SVN Python as of March/07. For details, see: | |||
|
2827 | # http://projects.scipy.org/ipython/ipython/ticket/123 | |||
|
2828 | try: | |||
|
2829 | globs,locs = where[0:2] | |||
|
2830 | except: | |||
|
2831 | try: | |||
|
2832 | globs = locs = where[0] | |||
|
2833 | except: | |||
|
2834 | globs = locs = globals() | |||
|
2835 | exec file(fname) in globs,locs | |||
|
2836 | else: | |||
|
2837 | execfile(fname,*where) | |||
|
2838 | except SyntaxError: | |||
|
2839 | self.showsyntaxerror() | |||
|
2840 | warn('Failure executing file: <%s>' % fname) | |||
|
2841 | except SystemExit,status: | |||
|
2842 | # Code that correctly sets the exit status flag to success (0) | |||
|
2843 | # shouldn't be bothered with a traceback. Note that a plain | |||
|
2844 | # sys.exit() does NOT set the message to 0 (it's empty) so that | |||
|
2845 | # will still get a traceback. Note that the structure of the | |||
|
2846 | # SystemExit exception changed between Python 2.4 and 2.5, so | |||
|
2847 | # the checks must be done in a version-dependent way. | |||
|
2848 | show = False | |||
|
2849 | ||||
|
2850 | if sys.version_info[:2] > (2,5): | |||
|
2851 | if status.message!=0 and not kw['exit_ignore']: | |||
|
2852 | show = True | |||
|
2853 | else: | |||
|
2854 | if status.code and not kw['exit_ignore']: | |||
|
2855 | show = True | |||
|
2856 | if show: | |||
|
2857 | self.showtraceback() | |||
|
2858 | warn('Failure executing file: <%s>' % fname) | |||
|
2859 | except: | |||
|
2860 | self.showtraceback() | |||
|
2861 | warn('Failure executing file: <%s>' % fname) | |||
|
2862 | ||||
|
2863 | syspath_cleanup() | |||
|
2864 | ||||
|
2865 | #************************* end of file <iplib.py> ***************************** |
This diff has been collapsed as it changes many lines, (1247 lines changed) Show them Hide them | |||||
@@ -0,0 +1,1247 b'' | |||||
|
1 | # -*- coding: utf-8 -*- | |||
|
2 | """IPython Shell classes. | |||
|
3 | ||||
|
4 | All the matplotlib support code was co-developed with John Hunter, | |||
|
5 | matplotlib's author. | |||
|
6 | """ | |||
|
7 | ||||
|
8 | #***************************************************************************** | |||
|
9 | # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu> | |||
|
10 | # | |||
|
11 | # Distributed under the terms of the BSD License. The full license is in | |||
|
12 | # the file COPYING, distributed as part of this software. | |||
|
13 | #***************************************************************************** | |||
|
14 | ||||
|
15 | # Code begins | |||
|
16 | # Stdlib imports | |||
|
17 | import __builtin__ | |||
|
18 | import __main__ | |||
|
19 | import Queue | |||
|
20 | import inspect | |||
|
21 | import os | |||
|
22 | import sys | |||
|
23 | import thread | |||
|
24 | import threading | |||
|
25 | import time | |||
|
26 | ||||
|
27 | from signal import signal, SIGINT | |||
|
28 | ||||
|
29 | try: | |||
|
30 | import ctypes | |||
|
31 | HAS_CTYPES = True | |||
|
32 | except ImportError: | |||
|
33 | HAS_CTYPES = False | |||
|
34 | ||||
|
35 | # IPython imports | |||
|
36 | import IPython | |||
|
37 | from IPython.core import ultratb | |||
|
38 | from IPython.core import ipapi | |||
|
39 | from IPython.core.magic import Magic | |||
|
40 | from IPython.utils.genutils import Term,warn,error,flag_calls, ask_yes_no | |||
|
41 | from IPython.core.iplib import InteractiveShell | |||
|
42 | from IPython.core.ipmaker import make_IPython | |||
|
43 | from IPython.utils.ipstruct import Struct | |||
|
44 | from IPython.testing import decorators as testdec | |||
|
45 | ||||
|
46 | # Globals | |||
|
47 | # global flag to pass around information about Ctrl-C without exceptions | |||
|
48 | KBINT = False | |||
|
49 | ||||
|
50 | # global flag to turn on/off Tk support. | |||
|
51 | USE_TK = False | |||
|
52 | ||||
|
53 | # ID for the main thread, used for cross-thread exceptions | |||
|
54 | MAIN_THREAD_ID = thread.get_ident() | |||
|
55 | ||||
|
56 | # Tag when runcode() is active, for exception handling | |||
|
57 | CODE_RUN = None | |||
|
58 | ||||
|
59 | # Default timeout for waiting for multithreaded shells (in seconds) | |||
|
60 | GUI_TIMEOUT = 10 | |||
|
61 | ||||
|
62 | #----------------------------------------------------------------------------- | |||
|
63 | # This class is trivial now, but I want to have it in to publish a clean | |||
|
64 | # interface. Later when the internals are reorganized, code that uses this | |||
|
65 | # shouldn't have to change. | |||
|
66 | ||||
|
67 | class IPShell: | |||
|
68 | """Create an IPython instance.""" | |||
|
69 | ||||
|
70 | def __init__(self,argv=None,user_ns=None,user_global_ns=None, | |||
|
71 | debug=1,shell_class=InteractiveShell): | |||
|
72 | self.IP = make_IPython(argv,user_ns=user_ns, | |||
|
73 | user_global_ns=user_global_ns, | |||
|
74 | debug=debug,shell_class=shell_class) | |||
|
75 | ||||
|
76 | def mainloop(self,sys_exit=0,banner=None): | |||
|
77 | self.IP.mainloop(banner) | |||
|
78 | if sys_exit: | |||
|
79 | sys.exit() | |||
|
80 | ||||
|
81 | #----------------------------------------------------------------------------- | |||
|
82 | def kill_embedded(self,parameter_s=''): | |||
|
83 | """%kill_embedded : deactivate for good the current embedded IPython. | |||
|
84 | ||||
|
85 | This function (after asking for confirmation) sets an internal flag so that | |||
|
86 | an embedded IPython will never activate again. This is useful to | |||
|
87 | permanently disable a shell that is being called inside a loop: once you've | |||
|
88 | figured out what you needed from it, you may then kill it and the program | |||
|
89 | will then continue to run without the interactive shell interfering again. | |||
|
90 | """ | |||
|
91 | ||||
|
92 | kill = ask_yes_no("Are you sure you want to kill this embedded instance " | |||
|
93 | "(y/n)? [y/N] ",'n') | |||
|
94 | if kill: | |||
|
95 | self.shell.embedded_active = False | |||
|
96 | print "This embedded IPython will not reactivate anymore once you exit." | |||
|
97 | ||||
|
98 | class IPShellEmbed: | |||
|
99 | """Allow embedding an IPython shell into a running program. | |||
|
100 | ||||
|
101 | Instances of this class are callable, with the __call__ method being an | |||
|
102 | alias to the embed() method of an InteractiveShell instance. | |||
|
103 | ||||
|
104 | Usage (see also the example-embed.py file for a running example): | |||
|
105 | ||||
|
106 | ipshell = IPShellEmbed([argv,banner,exit_msg,rc_override]) | |||
|
107 | ||||
|
108 | - argv: list containing valid command-line options for IPython, as they | |||
|
109 | would appear in sys.argv[1:]. | |||
|
110 | ||||
|
111 | For example, the following command-line options: | |||
|
112 | ||||
|
113 | $ ipython -prompt_in1 'Input <\\#>' -colors LightBG | |||
|
114 | ||||
|
115 | would be passed in the argv list as: | |||
|
116 | ||||
|
117 | ['-prompt_in1','Input <\\#>','-colors','LightBG'] | |||
|
118 | ||||
|
119 | - banner: string which gets printed every time the interpreter starts. | |||
|
120 | ||||
|
121 | - exit_msg: string which gets printed every time the interpreter exits. | |||
|
122 | ||||
|
123 | - rc_override: a dict or Struct of configuration options such as those | |||
|
124 | used by IPython. These options are read from your ~/.ipython/ipythonrc | |||
|
125 | file when the Shell object is created. Passing an explicit rc_override | |||
|
126 | dict with any options you want allows you to override those values at | |||
|
127 | creation time without having to modify the file. This way you can create | |||
|
128 | embeddable instances configured in any way you want without editing any | |||
|
129 | global files (thus keeping your interactive IPython configuration | |||
|
130 | unchanged). | |||
|
131 | ||||
|
132 | Then the ipshell instance can be called anywhere inside your code: | |||
|
133 | ||||
|
134 | ipshell(header='') -> Opens up an IPython shell. | |||
|
135 | ||||
|
136 | - header: string printed by the IPython shell upon startup. This can let | |||
|
137 | you know where in your code you are when dropping into the shell. Note | |||
|
138 | that 'banner' gets prepended to all calls, so header is used for | |||
|
139 | location-specific information. | |||
|
140 | ||||
|
141 | For more details, see the __call__ method below. | |||
|
142 | ||||
|
143 | When the IPython shell is exited with Ctrl-D, normal program execution | |||
|
144 | resumes. | |||
|
145 | ||||
|
146 | This functionality was inspired by a posting on comp.lang.python by cmkl | |||
|
147 | <cmkleffner@gmx.de> on Dec. 06/01 concerning similar uses of pyrepl, and | |||
|
148 | by the IDL stop/continue commands.""" | |||
|
149 | ||||
|
150 | def __init__(self,argv=None,banner='',exit_msg=None,rc_override=None, | |||
|
151 | user_ns=None): | |||
|
152 | """Note that argv here is a string, NOT a list.""" | |||
|
153 | self.set_banner(banner) | |||
|
154 | self.set_exit_msg(exit_msg) | |||
|
155 | self.set_dummy_mode(0) | |||
|
156 | ||||
|
157 | # sys.displayhook is a global, we need to save the user's original | |||
|
158 | # Don't rely on __displayhook__, as the user may have changed that. | |||
|
159 | self.sys_displayhook_ori = sys.displayhook | |||
|
160 | ||||
|
161 | # save readline completer status | |||
|
162 | try: | |||
|
163 | #print 'Save completer',sys.ipcompleter # dbg | |||
|
164 | self.sys_ipcompleter_ori = sys.ipcompleter | |||
|
165 | except: | |||
|
166 | pass # not nested with IPython | |||
|
167 | ||||
|
168 | self.IP = make_IPython(argv,rc_override=rc_override, | |||
|
169 | embedded=True, | |||
|
170 | user_ns=user_ns) | |||
|
171 | ||||
|
172 | ip = ipapi.IPApi(self.IP) | |||
|
173 | ip.expose_magic("kill_embedded",kill_embedded) | |||
|
174 | ||||
|
175 | # copy our own displayhook also | |||
|
176 | self.sys_displayhook_embed = sys.displayhook | |||
|
177 | # and leave the system's display hook clean | |||
|
178 | sys.displayhook = self.sys_displayhook_ori | |||
|
179 | # don't use the ipython crash handler so that user exceptions aren't | |||
|
180 | # trapped | |||
|
181 | sys.excepthook = ultratb.FormattedTB(color_scheme = self.IP.rc.colors, | |||
|
182 | mode = self.IP.rc.xmode, | |||
|
183 | call_pdb = self.IP.rc.pdb) | |||
|
184 | self.restore_system_completer() | |||
|
185 | ||||
|
186 | def restore_system_completer(self): | |||
|
187 | """Restores the readline completer which was in place. | |||
|
188 | ||||
|
189 | This allows embedded IPython within IPython not to disrupt the | |||
|
190 | parent's completion. | |||
|
191 | """ | |||
|
192 | ||||
|
193 | try: | |||
|
194 | self.IP.readline.set_completer(self.sys_ipcompleter_ori) | |||
|
195 | sys.ipcompleter = self.sys_ipcompleter_ori | |||
|
196 | except: | |||
|
197 | pass | |||
|
198 | ||||
|
199 | def __call__(self,header='',local_ns=None,global_ns=None,dummy=None): | |||
|
200 | """Activate the interactive interpreter. | |||
|
201 | ||||
|
202 | __call__(self,header='',local_ns=None,global_ns,dummy=None) -> Start | |||
|
203 | the interpreter shell with the given local and global namespaces, and | |||
|
204 | optionally print a header string at startup. | |||
|
205 | ||||
|
206 | The shell can be globally activated/deactivated using the | |||
|
207 | set/get_dummy_mode methods. This allows you to turn off a shell used | |||
|
208 | for debugging globally. | |||
|
209 | ||||
|
210 | However, *each* time you call the shell you can override the current | |||
|
211 | state of dummy_mode with the optional keyword parameter 'dummy'. For | |||
|
212 | example, if you set dummy mode on with IPShell.set_dummy_mode(1), you | |||
|
213 | can still have a specific call work by making it as IPShell(dummy=0). | |||
|
214 | ||||
|
215 | The optional keyword parameter dummy controls whether the call | |||
|
216 | actually does anything. """ | |||
|
217 | ||||
|
218 | # If the user has turned it off, go away | |||
|
219 | if not self.IP.embedded_active: | |||
|
220 | return | |||
|
221 | ||||
|
222 | # Normal exits from interactive mode set this flag, so the shell can't | |||
|
223 | # re-enter (it checks this variable at the start of interactive mode). | |||
|
224 | self.IP.exit_now = False | |||
|
225 | ||||
|
226 | # Allow the dummy parameter to override the global __dummy_mode | |||
|
227 | if dummy or (dummy != 0 and self.__dummy_mode): | |||
|
228 | return | |||
|
229 | ||||
|
230 | # Set global subsystems (display,completions) to our values | |||
|
231 | sys.displayhook = self.sys_displayhook_embed | |||
|
232 | if self.IP.has_readline: | |||
|
233 | self.IP.set_completer() | |||
|
234 | ||||
|
235 | if self.banner and header: | |||
|
236 | format = '%s\n%s\n' | |||
|
237 | else: | |||
|
238 | format = '%s%s\n' | |||
|
239 | banner = format % (self.banner,header) | |||
|
240 | ||||
|
241 | # Call the embedding code with a stack depth of 1 so it can skip over | |||
|
242 | # our call and get the original caller's namespaces. | |||
|
243 | self.IP.embed_mainloop(banner,local_ns,global_ns,stack_depth=1) | |||
|
244 | ||||
|
245 | if self.exit_msg: | |||
|
246 | print self.exit_msg | |||
|
247 | ||||
|
248 | # Restore global systems (display, completion) | |||
|
249 | sys.displayhook = self.sys_displayhook_ori | |||
|
250 | self.restore_system_completer() | |||
|
251 | ||||
|
252 | def set_dummy_mode(self,dummy): | |||
|
253 | """Sets the embeddable shell's dummy mode parameter. | |||
|
254 | ||||
|
255 | set_dummy_mode(dummy): dummy = 0 or 1. | |||
|
256 | ||||
|
257 | This parameter is persistent and makes calls to the embeddable shell | |||
|
258 | silently return without performing any action. This allows you to | |||
|
259 | globally activate or deactivate a shell you're using with a single call. | |||
|
260 | ||||
|
261 | If you need to manually""" | |||
|
262 | ||||
|
263 | if dummy not in [0,1,False,True]: | |||
|
264 | raise ValueError,'dummy parameter must be boolean' | |||
|
265 | self.__dummy_mode = dummy | |||
|
266 | ||||
|
267 | def get_dummy_mode(self): | |||
|
268 | """Return the current value of the dummy mode parameter. | |||
|
269 | """ | |||
|
270 | return self.__dummy_mode | |||
|
271 | ||||
|
272 | def set_banner(self,banner): | |||
|
273 | """Sets the global banner. | |||
|
274 | ||||
|
275 | This banner gets prepended to every header printed when the shell | |||
|
276 | instance is called.""" | |||
|
277 | ||||
|
278 | self.banner = banner | |||
|
279 | ||||
|
280 | def set_exit_msg(self,exit_msg): | |||
|
281 | """Sets the global exit_msg. | |||
|
282 | ||||
|
283 | This exit message gets printed upon exiting every time the embedded | |||
|
284 | shell is called. It is None by default. """ | |||
|
285 | ||||
|
286 | self.exit_msg = exit_msg | |||
|
287 | ||||
|
288 | #----------------------------------------------------------------------------- | |||
|
289 | if HAS_CTYPES: | |||
|
290 | # Add async exception support. Trick taken from: | |||
|
291 | # http://sebulba.wikispaces.com/recipe+thread2 | |||
|
292 | def _async_raise(tid, exctype): | |||
|
293 | """raises the exception, performs cleanup if needed""" | |||
|
294 | if not inspect.isclass(exctype): | |||
|
295 | raise TypeError("Only types can be raised (not instances)") | |||
|
296 | # Explicit cast to c_long is necessary for 64-bit support: | |||
|
297 | # See https://bugs.launchpad.net/ipython/+bug/237073 | |||
|
298 | res = ctypes.pythonapi.PyThreadState_SetAsyncExc(ctypes.c_long(tid), | |||
|
299 | ctypes.py_object(exctype)) | |||
|
300 | if res == 0: | |||
|
301 | raise ValueError("invalid thread id") | |||
|
302 | elif res != 1: | |||
|
303 | # If it returns a number greater than one, you're in trouble, | |||
|
304 | # and you should call it again with exc=NULL to revert the effect | |||
|
305 | ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, 0) | |||
|
306 | raise SystemError("PyThreadState_SetAsyncExc failed") | |||
|
307 | ||||
|
308 | def sigint_handler(signum,stack_frame): | |||
|
309 | """Sigint handler for threaded apps. | |||
|
310 | ||||
|
311 | This is a horrible hack to pass information about SIGINT _without_ | |||
|
312 | using exceptions, since I haven't been able to properly manage | |||
|
313 | cross-thread exceptions in GTK/WX. In fact, I don't think it can be | |||
|
314 | done (or at least that's my understanding from a c.l.py thread where | |||
|
315 | this was discussed).""" | |||
|
316 | ||||
|
317 | global KBINT | |||
|
318 | ||||
|
319 | if CODE_RUN: | |||
|
320 | _async_raise(MAIN_THREAD_ID,KeyboardInterrupt) | |||
|
321 | else: | |||
|
322 | KBINT = True | |||
|
323 | print '\nKeyboardInterrupt - Press <Enter> to continue.', | |||
|
324 | Term.cout.flush() | |||
|
325 | ||||
|
326 | else: | |||
|
327 | def sigint_handler(signum,stack_frame): | |||
|
328 | """Sigint handler for threaded apps. | |||
|
329 | ||||
|
330 | This is a horrible hack to pass information about SIGINT _without_ | |||
|
331 | using exceptions, since I haven't been able to properly manage | |||
|
332 | cross-thread exceptions in GTK/WX. In fact, I don't think it can be | |||
|
333 | done (or at least that's my understanding from a c.l.py thread where | |||
|
334 | this was discussed).""" | |||
|
335 | ||||
|
336 | global KBINT | |||
|
337 | ||||
|
338 | print '\nKeyboardInterrupt - Press <Enter> to continue.', | |||
|
339 | Term.cout.flush() | |||
|
340 | # Set global flag so that runsource can know that Ctrl-C was hit | |||
|
341 | KBINT = True | |||
|
342 | ||||
|
343 | ||||
|
344 | class MTInteractiveShell(InteractiveShell): | |||
|
345 | """Simple multi-threaded shell.""" | |||
|
346 | ||||
|
347 | # Threading strategy taken from: | |||
|
348 | # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65109, by Brian | |||
|
349 | # McErlean and John Finlay. Modified with corrections by Antoon Pardon, | |||
|
350 | # from the pygtk mailing list, to avoid lockups with system calls. | |||
|
351 | ||||
|
352 | # class attribute to indicate whether the class supports threads or not. | |||
|
353 | # Subclasses with thread support should override this as needed. | |||
|
354 | isthreaded = True | |||
|
355 | ||||
|
356 | def __init__(self,name,usage=None,rc=Struct(opts=None,args=None), | |||
|
357 | user_ns=None,user_global_ns=None,banner2='', | |||
|
358 | gui_timeout=GUI_TIMEOUT,**kw): | |||
|
359 | """Similar to the normal InteractiveShell, but with threading control""" | |||
|
360 | ||||
|
361 | InteractiveShell.__init__(self,name,usage,rc,user_ns, | |||
|
362 | user_global_ns,banner2) | |||
|
363 | ||||
|
364 | # Timeout we wait for GUI thread | |||
|
365 | self.gui_timeout = gui_timeout | |||
|
366 | ||||
|
367 | # A queue to hold the code to be executed. | |||
|
368 | self.code_queue = Queue.Queue() | |||
|
369 | ||||
|
370 | # Stuff to do at closing time | |||
|
371 | self._kill = None | |||
|
372 | on_kill = kw.get('on_kill', []) | |||
|
373 | # Check that all things to kill are callable: | |||
|
374 | for t in on_kill: | |||
|
375 | if not callable(t): | |||
|
376 | raise TypeError,'on_kill must be a list of callables' | |||
|
377 | self.on_kill = on_kill | |||
|
378 | # thread identity of the "worker thread" (that may execute code directly) | |||
|
379 | self.worker_ident = None | |||
|
380 | ||||
|
381 | def runsource(self, source, filename="<input>", symbol="single"): | |||
|
382 | """Compile and run some source in the interpreter. | |||
|
383 | ||||
|
384 | Modified version of code.py's runsource(), to handle threading issues. | |||
|
385 | See the original for full docstring details.""" | |||
|
386 | ||||
|
387 | global KBINT | |||
|
388 | ||||
|
389 | # If Ctrl-C was typed, we reset the flag and return right away | |||
|
390 | if KBINT: | |||
|
391 | KBINT = False | |||
|
392 | return False | |||
|
393 | ||||
|
394 | if self._kill: | |||
|
395 | # can't queue new code if we are being killed | |||
|
396 | return True | |||
|
397 | ||||
|
398 | try: | |||
|
399 | code = self.compile(source, filename, symbol) | |||
|
400 | except (OverflowError, SyntaxError, ValueError): | |||
|
401 | # Case 1 | |||
|
402 | self.showsyntaxerror(filename) | |||
|
403 | return False | |||
|
404 | ||||
|
405 | if code is None: | |||
|
406 | # Case 2 | |||
|
407 | return True | |||
|
408 | ||||
|
409 | # shortcut - if we are in worker thread, or the worker thread is not | |||
|
410 | # running, execute directly (to allow recursion and prevent deadlock if | |||
|
411 | # code is run early in IPython construction) | |||
|
412 | ||||
|
413 | if (self.worker_ident is None | |||
|
414 | or self.worker_ident == thread.get_ident() ): | |||
|
415 | InteractiveShell.runcode(self,code) | |||
|
416 | return False | |||
|
417 | ||||
|
418 | # Case 3 | |||
|
419 | # Store code in queue, so the execution thread can handle it. | |||
|
420 | ||||
|
421 | completed_ev, received_ev = threading.Event(), threading.Event() | |||
|
422 | ||||
|
423 | self.code_queue.put((code,completed_ev, received_ev)) | |||
|
424 | # first make sure the message was received, with timeout | |||
|
425 | received_ev.wait(self.gui_timeout) | |||
|
426 | if not received_ev.isSet(): | |||
|
427 | # the mainloop is dead, start executing code directly | |||
|
428 | print "Warning: Timeout for mainloop thread exceeded" | |||
|
429 | print "switching to nonthreaded mode (until mainloop wakes up again)" | |||
|
430 | self.worker_ident = None | |||
|
431 | else: | |||
|
432 | completed_ev.wait() | |||
|
433 | return False | |||
|
434 | ||||
|
435 | def runcode(self): | |||
|
436 | """Execute a code object. | |||
|
437 | ||||
|
438 | Multithreaded wrapper around IPython's runcode().""" | |||
|
439 | ||||
|
440 | global CODE_RUN | |||
|
441 | ||||
|
442 | # we are in worker thread, stash out the id for runsource() | |||
|
443 | self.worker_ident = thread.get_ident() | |||
|
444 | ||||
|
445 | if self._kill: | |||
|
446 | print >>Term.cout, 'Closing threads...', | |||
|
447 | Term.cout.flush() | |||
|
448 | for tokill in self.on_kill: | |||
|
449 | tokill() | |||
|
450 | print >>Term.cout, 'Done.' | |||
|
451 | # allow kill() to return | |||
|
452 | self._kill.set() | |||
|
453 | return True | |||
|
454 | ||||
|
455 | # Install sigint handler. We do it every time to ensure that if user | |||
|
456 | # code modifies it, we restore our own handling. | |||
|
457 | try: | |||
|
458 | signal(SIGINT,sigint_handler) | |||
|
459 | except SystemError: | |||
|
460 | # This happens under Windows, which seems to have all sorts | |||
|
461 | # of problems with signal handling. Oh well... | |||
|
462 | pass | |||
|
463 | ||||
|
464 | # Flush queue of pending code by calling the run methood of the parent | |||
|
465 | # class with all items which may be in the queue. | |||
|
466 | code_to_run = None | |||
|
467 | while 1: | |||
|
468 | try: | |||
|
469 | code_to_run, completed_ev, received_ev = self.code_queue.get_nowait() | |||
|
470 | except Queue.Empty: | |||
|
471 | break | |||
|
472 | received_ev.set() | |||
|
473 | ||||
|
474 | # Exceptions need to be raised differently depending on which | |||
|
475 | # thread is active. This convoluted try/except is only there to | |||
|
476 | # protect against asynchronous exceptions, to ensure that a KBINT | |||
|
477 | # at the wrong time doesn't deadlock everything. The global | |||
|
478 | # CODE_TO_RUN is set to true/false as close as possible to the | |||
|
479 | # runcode() call, so that the KBINT handler is correctly informed. | |||
|
480 | try: | |||
|
481 | try: | |||
|
482 | CODE_RUN = True | |||
|
483 | InteractiveShell.runcode(self,code_to_run) | |||
|
484 | except KeyboardInterrupt: | |||
|
485 | print "Keyboard interrupted in mainloop" | |||
|
486 | while not self.code_queue.empty(): | |||
|
487 | code, ev1,ev2 = self.code_queue.get_nowait() | |||
|
488 | ev1.set() | |||
|
489 | ev2.set() | |||
|
490 | break | |||
|
491 | finally: | |||
|
492 | CODE_RUN = False | |||
|
493 | # allow runsource() return from wait | |||
|
494 | completed_ev.set() | |||
|
495 | ||||
|
496 | ||||
|
497 | # This MUST return true for gtk threading to work | |||
|
498 | return True | |||
|
499 | ||||
|
500 | def kill(self): | |||
|
501 | """Kill the thread, returning when it has been shut down.""" | |||
|
502 | self._kill = threading.Event() | |||
|
503 | self._kill.wait() | |||
|
504 | ||||
|
505 | class MatplotlibShellBase: | |||
|
506 | """Mixin class to provide the necessary modifications to regular IPython | |||
|
507 | shell classes for matplotlib support. | |||
|
508 | ||||
|
509 | Given Python's MRO, this should be used as the FIRST class in the | |||
|
510 | inheritance hierarchy, so that it overrides the relevant methods.""" | |||
|
511 | ||||
|
512 | def _matplotlib_config(self,name,user_ns,user_global_ns=None): | |||
|
513 | """Return items needed to setup the user's shell with matplotlib""" | |||
|
514 | ||||
|
515 | # Initialize matplotlib to interactive mode always | |||
|
516 | import matplotlib | |||
|
517 | from matplotlib import backends | |||
|
518 | matplotlib.interactive(True) | |||
|
519 | ||||
|
520 | def use(arg): | |||
|
521 | """IPython wrapper for matplotlib's backend switcher. | |||
|
522 | ||||
|
523 | In interactive use, we can not allow switching to a different | |||
|
524 | interactive backend, since thread conflicts will most likely crash | |||
|
525 | the python interpreter. This routine does a safety check first, | |||
|
526 | and refuses to perform a dangerous switch. It still allows | |||
|
527 | switching to non-interactive backends.""" | |||
|
528 | ||||
|
529 | if arg in backends.interactive_bk and arg != self.mpl_backend: | |||
|
530 | m=('invalid matplotlib backend switch.\n' | |||
|
531 | 'This script attempted to switch to the interactive ' | |||
|
532 | 'backend: `%s`\n' | |||
|
533 | 'Your current choice of interactive backend is: `%s`\n\n' | |||
|
534 | 'Switching interactive matplotlib backends at runtime\n' | |||
|
535 | 'would crash the python interpreter, ' | |||
|
536 | 'and IPython has blocked it.\n\n' | |||
|
537 | 'You need to either change your choice of matplotlib backend\n' | |||
|
538 | 'by editing your .matplotlibrc file, or run this script as a \n' | |||
|
539 | 'standalone file from the command line, not using IPython.\n' % | |||
|
540 | (arg,self.mpl_backend) ) | |||
|
541 | raise RuntimeError, m | |||
|
542 | else: | |||
|
543 | self.mpl_use(arg) | |||
|
544 | self.mpl_use._called = True | |||
|
545 | ||||
|
546 | self.matplotlib = matplotlib | |||
|
547 | self.mpl_backend = matplotlib.rcParams['backend'] | |||
|
548 | ||||
|
549 | # we also need to block switching of interactive backends by use() | |||
|
550 | self.mpl_use = matplotlib.use | |||
|
551 | self.mpl_use._called = False | |||
|
552 | # overwrite the original matplotlib.use with our wrapper | |||
|
553 | matplotlib.use = use | |||
|
554 | ||||
|
555 | # This must be imported last in the matplotlib series, after | |||
|
556 | # backend/interactivity choices have been made | |||
|
557 | import matplotlib.pylab as pylab | |||
|
558 | self.pylab = pylab | |||
|
559 | ||||
|
560 | self.pylab.show._needmain = False | |||
|
561 | # We need to detect at runtime whether show() is called by the user. | |||
|
562 | # For this, we wrap it into a decorator which adds a 'called' flag. | |||
|
563 | self.pylab.draw_if_interactive = flag_calls(self.pylab.draw_if_interactive) | |||
|
564 | ||||
|
565 | # Build a user namespace initialized with matplotlib/matlab features. | |||
|
566 | user_ns, user_global_ns = ipapi.make_user_namespaces(user_ns, | |||
|
567 | user_global_ns) | |||
|
568 | ||||
|
569 | # Import numpy as np/pyplot as plt are conventions we're trying to | |||
|
570 | # somewhat standardize on. Making them available to users by default | |||
|
571 | # will greatly help this. | |||
|
572 | exec ("import numpy\n" | |||
|
573 | "import numpy as np\n" | |||
|
574 | "import matplotlib\n" | |||
|
575 | "import matplotlib.pylab as pylab\n" | |||
|
576 | "try:\n" | |||
|
577 | " import matplotlib.pyplot as plt\n" | |||
|
578 | "except ImportError:\n" | |||
|
579 | " pass\n" | |||
|
580 | ) in user_ns | |||
|
581 | ||||
|
582 | # Build matplotlib info banner | |||
|
583 | b=""" | |||
|
584 | Welcome to pylab, a matplotlib-based Python environment. | |||
|
585 | For more information, type 'help(pylab)'. | |||
|
586 | """ | |||
|
587 | return user_ns,user_global_ns,b | |||
|
588 | ||||
|
589 | def mplot_exec(self,fname,*where,**kw): | |||
|
590 | """Execute a matplotlib script. | |||
|
591 | ||||
|
592 | This is a call to execfile(), but wrapped in safeties to properly | |||
|
593 | handle interactive rendering and backend switching.""" | |||
|
594 | ||||
|
595 | #print '*** Matplotlib runner ***' # dbg | |||
|
596 | # turn off rendering until end of script | |||
|
597 | isInteractive = self.matplotlib.rcParams['interactive'] | |||
|
598 | self.matplotlib.interactive(False) | |||
|
599 | self.safe_execfile(fname,*where,**kw) | |||
|
600 | self.matplotlib.interactive(isInteractive) | |||
|
601 | # make rendering call now, if the user tried to do it | |||
|
602 | if self.pylab.draw_if_interactive.called: | |||
|
603 | self.pylab.draw() | |||
|
604 | self.pylab.draw_if_interactive.called = False | |||
|
605 | ||||
|
606 | # if a backend switch was performed, reverse it now | |||
|
607 | if self.mpl_use._called: | |||
|
608 | self.matplotlib.rcParams['backend'] = self.mpl_backend | |||
|
609 | ||||
|
610 | @testdec.skip_doctest | |||
|
611 | def magic_run(self,parameter_s=''): | |||
|
612 | Magic.magic_run(self,parameter_s,runner=self.mplot_exec) | |||
|
613 | ||||
|
614 | # Fix the docstring so users see the original as well | |||
|
615 | magic_run.__doc__ = "%s\n%s" % (Magic.magic_run.__doc__, | |||
|
616 | "\n *** Modified %run for Matplotlib," | |||
|
617 | " with proper interactive handling ***") | |||
|
618 | ||||
|
619 | # Now we provide 2 versions of a matplotlib-aware IPython base shells, single | |||
|
620 | # and multithreaded. Note that these are meant for internal use, the IPShell* | |||
|
621 | # classes below are the ones meant for public consumption. | |||
|
622 | ||||
|
623 | class MatplotlibShell(MatplotlibShellBase,InteractiveShell): | |||
|
624 | """Single-threaded shell with matplotlib support.""" | |||
|
625 | ||||
|
626 | def __init__(self,name,usage=None,rc=Struct(opts=None,args=None), | |||
|
627 | user_ns=None,user_global_ns=None,**kw): | |||
|
628 | user_ns,user_global_ns,b2 = self._matplotlib_config(name,user_ns,user_global_ns) | |||
|
629 | InteractiveShell.__init__(self,name,usage,rc,user_ns,user_global_ns, | |||
|
630 | banner2=b2,**kw) | |||
|
631 | ||||
|
632 | class MatplotlibMTShell(MatplotlibShellBase,MTInteractiveShell): | |||
|
633 | """Multi-threaded shell with matplotlib support.""" | |||
|
634 | ||||
|
635 | def __init__(self,name,usage=None,rc=Struct(opts=None,args=None), | |||
|
636 | user_ns=None,user_global_ns=None, **kw): | |||
|
637 | user_ns,user_global_ns,b2 = self._matplotlib_config(name,user_ns,user_global_ns) | |||
|
638 | MTInteractiveShell.__init__(self,name,usage,rc,user_ns,user_global_ns, | |||
|
639 | banner2=b2,**kw) | |||
|
640 | ||||
|
641 | #----------------------------------------------------------------------------- | |||
|
642 | # Utility functions for the different GUI enabled IPShell* classes. | |||
|
643 | ||||
|
644 | def get_tk(): | |||
|
645 | """Tries to import Tkinter and returns a withdrawn Tkinter root | |||
|
646 | window. If Tkinter is already imported or not available, this | |||
|
647 | returns None. This function calls `hijack_tk` underneath. | |||
|
648 | """ | |||
|
649 | if not USE_TK or sys.modules.has_key('Tkinter'): | |||
|
650 | return None | |||
|
651 | else: | |||
|
652 | try: | |||
|
653 | import Tkinter | |||
|
654 | except ImportError: | |||
|
655 | return None | |||
|
656 | else: | |||
|
657 | hijack_tk() | |||
|
658 | r = Tkinter.Tk() | |||
|
659 | r.withdraw() | |||
|
660 | return r | |||
|
661 | ||||
|
662 | def hijack_tk(): | |||
|
663 | """Modifies Tkinter's mainloop with a dummy so when a module calls | |||
|
664 | mainloop, it does not block. | |||
|
665 | ||||
|
666 | """ | |||
|
667 | def misc_mainloop(self, n=0): | |||
|
668 | pass | |||
|
669 | def tkinter_mainloop(n=0): | |||
|
670 | pass | |||
|
671 | ||||
|
672 | import Tkinter | |||
|
673 | Tkinter.Misc.mainloop = misc_mainloop | |||
|
674 | Tkinter.mainloop = tkinter_mainloop | |||
|
675 | ||||
|
676 | def update_tk(tk): | |||
|
677 | """Updates the Tkinter event loop. This is typically called from | |||
|
678 | the respective WX or GTK mainloops. | |||
|
679 | """ | |||
|
680 | if tk: | |||
|
681 | tk.update() | |||
|
682 | ||||
|
683 | def hijack_wx(): | |||
|
684 | """Modifies wxPython's MainLoop with a dummy so user code does not | |||
|
685 | block IPython. The hijacked mainloop function is returned. | |||
|
686 | """ | |||
|
687 | def dummy_mainloop(*args, **kw): | |||
|
688 | pass | |||
|
689 | ||||
|
690 | try: | |||
|
691 | import wx | |||
|
692 | except ImportError: | |||
|
693 | # For very old versions of WX | |||
|
694 | import wxPython as wx | |||
|
695 | ||||
|
696 | ver = wx.__version__ | |||
|
697 | orig_mainloop = None | |||
|
698 | if ver[:3] >= '2.5': | |||
|
699 | import wx | |||
|
700 | if hasattr(wx, '_core_'): core = getattr(wx, '_core_') | |||
|
701 | elif hasattr(wx, '_core'): core = getattr(wx, '_core') | |||
|
702 | else: raise AttributeError('Could not find wx core module') | |||
|
703 | orig_mainloop = core.PyApp_MainLoop | |||
|
704 | core.PyApp_MainLoop = dummy_mainloop | |||
|
705 | elif ver[:3] == '2.4': | |||
|
706 | orig_mainloop = wx.wxc.wxPyApp_MainLoop | |||
|
707 | wx.wxc.wxPyApp_MainLoop = dummy_mainloop | |||
|
708 | else: | |||
|
709 | warn("Unable to find either wxPython version 2.4 or >= 2.5.") | |||
|
710 | return orig_mainloop | |||
|
711 | ||||
|
712 | def hijack_gtk(): | |||
|
713 | """Modifies pyGTK's mainloop with a dummy so user code does not | |||
|
714 | block IPython. This function returns the original `gtk.mainloop` | |||
|
715 | function that has been hijacked. | |||
|
716 | """ | |||
|
717 | def dummy_mainloop(*args, **kw): | |||
|
718 | pass | |||
|
719 | import gtk | |||
|
720 | if gtk.pygtk_version >= (2,4,0): orig_mainloop = gtk.main | |||
|
721 | else: orig_mainloop = gtk.mainloop | |||
|
722 | gtk.mainloop = dummy_mainloop | |||
|
723 | gtk.main = dummy_mainloop | |||
|
724 | return orig_mainloop | |||
|
725 | ||||
|
726 | def hijack_qt(): | |||
|
727 | """Modifies PyQt's mainloop with a dummy so user code does not | |||
|
728 | block IPython. This function returns the original | |||
|
729 | `qt.qApp.exec_loop` function that has been hijacked. | |||
|
730 | """ | |||
|
731 | def dummy_mainloop(*args, **kw): | |||
|
732 | pass | |||
|
733 | import qt | |||
|
734 | orig_mainloop = qt.qApp.exec_loop | |||
|
735 | qt.qApp.exec_loop = dummy_mainloop | |||
|
736 | qt.QApplication.exec_loop = dummy_mainloop | |||
|
737 | return orig_mainloop | |||
|
738 | ||||
|
739 | def hijack_qt4(): | |||
|
740 | """Modifies PyQt4's mainloop with a dummy so user code does not | |||
|
741 | block IPython. This function returns the original | |||
|
742 | `QtGui.qApp.exec_` function that has been hijacked. | |||
|
743 | """ | |||
|
744 | def dummy_mainloop(*args, **kw): | |||
|
745 | pass | |||
|
746 | from PyQt4 import QtGui, QtCore | |||
|
747 | orig_mainloop = QtGui.qApp.exec_ | |||
|
748 | QtGui.qApp.exec_ = dummy_mainloop | |||
|
749 | QtGui.QApplication.exec_ = dummy_mainloop | |||
|
750 | QtCore.QCoreApplication.exec_ = dummy_mainloop | |||
|
751 | return orig_mainloop | |||
|
752 | ||||
|
753 | #----------------------------------------------------------------------------- | |||
|
754 | # The IPShell* classes below are the ones meant to be run by external code as | |||
|
755 | # IPython instances. Note that unless a specific threading strategy is | |||
|
756 | # desired, the factory function start() below should be used instead (it | |||
|
757 | # selects the proper threaded class). | |||
|
758 | ||||
|
759 | class IPThread(threading.Thread): | |||
|
760 | def run(self): | |||
|
761 | self.IP.mainloop(self._banner) | |||
|
762 | self.IP.kill() | |||
|
763 | ||||
|
764 | class IPShellGTK(IPThread): | |||
|
765 | """Run a gtk mainloop() in a separate thread. | |||
|
766 | ||||
|
767 | Python commands can be passed to the thread where they will be executed. | |||
|
768 | This is implemented by periodically checking for passed code using a | |||
|
769 | GTK timeout callback.""" | |||
|
770 | ||||
|
771 | TIMEOUT = 100 # Millisecond interval between timeouts. | |||
|
772 | ||||
|
773 | def __init__(self,argv=None,user_ns=None,user_global_ns=None, | |||
|
774 | debug=1,shell_class=MTInteractiveShell): | |||
|
775 | ||||
|
776 | import gtk | |||
|
777 | # Check for set_interactive, coming up in new pygtk. | |||
|
778 | # Disable it so that this code works, but notify | |||
|
779 | # the user that he has a better option as well. | |||
|
780 | # XXX TODO better support when set_interactive is released | |||
|
781 | try: | |||
|
782 | gtk.set_interactive(False) | |||
|
783 | print "Your PyGtk has set_interactive(), so you can use the" | |||
|
784 | print "more stable single-threaded Gtk mode." | |||
|
785 | print "See https://bugs.launchpad.net/ipython/+bug/270856" | |||
|
786 | except AttributeError: | |||
|
787 | pass | |||
|
788 | ||||
|
789 | self.gtk = gtk | |||
|
790 | self.gtk_mainloop = hijack_gtk() | |||
|
791 | ||||
|
792 | # Allows us to use both Tk and GTK. | |||
|
793 | self.tk = get_tk() | |||
|
794 | ||||
|
795 | if gtk.pygtk_version >= (2,4,0): mainquit = self.gtk.main_quit | |||
|
796 | else: mainquit = self.gtk.mainquit | |||
|
797 | ||||
|
798 | self.IP = make_IPython(argv,user_ns=user_ns, | |||
|
799 | user_global_ns=user_global_ns, | |||
|
800 | debug=debug, | |||
|
801 | shell_class=shell_class, | |||
|
802 | on_kill=[mainquit]) | |||
|
803 | ||||
|
804 | # HACK: slot for banner in self; it will be passed to the mainloop | |||
|
805 | # method only and .run() needs it. The actual value will be set by | |||
|
806 | # .mainloop(). | |||
|
807 | self._banner = None | |||
|
808 | ||||
|
809 | threading.Thread.__init__(self) | |||
|
810 | ||||
|
811 | def mainloop(self,sys_exit=0,banner=None): | |||
|
812 | ||||
|
813 | self._banner = banner | |||
|
814 | ||||
|
815 | if self.gtk.pygtk_version >= (2,4,0): | |||
|
816 | import gobject | |||
|
817 | gobject.idle_add(self.on_timer) | |||
|
818 | else: | |||
|
819 | self.gtk.idle_add(self.on_timer) | |||
|
820 | ||||
|
821 | if sys.platform != 'win32': | |||
|
822 | try: | |||
|
823 | if self.gtk.gtk_version[0] >= 2: | |||
|
824 | self.gtk.gdk.threads_init() | |||
|
825 | except AttributeError: | |||
|
826 | pass | |||
|
827 | except RuntimeError: | |||
|
828 | error('Your pyGTK likely has not been compiled with ' | |||
|
829 | 'threading support.\n' | |||
|
830 | 'The exception printout is below.\n' | |||
|
831 | 'You can either rebuild pyGTK with threads, or ' | |||
|
832 | 'try using \n' | |||
|
833 | 'matplotlib with a different backend (like Tk or WX).\n' | |||
|
834 | 'Note that matplotlib will most likely not work in its ' | |||
|
835 | 'current state!') | |||
|
836 | self.IP.InteractiveTB() | |||
|
837 | ||||
|
838 | self.start() | |||
|
839 | self.gtk.gdk.threads_enter() | |||
|
840 | self.gtk_mainloop() | |||
|
841 | self.gtk.gdk.threads_leave() | |||
|
842 | self.join() | |||
|
843 | ||||
|
844 | def on_timer(self): | |||
|
845 | """Called when GTK is idle. | |||
|
846 | ||||
|
847 | Must return True always, otherwise GTK stops calling it""" | |||
|
848 | ||||
|
849 | update_tk(self.tk) | |||
|
850 | self.IP.runcode() | |||
|
851 | time.sleep(0.01) | |||
|
852 | return True | |||
|
853 | ||||
|
854 | ||||
|
855 | class IPShellWX(IPThread): | |||
|
856 | """Run a wx mainloop() in a separate thread. | |||
|
857 | ||||
|
858 | Python commands can be passed to the thread where they will be executed. | |||
|
859 | This is implemented by periodically checking for passed code using a | |||
|
860 | GTK timeout callback.""" | |||
|
861 | ||||
|
862 | TIMEOUT = 100 # Millisecond interval between timeouts. | |||
|
863 | ||||
|
864 | def __init__(self,argv=None,user_ns=None,user_global_ns=None, | |||
|
865 | debug=1,shell_class=MTInteractiveShell): | |||
|
866 | ||||
|
867 | self.IP = make_IPython(argv,user_ns=user_ns, | |||
|
868 | user_global_ns=user_global_ns, | |||
|
869 | debug=debug, | |||
|
870 | shell_class=shell_class, | |||
|
871 | on_kill=[self.wxexit]) | |||
|
872 | ||||
|
873 | wantedwxversion=self.IP.rc.wxversion | |||
|
874 | if wantedwxversion!="0": | |||
|
875 | try: | |||
|
876 | import wxversion | |||
|
877 | except ImportError: | |||
|
878 | error('The wxversion module is needed for WX version selection') | |||
|
879 | else: | |||
|
880 | try: | |||
|
881 | wxversion.select(wantedwxversion) | |||
|
882 | except: | |||
|
883 | self.IP.InteractiveTB() | |||
|
884 | error('Requested wxPython version %s could not be loaded' % | |||
|
885 | wantedwxversion) | |||
|
886 | ||||
|
887 | import wx | |||
|
888 | ||||
|
889 | threading.Thread.__init__(self) | |||
|
890 | self.wx = wx | |||
|
891 | self.wx_mainloop = hijack_wx() | |||
|
892 | ||||
|
893 | # Allows us to use both Tk and GTK. | |||
|
894 | self.tk = get_tk() | |||
|
895 | ||||
|
896 | # HACK: slot for banner in self; it will be passed to the mainloop | |||
|
897 | # method only and .run() needs it. The actual value will be set by | |||
|
898 | # .mainloop(). | |||
|
899 | self._banner = None | |||
|
900 | ||||
|
901 | self.app = None | |||
|
902 | ||||
|
903 | def wxexit(self, *args): | |||
|
904 | if self.app is not None: | |||
|
905 | self.app.agent.timer.Stop() | |||
|
906 | self.app.ExitMainLoop() | |||
|
907 | ||||
|
908 | def mainloop(self,sys_exit=0,banner=None): | |||
|
909 | ||||
|
910 | self._banner = banner | |||
|
911 | ||||
|
912 | self.start() | |||
|
913 | ||||
|
914 | class TimerAgent(self.wx.MiniFrame): | |||
|
915 | wx = self.wx | |||
|
916 | IP = self.IP | |||
|
917 | tk = self.tk | |||
|
918 | def __init__(self, parent, interval): | |||
|
919 | style = self.wx.DEFAULT_FRAME_STYLE | self.wx.TINY_CAPTION_HORIZ | |||
|
920 | self.wx.MiniFrame.__init__(self, parent, -1, ' ', pos=(200, 200), | |||
|
921 | size=(100, 100),style=style) | |||
|
922 | self.Show(False) | |||
|
923 | self.interval = interval | |||
|
924 | self.timerId = self.wx.NewId() | |||
|
925 | ||||
|
926 | def StartWork(self): | |||
|
927 | self.timer = self.wx.Timer(self, self.timerId) | |||
|
928 | self.wx.EVT_TIMER(self, self.timerId, self.OnTimer) | |||
|
929 | self.timer.Start(self.interval) | |||
|
930 | ||||
|
931 | def OnTimer(self, event): | |||
|
932 | update_tk(self.tk) | |||
|
933 | self.IP.runcode() | |||
|
934 | ||||
|
935 | class App(self.wx.App): | |||
|
936 | wx = self.wx | |||
|
937 | TIMEOUT = self.TIMEOUT | |||
|
938 | def OnInit(self): | |||
|
939 | 'Create the main window and insert the custom frame' | |||
|
940 | self.agent = TimerAgent(None, self.TIMEOUT) | |||
|
941 | self.agent.Show(False) | |||
|
942 | self.agent.StartWork() | |||
|
943 | return True | |||
|
944 | ||||
|
945 | self.app = App(redirect=False) | |||
|
946 | self.wx_mainloop(self.app) | |||
|
947 | self.join() | |||
|
948 | ||||
|
949 | ||||
|
950 | class IPShellQt(IPThread): | |||
|
951 | """Run a Qt event loop in a separate thread. | |||
|
952 | ||||
|
953 | Python commands can be passed to the thread where they will be executed. | |||
|
954 | This is implemented by periodically checking for passed code using a | |||
|
955 | Qt timer / slot.""" | |||
|
956 | ||||
|
957 | TIMEOUT = 100 # Millisecond interval between timeouts. | |||
|
958 | ||||
|
959 | def __init__(self, argv=None, user_ns=None, user_global_ns=None, | |||
|
960 | debug=0, shell_class=MTInteractiveShell): | |||
|
961 | ||||
|
962 | import qt | |||
|
963 | ||||
|
964 | self.exec_loop = hijack_qt() | |||
|
965 | ||||
|
966 | # Allows us to use both Tk and QT. | |||
|
967 | self.tk = get_tk() | |||
|
968 | ||||
|
969 | self.IP = make_IPython(argv, | |||
|
970 | user_ns=user_ns, | |||
|
971 | user_global_ns=user_global_ns, | |||
|
972 | debug=debug, | |||
|
973 | shell_class=shell_class, | |||
|
974 | on_kill=[qt.qApp.exit]) | |||
|
975 | ||||
|
976 | # HACK: slot for banner in self; it will be passed to the mainloop | |||
|
977 | # method only and .run() needs it. The actual value will be set by | |||
|
978 | # .mainloop(). | |||
|
979 | self._banner = None | |||
|
980 | ||||
|
981 | threading.Thread.__init__(self) | |||
|
982 | ||||
|
983 | def mainloop(self, sys_exit=0, banner=None): | |||
|
984 | ||||
|
985 | import qt | |||
|
986 | ||||
|
987 | self._banner = banner | |||
|
988 | ||||
|
989 | if qt.QApplication.startingUp(): | |||
|
990 | a = qt.QApplication(sys.argv) | |||
|
991 | ||||
|
992 | self.timer = qt.QTimer() | |||
|
993 | qt.QObject.connect(self.timer, | |||
|
994 | qt.SIGNAL('timeout()'), | |||
|
995 | self.on_timer) | |||
|
996 | ||||
|
997 | self.start() | |||
|
998 | self.timer.start(self.TIMEOUT, True) | |||
|
999 | while True: | |||
|
1000 | if self.IP._kill: break | |||
|
1001 | self.exec_loop() | |||
|
1002 | self.join() | |||
|
1003 | ||||
|
1004 | def on_timer(self): | |||
|
1005 | update_tk(self.tk) | |||
|
1006 | result = self.IP.runcode() | |||
|
1007 | self.timer.start(self.TIMEOUT, True) | |||
|
1008 | return result | |||
|
1009 | ||||
|
1010 | ||||
|
1011 | class IPShellQt4(IPThread): | |||
|
1012 | """Run a Qt event loop in a separate thread. | |||
|
1013 | ||||
|
1014 | Python commands can be passed to the thread where they will be executed. | |||
|
1015 | This is implemented by periodically checking for passed code using a | |||
|
1016 | Qt timer / slot.""" | |||
|
1017 | ||||
|
1018 | TIMEOUT = 100 # Millisecond interval between timeouts. | |||
|
1019 | ||||
|
1020 | def __init__(self, argv=None, user_ns=None, user_global_ns=None, | |||
|
1021 | debug=0, shell_class=MTInteractiveShell): | |||
|
1022 | ||||
|
1023 | from PyQt4 import QtCore, QtGui | |||
|
1024 | ||||
|
1025 | try: | |||
|
1026 | # present in PyQt4-4.2.1 or later | |||
|
1027 | QtCore.pyqtRemoveInputHook() | |||
|
1028 | except AttributeError: | |||
|
1029 | pass | |||
|
1030 | ||||
|
1031 | if QtCore.PYQT_VERSION_STR == '4.3': | |||
|
1032 | warn('''PyQt4 version 4.3 detected. | |||
|
1033 | If you experience repeated threading warnings, please update PyQt4. | |||
|
1034 | ''') | |||
|
1035 | ||||
|
1036 | self.exec_ = hijack_qt4() | |||
|
1037 | ||||
|
1038 | # Allows us to use both Tk and QT. | |||
|
1039 | self.tk = get_tk() | |||
|
1040 | ||||
|
1041 | self.IP = make_IPython(argv, | |||
|
1042 | user_ns=user_ns, | |||
|
1043 | user_global_ns=user_global_ns, | |||
|
1044 | debug=debug, | |||
|
1045 | shell_class=shell_class, | |||
|
1046 | on_kill=[QtGui.qApp.exit]) | |||
|
1047 | ||||
|
1048 | # HACK: slot for banner in self; it will be passed to the mainloop | |||
|
1049 | # method only and .run() needs it. The actual value will be set by | |||
|
1050 | # .mainloop(). | |||
|
1051 | self._banner = None | |||
|
1052 | ||||
|
1053 | threading.Thread.__init__(self) | |||
|
1054 | ||||
|
1055 | def mainloop(self, sys_exit=0, banner=None): | |||
|
1056 | ||||
|
1057 | from PyQt4 import QtCore, QtGui | |||
|
1058 | ||||
|
1059 | self._banner = banner | |||
|
1060 | ||||
|
1061 | if QtGui.QApplication.startingUp(): | |||
|
1062 | a = QtGui.QApplication(sys.argv) | |||
|
1063 | ||||
|
1064 | self.timer = QtCore.QTimer() | |||
|
1065 | QtCore.QObject.connect(self.timer, | |||
|
1066 | QtCore.SIGNAL('timeout()'), | |||
|
1067 | self.on_timer) | |||
|
1068 | ||||
|
1069 | self.start() | |||
|
1070 | self.timer.start(self.TIMEOUT) | |||
|
1071 | while True: | |||
|
1072 | if self.IP._kill: break | |||
|
1073 | self.exec_() | |||
|
1074 | self.join() | |||
|
1075 | ||||
|
1076 | def on_timer(self): | |||
|
1077 | update_tk(self.tk) | |||
|
1078 | result = self.IP.runcode() | |||
|
1079 | self.timer.start(self.TIMEOUT) | |||
|
1080 | return result | |||
|
1081 | ||||
|
1082 | ||||
|
1083 | # A set of matplotlib public IPython shell classes, for single-threaded (Tk* | |||
|
1084 | # and FLTK*) and multithreaded (GTK*, WX* and Qt*) backends to use. | |||
|
1085 | def _load_pylab(user_ns): | |||
|
1086 | """Allow users to disable pulling all of pylab into the top-level | |||
|
1087 | namespace. | |||
|
1088 | ||||
|
1089 | This little utility must be called AFTER the actual ipython instance is | |||
|
1090 | running, since only then will the options file have been fully parsed.""" | |||
|
1091 | ||||
|
1092 | ip = ipapi.get() | |||
|
1093 | if ip.options.pylab_import_all: | |||
|
1094 | ip.ex("from matplotlib.pylab import *") | |||
|
1095 | ip.IP.user_config_ns.update(ip.user_ns) | |||
|
1096 | ||||
|
1097 | ||||
|
1098 | class IPShellMatplotlib(IPShell): | |||
|
1099 | """Subclass IPShell with MatplotlibShell as the internal shell. | |||
|
1100 | ||||
|
1101 | Single-threaded class, meant for the Tk* and FLTK* backends. | |||
|
1102 | ||||
|
1103 | Having this on a separate class simplifies the external driver code.""" | |||
|
1104 | ||||
|
1105 | def __init__(self,argv=None,user_ns=None,user_global_ns=None,debug=1): | |||
|
1106 | IPShell.__init__(self,argv,user_ns,user_global_ns,debug, | |||
|
1107 | shell_class=MatplotlibShell) | |||
|
1108 | _load_pylab(self.IP.user_ns) | |||
|
1109 | ||||
|
1110 | class IPShellMatplotlibGTK(IPShellGTK): | |||
|
1111 | """Subclass IPShellGTK with MatplotlibMTShell as the internal shell. | |||
|
1112 | ||||
|
1113 | Multi-threaded class, meant for the GTK* backends.""" | |||
|
1114 | ||||
|
1115 | def __init__(self,argv=None,user_ns=None,user_global_ns=None,debug=1): | |||
|
1116 | IPShellGTK.__init__(self,argv,user_ns,user_global_ns,debug, | |||
|
1117 | shell_class=MatplotlibMTShell) | |||
|
1118 | _load_pylab(self.IP.user_ns) | |||
|
1119 | ||||
|
1120 | class IPShellMatplotlibWX(IPShellWX): | |||
|
1121 | """Subclass IPShellWX with MatplotlibMTShell as the internal shell. | |||
|
1122 | ||||
|
1123 | Multi-threaded class, meant for the WX* backends.""" | |||
|
1124 | ||||
|
1125 | def __init__(self,argv=None,user_ns=None,user_global_ns=None,debug=1): | |||
|
1126 | IPShellWX.__init__(self,argv,user_ns,user_global_ns,debug, | |||
|
1127 | shell_class=MatplotlibMTShell) | |||
|
1128 | _load_pylab(self.IP.user_ns) | |||
|
1129 | ||||
|
1130 | class IPShellMatplotlibQt(IPShellQt): | |||
|
1131 | """Subclass IPShellQt with MatplotlibMTShell as the internal shell. | |||
|
1132 | ||||
|
1133 | Multi-threaded class, meant for the Qt* backends.""" | |||
|
1134 | ||||
|
1135 | def __init__(self,argv=None,user_ns=None,user_global_ns=None,debug=1): | |||
|
1136 | IPShellQt.__init__(self,argv,user_ns,user_global_ns,debug, | |||
|
1137 | shell_class=MatplotlibMTShell) | |||
|
1138 | _load_pylab(self.IP.user_ns) | |||
|
1139 | ||||
|
1140 | class IPShellMatplotlibQt4(IPShellQt4): | |||
|
1141 | """Subclass IPShellQt4 with MatplotlibMTShell as the internal shell. | |||
|
1142 | ||||
|
1143 | Multi-threaded class, meant for the Qt4* backends.""" | |||
|
1144 | ||||
|
1145 | def __init__(self,argv=None,user_ns=None,user_global_ns=None,debug=1): | |||
|
1146 | IPShellQt4.__init__(self,argv,user_ns,user_global_ns,debug, | |||
|
1147 | shell_class=MatplotlibMTShell) | |||
|
1148 | _load_pylab(self.IP.user_ns) | |||
|
1149 | ||||
|
1150 | #----------------------------------------------------------------------------- | |||
|
1151 | # Factory functions to actually start the proper thread-aware shell | |||
|
1152 | ||||
|
1153 | def _select_shell(argv): | |||
|
1154 | """Select a shell from the given argv vector. | |||
|
1155 | ||||
|
1156 | This function implements the threading selection policy, allowing runtime | |||
|
1157 | control of the threading mode, both for general users and for matplotlib. | |||
|
1158 | ||||
|
1159 | Return: | |||
|
1160 | Shell class to be instantiated for runtime operation. | |||
|
1161 | """ | |||
|
1162 | ||||
|
1163 | global USE_TK | |||
|
1164 | ||||
|
1165 | mpl_shell = {'gthread' : IPShellMatplotlibGTK, | |||
|
1166 | 'wthread' : IPShellMatplotlibWX, | |||
|
1167 | 'qthread' : IPShellMatplotlibQt, | |||
|
1168 | 'q4thread' : IPShellMatplotlibQt4, | |||
|
1169 | 'tkthread' : IPShellMatplotlib, # Tk is built-in | |||
|
1170 | } | |||
|
1171 | ||||
|
1172 | th_shell = {'gthread' : IPShellGTK, | |||
|
1173 | 'wthread' : IPShellWX, | |||
|
1174 | 'qthread' : IPShellQt, | |||
|
1175 | 'q4thread' : IPShellQt4, | |||
|
1176 | 'tkthread' : IPShell, # Tk is built-in | |||
|
1177 | } | |||
|
1178 | ||||
|
1179 | backends = {'gthread' : 'GTKAgg', | |||
|
1180 | 'wthread' : 'WXAgg', | |||
|
1181 | 'qthread' : 'QtAgg', | |||
|
1182 | 'q4thread' :'Qt4Agg', | |||
|
1183 | 'tkthread' :'TkAgg', | |||
|
1184 | } | |||
|
1185 | ||||
|
1186 | all_opts = set(['tk','pylab','gthread','qthread','q4thread','wthread', | |||
|
1187 | 'tkthread']) | |||
|
1188 | user_opts = set([s.replace('-','') for s in argv[:3]]) | |||
|
1189 | special_opts = user_opts & all_opts | |||
|
1190 | ||||
|
1191 | if 'tk' in special_opts: | |||
|
1192 | USE_TK = True | |||
|
1193 | special_opts.remove('tk') | |||
|
1194 | ||||
|
1195 | if 'pylab' in special_opts: | |||
|
1196 | ||||
|
1197 | try: | |||
|
1198 | import matplotlib | |||
|
1199 | except ImportError: | |||
|
1200 | error('matplotlib could NOT be imported! Starting normal IPython.') | |||
|
1201 | return IPShell | |||
|
1202 | ||||
|
1203 | special_opts.remove('pylab') | |||
|
1204 | # If there's any option left, it means the user wants to force the | |||
|
1205 | # threading backend, else it's auto-selected from the rc file | |||
|
1206 | if special_opts: | |||
|
1207 | th_mode = special_opts.pop() | |||
|
1208 | matplotlib.rcParams['backend'] = backends[th_mode] | |||
|
1209 | else: | |||
|
1210 | backend = matplotlib.rcParams['backend'] | |||
|
1211 | if backend.startswith('GTK'): | |||
|
1212 | th_mode = 'gthread' | |||
|
1213 | elif backend.startswith('WX'): | |||
|
1214 | th_mode = 'wthread' | |||
|
1215 | elif backend.startswith('Qt4'): | |||
|
1216 | th_mode = 'q4thread' | |||
|
1217 | elif backend.startswith('Qt'): | |||
|
1218 | th_mode = 'qthread' | |||
|
1219 | else: | |||
|
1220 | # Any other backend, use plain Tk | |||
|
1221 | th_mode = 'tkthread' | |||
|
1222 | ||||
|
1223 | return mpl_shell[th_mode] | |||
|
1224 | else: | |||
|
1225 | # No pylab requested, just plain threads | |||
|
1226 | try: | |||
|
1227 | th_mode = special_opts.pop() | |||
|
1228 | except KeyError: | |||
|
1229 | th_mode = 'tkthread' | |||
|
1230 | return th_shell[th_mode] | |||
|
1231 | ||||
|
1232 | ||||
|
1233 | # This is the one which should be called by external code. | |||
|
1234 | def start(user_ns = None): | |||
|
1235 | """Return a running shell instance, dealing with threading options. | |||
|
1236 | ||||
|
1237 | This is a factory function which will instantiate the proper IPython shell | |||
|
1238 | based on the user's threading choice. Such a selector is needed because | |||
|
1239 | different GUI toolkits require different thread handling details.""" | |||
|
1240 | ||||
|
1241 | shell = _select_shell(sys.argv) | |||
|
1242 | return shell(user_ns = user_ns) | |||
|
1243 | ||||
|
1244 | # Some aliases for backwards compatibility | |||
|
1245 | IPythonShell = IPShell | |||
|
1246 | IPythonShellEmbed = IPShellEmbed | |||
|
1247 | #************************ End of file <Shell.py> *************************** |
@@ -0,0 +1,71 b'' | |||||
|
1 | #!/usr/bin/env python | |||
|
2 | # encoding: utf-8 | |||
|
3 | ||||
|
4 | def test_import_completer(): | |||
|
5 | from IPython.core import completer | |||
|
6 | ||||
|
7 | def test_import_crashhandler(): | |||
|
8 | from IPython.core import crashhandler | |||
|
9 | ||||
|
10 | def test_import_debugger(): | |||
|
11 | from IPython.core import debugger | |||
|
12 | ||||
|
13 | def test_import_fakemodule(): | |||
|
14 | from IPython.core import fakemodule | |||
|
15 | ||||
|
16 | def test_import_excolors(): | |||
|
17 | from IPython.core import excolors | |||
|
18 | ||||
|
19 | def test_import_history(): | |||
|
20 | from IPython.core import history | |||
|
21 | ||||
|
22 | def test_import_hooks(): | |||
|
23 | from IPython.core import hooks | |||
|
24 | ||||
|
25 | def test_import_ipapi(): | |||
|
26 | from IPython.core import ipapi | |||
|
27 | ||||
|
28 | def test_import_iplib(): | |||
|
29 | from IPython.core import iplib | |||
|
30 | ||||
|
31 | def test_import_ipmaker(): | |||
|
32 | from IPython.core import ipmaker | |||
|
33 | ||||
|
34 | def test_import_logger(): | |||
|
35 | from IPython.core import logger | |||
|
36 | ||||
|
37 | def test_import_macro(): | |||
|
38 | from IPython.core import macro | |||
|
39 | ||||
|
40 | def test_import_magic(): | |||
|
41 | from IPython.core import magic | |||
|
42 | ||||
|
43 | def test_import_oinspect(): | |||
|
44 | from IPython.core import oinspect | |||
|
45 | ||||
|
46 | def test_import_outputtrap(): | |||
|
47 | from IPython.core import outputtrap | |||
|
48 | ||||
|
49 | def test_import_prefilter(): | |||
|
50 | from IPython.core import prefilter | |||
|
51 | ||||
|
52 | def test_import_prompts(): | |||
|
53 | from IPython.core import prompts | |||
|
54 | ||||
|
55 | def test_import_release(): | |||
|
56 | from IPython.core import release | |||
|
57 | ||||
|
58 | def test_import_shadowns(): | |||
|
59 | from IPython.core import shadowns | |||
|
60 | ||||
|
61 | def test_import_shell(): | |||
|
62 | from IPython.core import shell | |||
|
63 | ||||
|
64 | def test_import_shellglobals(): | |||
|
65 | from IPython.core import shellglobals | |||
|
66 | ||||
|
67 | def test_import_ultratb(): | |||
|
68 | from IPython.core import ultratb | |||
|
69 | ||||
|
70 | def test_import_usage(): | |||
|
71 | from IPython.core import usage |
1 | NO CONTENT: new file 100644 |
|
NO CONTENT: new file 100644 |
1 | NO CONTENT: new file 100644 |
|
NO CONTENT: new file 100644 |
1 | NO CONTENT: new file 100644 |
|
NO CONTENT: new file 100644 |
@@ -0,0 +1,14 b'' | |||||
|
1 | #!/usr/bin/env python | |||
|
2 | # encoding: utf-8 | |||
|
3 | ||||
|
4 | def test_import_backgroundjobs(): | |||
|
5 | from IPython.lib import backgroundjobs | |||
|
6 | ||||
|
7 | def test_import_deepreload(): | |||
|
8 | from IPython.lib import deepreload | |||
|
9 | ||||
|
10 | def test_import_demo(): | |||
|
11 | from IPython.lib import demo | |||
|
12 | ||||
|
13 | def test_import_irunner(): | |||
|
14 | from IPython.lib import demo |
1 | NO CONTENT: new file 100644 |
|
NO CONTENT: new file 100644 |
1 | NO CONTENT: new file 100644 |
|
NO CONTENT: new file 100644 |
1 | NO CONTENT: new file 100644 |
|
NO CONTENT: new file 100644 |
1 | NO CONTENT: new file 100644 |
|
NO CONTENT: new file 100644 |
1 | NO CONTENT: new file 100644 |
|
NO CONTENT: new file 100644 | ||
The requested commit or file is too big and content was truncated. Show full diff |
1 | NO CONTENT: new file 100644 |
|
NO CONTENT: new file 100644 | ||
The requested commit or file is too big and content was truncated. Show full diff |
1 | NO CONTENT: new file 100644 |
|
NO CONTENT: new file 100644 | ||
The requested commit or file is too big and content was truncated. Show full diff |
This diff has been collapsed as it changes many lines, (1251 lines changed) Show them Hide them | |||||
@@ -1,1246 +1,29 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | #!/usr/bin/env python | |
2 | """IPython Shell classes. |
|
2 | # encoding: utf-8 | |
|
3 | """ | |||
|
4 | A backwards compatibility layer for IPython.Shell. | |||
3 |
|
5 | |||
4 | All the matplotlib support code was co-developed with John Hunter, |
|
6 | Previously, IPython had an IPython.Shell module. IPython.Shell has been moved | |
5 | matplotlib's author. |
|
7 | to IPython.core.shell and is being refactored. This new module is provided | |
|
8 | for backwards compatability. We strongly encourage everyone to start using | |||
|
9 | the new code in IPython.core.shell. | |||
6 | """ |
|
10 | """ | |
7 |
|
11 | |||
8 | #***************************************************************************** |
|
12 | #----------------------------------------------------------------------------- | |
9 | # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu> |
|
13 | # Copyright (C) 2008-2009 The IPython Development Team | |
10 | # |
|
14 | # | |
11 | # Distributed under the terms of the BSD License. The full license is in |
|
15 | # Distributed under the terms of the BSD License. The full license is in | |
12 | # the file COPYING, distributed as part of this software. |
|
16 | # the file COPYING, distributed as part of this software. | |
13 | #***************************************************************************** |
|
|||
14 |
|
||||
15 | # Code begins |
|
|||
16 | # Stdlib imports |
|
|||
17 | import __builtin__ |
|
|||
18 | import __main__ |
|
|||
19 | import Queue |
|
|||
20 | import inspect |
|
|||
21 | import os |
|
|||
22 | import sys |
|
|||
23 | import thread |
|
|||
24 | import threading |
|
|||
25 | import time |
|
|||
26 |
|
||||
27 | from signal import signal, SIGINT |
|
|||
28 |
|
||||
29 | try: |
|
|||
30 | import ctypes |
|
|||
31 | HAS_CTYPES = True |
|
|||
32 | except ImportError: |
|
|||
33 | HAS_CTYPES = False |
|
|||
34 |
|
||||
35 | # IPython imports |
|
|||
36 | import IPython |
|
|||
37 | from IPython import ultraTB, ipapi |
|
|||
38 | from IPython.Magic import Magic |
|
|||
39 | from IPython.genutils import Term,warn,error,flag_calls, ask_yes_no |
|
|||
40 | from IPython.iplib import InteractiveShell |
|
|||
41 | from IPython.ipmaker import make_IPython |
|
|||
42 | from IPython.ipstruct import Struct |
|
|||
43 | from IPython.testing import decorators as testdec |
|
|||
44 |
|
||||
45 | # Globals |
|
|||
46 | # global flag to pass around information about Ctrl-C without exceptions |
|
|||
47 | KBINT = False |
|
|||
48 |
|
||||
49 | # global flag to turn on/off Tk support. |
|
|||
50 | USE_TK = False |
|
|||
51 |
|
||||
52 | # ID for the main thread, used for cross-thread exceptions |
|
|||
53 | MAIN_THREAD_ID = thread.get_ident() |
|
|||
54 |
|
||||
55 | # Tag when runcode() is active, for exception handling |
|
|||
56 | CODE_RUN = None |
|
|||
57 |
|
||||
58 | # Default timeout for waiting for multithreaded shells (in seconds) |
|
|||
59 | GUI_TIMEOUT = 10 |
|
|||
60 |
|
||||
61 | #----------------------------------------------------------------------------- |
|
|||
62 | # This class is trivial now, but I want to have it in to publish a clean |
|
|||
63 | # interface. Later when the internals are reorganized, code that uses this |
|
|||
64 | # shouldn't have to change. |
|
|||
65 |
|
||||
66 | class IPShell: |
|
|||
67 | """Create an IPython instance.""" |
|
|||
68 |
|
||||
69 | def __init__(self,argv=None,user_ns=None,user_global_ns=None, |
|
|||
70 | debug=1,shell_class=InteractiveShell): |
|
|||
71 | self.IP = make_IPython(argv,user_ns=user_ns, |
|
|||
72 | user_global_ns=user_global_ns, |
|
|||
73 | debug=debug,shell_class=shell_class) |
|
|||
74 |
|
||||
75 | def mainloop(self,sys_exit=0,banner=None): |
|
|||
76 | self.IP.mainloop(banner) |
|
|||
77 | if sys_exit: |
|
|||
78 | sys.exit() |
|
|||
79 |
|
||||
80 | #----------------------------------------------------------------------------- |
|
|||
81 | def kill_embedded(self,parameter_s=''): |
|
|||
82 | """%kill_embedded : deactivate for good the current embedded IPython. |
|
|||
83 |
|
||||
84 | This function (after asking for confirmation) sets an internal flag so that |
|
|||
85 | an embedded IPython will never activate again. This is useful to |
|
|||
86 | permanently disable a shell that is being called inside a loop: once you've |
|
|||
87 | figured out what you needed from it, you may then kill it and the program |
|
|||
88 | will then continue to run without the interactive shell interfering again. |
|
|||
89 | """ |
|
|||
90 |
|
||||
91 | kill = ask_yes_no("Are you sure you want to kill this embedded instance " |
|
|||
92 | "(y/n)? [y/N] ",'n') |
|
|||
93 | if kill: |
|
|||
94 | self.shell.embedded_active = False |
|
|||
95 | print "This embedded IPython will not reactivate anymore once you exit." |
|
|||
96 |
|
||||
97 | class IPShellEmbed: |
|
|||
98 | """Allow embedding an IPython shell into a running program. |
|
|||
99 |
|
||||
100 | Instances of this class are callable, with the __call__ method being an |
|
|||
101 | alias to the embed() method of an InteractiveShell instance. |
|
|||
102 |
|
||||
103 | Usage (see also the example-embed.py file for a running example): |
|
|||
104 |
|
||||
105 | ipshell = IPShellEmbed([argv,banner,exit_msg,rc_override]) |
|
|||
106 |
|
||||
107 | - argv: list containing valid command-line options for IPython, as they |
|
|||
108 | would appear in sys.argv[1:]. |
|
|||
109 |
|
||||
110 | For example, the following command-line options: |
|
|||
111 |
|
||||
112 | $ ipython -prompt_in1 'Input <\\#>' -colors LightBG |
|
|||
113 |
|
||||
114 | would be passed in the argv list as: |
|
|||
115 |
|
||||
116 | ['-prompt_in1','Input <\\#>','-colors','LightBG'] |
|
|||
117 |
|
||||
118 | - banner: string which gets printed every time the interpreter starts. |
|
|||
119 |
|
||||
120 | - exit_msg: string which gets printed every time the interpreter exits. |
|
|||
121 |
|
||||
122 | - rc_override: a dict or Struct of configuration options such as those |
|
|||
123 | used by IPython. These options are read from your ~/.ipython/ipythonrc |
|
|||
124 | file when the Shell object is created. Passing an explicit rc_override |
|
|||
125 | dict with any options you want allows you to override those values at |
|
|||
126 | creation time without having to modify the file. This way you can create |
|
|||
127 | embeddable instances configured in any way you want without editing any |
|
|||
128 | global files (thus keeping your interactive IPython configuration |
|
|||
129 | unchanged). |
|
|||
130 |
|
||||
131 | Then the ipshell instance can be called anywhere inside your code: |
|
|||
132 |
|
||||
133 | ipshell(header='') -> Opens up an IPython shell. |
|
|||
134 |
|
||||
135 | - header: string printed by the IPython shell upon startup. This can let |
|
|||
136 | you know where in your code you are when dropping into the shell. Note |
|
|||
137 | that 'banner' gets prepended to all calls, so header is used for |
|
|||
138 | location-specific information. |
|
|||
139 |
|
||||
140 | For more details, see the __call__ method below. |
|
|||
141 |
|
||||
142 | When the IPython shell is exited with Ctrl-D, normal program execution |
|
|||
143 | resumes. |
|
|||
144 |
|
||||
145 | This functionality was inspired by a posting on comp.lang.python by cmkl |
|
|||
146 | <cmkleffner@gmx.de> on Dec. 06/01 concerning similar uses of pyrepl, and |
|
|||
147 | by the IDL stop/continue commands.""" |
|
|||
148 |
|
||||
149 | def __init__(self,argv=None,banner='',exit_msg=None,rc_override=None, |
|
|||
150 | user_ns=None): |
|
|||
151 | """Note that argv here is a string, NOT a list.""" |
|
|||
152 | self.set_banner(banner) |
|
|||
153 | self.set_exit_msg(exit_msg) |
|
|||
154 | self.set_dummy_mode(0) |
|
|||
155 |
|
||||
156 | # sys.displayhook is a global, we need to save the user's original |
|
|||
157 | # Don't rely on __displayhook__, as the user may have changed that. |
|
|||
158 | self.sys_displayhook_ori = sys.displayhook |
|
|||
159 |
|
||||
160 | # save readline completer status |
|
|||
161 | try: |
|
|||
162 | #print 'Save completer',sys.ipcompleter # dbg |
|
|||
163 | self.sys_ipcompleter_ori = sys.ipcompleter |
|
|||
164 | except: |
|
|||
165 | pass # not nested with IPython |
|
|||
166 |
|
||||
167 | self.IP = make_IPython(argv,rc_override=rc_override, |
|
|||
168 | embedded=True, |
|
|||
169 | user_ns=user_ns) |
|
|||
170 |
|
||||
171 | ip = ipapi.IPApi(self.IP) |
|
|||
172 | ip.expose_magic("kill_embedded",kill_embedded) |
|
|||
173 |
|
||||
174 | # copy our own displayhook also |
|
|||
175 | self.sys_displayhook_embed = sys.displayhook |
|
|||
176 | # and leave the system's display hook clean |
|
|||
177 | sys.displayhook = self.sys_displayhook_ori |
|
|||
178 | # don't use the ipython crash handler so that user exceptions aren't |
|
|||
179 | # trapped |
|
|||
180 | sys.excepthook = ultraTB.FormattedTB(color_scheme = self.IP.rc.colors, |
|
|||
181 | mode = self.IP.rc.xmode, |
|
|||
182 | call_pdb = self.IP.rc.pdb) |
|
|||
183 | self.restore_system_completer() |
|
|||
184 |
|
||||
185 | def restore_system_completer(self): |
|
|||
186 | """Restores the readline completer which was in place. |
|
|||
187 |
|
||||
188 | This allows embedded IPython within IPython not to disrupt the |
|
|||
189 | parent's completion. |
|
|||
190 | """ |
|
|||
191 |
|
||||
192 | try: |
|
|||
193 | self.IP.readline.set_completer(self.sys_ipcompleter_ori) |
|
|||
194 | sys.ipcompleter = self.sys_ipcompleter_ori |
|
|||
195 | except: |
|
|||
196 | pass |
|
|||
197 |
|
||||
198 | def __call__(self,header='',local_ns=None,global_ns=None,dummy=None): |
|
|||
199 | """Activate the interactive interpreter. |
|
|||
200 |
|
||||
201 | __call__(self,header='',local_ns=None,global_ns,dummy=None) -> Start |
|
|||
202 | the interpreter shell with the given local and global namespaces, and |
|
|||
203 | optionally print a header string at startup. |
|
|||
204 |
|
||||
205 | The shell can be globally activated/deactivated using the |
|
|||
206 | set/get_dummy_mode methods. This allows you to turn off a shell used |
|
|||
207 | for debugging globally. |
|
|||
208 |
|
||||
209 | However, *each* time you call the shell you can override the current |
|
|||
210 | state of dummy_mode with the optional keyword parameter 'dummy'. For |
|
|||
211 | example, if you set dummy mode on with IPShell.set_dummy_mode(1), you |
|
|||
212 | can still have a specific call work by making it as IPShell(dummy=0). |
|
|||
213 |
|
||||
214 | The optional keyword parameter dummy controls whether the call |
|
|||
215 | actually does anything. """ |
|
|||
216 |
|
||||
217 | # If the user has turned it off, go away |
|
|||
218 | if not self.IP.embedded_active: |
|
|||
219 | return |
|
|||
220 |
|
||||
221 | # Normal exits from interactive mode set this flag, so the shell can't |
|
|||
222 | # re-enter (it checks this variable at the start of interactive mode). |
|
|||
223 | self.IP.exit_now = False |
|
|||
224 |
|
||||
225 | # Allow the dummy parameter to override the global __dummy_mode |
|
|||
226 | if dummy or (dummy != 0 and self.__dummy_mode): |
|
|||
227 | return |
|
|||
228 |
|
||||
229 | # Set global subsystems (display,completions) to our values |
|
|||
230 | sys.displayhook = self.sys_displayhook_embed |
|
|||
231 | if self.IP.has_readline: |
|
|||
232 | self.IP.set_completer() |
|
|||
233 |
|
||||
234 | if self.banner and header: |
|
|||
235 | format = '%s\n%s\n' |
|
|||
236 | else: |
|
|||
237 | format = '%s%s\n' |
|
|||
238 | banner = format % (self.banner,header) |
|
|||
239 |
|
||||
240 | # Call the embedding code with a stack depth of 1 so it can skip over |
|
|||
241 | # our call and get the original caller's namespaces. |
|
|||
242 | self.IP.embed_mainloop(banner,local_ns,global_ns,stack_depth=1) |
|
|||
243 |
|
||||
244 | if self.exit_msg: |
|
|||
245 | print self.exit_msg |
|
|||
246 |
|
||||
247 | # Restore global systems (display, completion) |
|
|||
248 | sys.displayhook = self.sys_displayhook_ori |
|
|||
249 | self.restore_system_completer() |
|
|||
250 |
|
||||
251 | def set_dummy_mode(self,dummy): |
|
|||
252 | """Sets the embeddable shell's dummy mode parameter. |
|
|||
253 |
|
||||
254 | set_dummy_mode(dummy): dummy = 0 or 1. |
|
|||
255 |
|
||||
256 | This parameter is persistent and makes calls to the embeddable shell |
|
|||
257 | silently return without performing any action. This allows you to |
|
|||
258 | globally activate or deactivate a shell you're using with a single call. |
|
|||
259 |
|
||||
260 | If you need to manually""" |
|
|||
261 |
|
||||
262 | if dummy not in [0,1,False,True]: |
|
|||
263 | raise ValueError,'dummy parameter must be boolean' |
|
|||
264 | self.__dummy_mode = dummy |
|
|||
265 |
|
||||
266 | def get_dummy_mode(self): |
|
|||
267 | """Return the current value of the dummy mode parameter. |
|
|||
268 | """ |
|
|||
269 | return self.__dummy_mode |
|
|||
270 |
|
||||
271 | def set_banner(self,banner): |
|
|||
272 | """Sets the global banner. |
|
|||
273 |
|
||||
274 | This banner gets prepended to every header printed when the shell |
|
|||
275 | instance is called.""" |
|
|||
276 |
|
||||
277 | self.banner = banner |
|
|||
278 |
|
||||
279 | def set_exit_msg(self,exit_msg): |
|
|||
280 | """Sets the global exit_msg. |
|
|||
281 |
|
||||
282 | This exit message gets printed upon exiting every time the embedded |
|
|||
283 | shell is called. It is None by default. """ |
|
|||
284 |
|
||||
285 | self.exit_msg = exit_msg |
|
|||
286 |
|
||||
287 | #----------------------------------------------------------------------------- |
|
|||
288 | if HAS_CTYPES: |
|
|||
289 | # Add async exception support. Trick taken from: |
|
|||
290 | # http://sebulba.wikispaces.com/recipe+thread2 |
|
|||
291 | def _async_raise(tid, exctype): |
|
|||
292 | """raises the exception, performs cleanup if needed""" |
|
|||
293 | if not inspect.isclass(exctype): |
|
|||
294 | raise TypeError("Only types can be raised (not instances)") |
|
|||
295 | # Explicit cast to c_long is necessary for 64-bit support: |
|
|||
296 | # See https://bugs.launchpad.net/ipython/+bug/237073 |
|
|||
297 | res = ctypes.pythonapi.PyThreadState_SetAsyncExc(ctypes.c_long(tid), |
|
|||
298 | ctypes.py_object(exctype)) |
|
|||
299 | if res == 0: |
|
|||
300 | raise ValueError("invalid thread id") |
|
|||
301 | elif res != 1: |
|
|||
302 | # If it returns a number greater than one, you're in trouble, |
|
|||
303 | # and you should call it again with exc=NULL to revert the effect |
|
|||
304 | ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, 0) |
|
|||
305 | raise SystemError("PyThreadState_SetAsyncExc failed") |
|
|||
306 |
|
||||
307 | def sigint_handler(signum,stack_frame): |
|
|||
308 | """Sigint handler for threaded apps. |
|
|||
309 |
|
||||
310 | This is a horrible hack to pass information about SIGINT _without_ |
|
|||
311 | using exceptions, since I haven't been able to properly manage |
|
|||
312 | cross-thread exceptions in GTK/WX. In fact, I don't think it can be |
|
|||
313 | done (or at least that's my understanding from a c.l.py thread where |
|
|||
314 | this was discussed).""" |
|
|||
315 |
|
||||
316 | global KBINT |
|
|||
317 |
|
||||
318 | if CODE_RUN: |
|
|||
319 | _async_raise(MAIN_THREAD_ID,KeyboardInterrupt) |
|
|||
320 | else: |
|
|||
321 | KBINT = True |
|
|||
322 | print '\nKeyboardInterrupt - Press <Enter> to continue.', |
|
|||
323 | Term.cout.flush() |
|
|||
324 |
|
||||
325 | else: |
|
|||
326 | def sigint_handler(signum,stack_frame): |
|
|||
327 | """Sigint handler for threaded apps. |
|
|||
328 |
|
||||
329 | This is a horrible hack to pass information about SIGINT _without_ |
|
|||
330 | using exceptions, since I haven't been able to properly manage |
|
|||
331 | cross-thread exceptions in GTK/WX. In fact, I don't think it can be |
|
|||
332 | done (or at least that's my understanding from a c.l.py thread where |
|
|||
333 | this was discussed).""" |
|
|||
334 |
|
||||
335 | global KBINT |
|
|||
336 |
|
||||
337 | print '\nKeyboardInterrupt - Press <Enter> to continue.', |
|
|||
338 | Term.cout.flush() |
|
|||
339 | # Set global flag so that runsource can know that Ctrl-C was hit |
|
|||
340 | KBINT = True |
|
|||
341 |
|
||||
342 |
|
||||
343 | class MTInteractiveShell(InteractiveShell): |
|
|||
344 | """Simple multi-threaded shell.""" |
|
|||
345 |
|
||||
346 | # Threading strategy taken from: |
|
|||
347 | # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65109, by Brian |
|
|||
348 | # McErlean and John Finlay. Modified with corrections by Antoon Pardon, |
|
|||
349 | # from the pygtk mailing list, to avoid lockups with system calls. |
|
|||
350 |
|
||||
351 | # class attribute to indicate whether the class supports threads or not. |
|
|||
352 | # Subclasses with thread support should override this as needed. |
|
|||
353 | isthreaded = True |
|
|||
354 |
|
||||
355 | def __init__(self,name,usage=None,rc=Struct(opts=None,args=None), |
|
|||
356 | user_ns=None,user_global_ns=None,banner2='', |
|
|||
357 | gui_timeout=GUI_TIMEOUT,**kw): |
|
|||
358 | """Similar to the normal InteractiveShell, but with threading control""" |
|
|||
359 |
|
||||
360 | InteractiveShell.__init__(self,name,usage,rc,user_ns, |
|
|||
361 | user_global_ns,banner2) |
|
|||
362 |
|
||||
363 | # Timeout we wait for GUI thread |
|
|||
364 | self.gui_timeout = gui_timeout |
|
|||
365 |
|
||||
366 | # A queue to hold the code to be executed. |
|
|||
367 | self.code_queue = Queue.Queue() |
|
|||
368 |
|
||||
369 | # Stuff to do at closing time |
|
|||
370 | self._kill = None |
|
|||
371 | on_kill = kw.get('on_kill', []) |
|
|||
372 | # Check that all things to kill are callable: |
|
|||
373 | for t in on_kill: |
|
|||
374 | if not callable(t): |
|
|||
375 | raise TypeError,'on_kill must be a list of callables' |
|
|||
376 | self.on_kill = on_kill |
|
|||
377 | # thread identity of the "worker thread" (that may execute code directly) |
|
|||
378 | self.worker_ident = None |
|
|||
379 |
|
||||
380 | def runsource(self, source, filename="<input>", symbol="single"): |
|
|||
381 | """Compile and run some source in the interpreter. |
|
|||
382 |
|
||||
383 | Modified version of code.py's runsource(), to handle threading issues. |
|
|||
384 | See the original for full docstring details.""" |
|
|||
385 |
|
||||
386 | global KBINT |
|
|||
387 |
|
||||
388 | # If Ctrl-C was typed, we reset the flag and return right away |
|
|||
389 | if KBINT: |
|
|||
390 | KBINT = False |
|
|||
391 | return False |
|
|||
392 |
|
||||
393 | if self._kill: |
|
|||
394 | # can't queue new code if we are being killed |
|
|||
395 | return True |
|
|||
396 |
|
||||
397 | try: |
|
|||
398 | code = self.compile(source, filename, symbol) |
|
|||
399 | except (OverflowError, SyntaxError, ValueError): |
|
|||
400 | # Case 1 |
|
|||
401 | self.showsyntaxerror(filename) |
|
|||
402 | return False |
|
|||
403 |
|
||||
404 | if code is None: |
|
|||
405 | # Case 2 |
|
|||
406 | return True |
|
|||
407 |
|
||||
408 | # shortcut - if we are in worker thread, or the worker thread is not |
|
|||
409 | # running, execute directly (to allow recursion and prevent deadlock if |
|
|||
410 | # code is run early in IPython construction) |
|
|||
411 |
|
||||
412 | if (self.worker_ident is None |
|
|||
413 | or self.worker_ident == thread.get_ident() ): |
|
|||
414 | InteractiveShell.runcode(self,code) |
|
|||
415 | return False |
|
|||
416 |
|
||||
417 | # Case 3 |
|
|||
418 | # Store code in queue, so the execution thread can handle it. |
|
|||
419 |
|
||||
420 | completed_ev, received_ev = threading.Event(), threading.Event() |
|
|||
421 |
|
||||
422 | self.code_queue.put((code,completed_ev, received_ev)) |
|
|||
423 | # first make sure the message was received, with timeout |
|
|||
424 | received_ev.wait(self.gui_timeout) |
|
|||
425 | if not received_ev.isSet(): |
|
|||
426 | # the mainloop is dead, start executing code directly |
|
|||
427 | print "Warning: Timeout for mainloop thread exceeded" |
|
|||
428 | print "switching to nonthreaded mode (until mainloop wakes up again)" |
|
|||
429 | self.worker_ident = None |
|
|||
430 | else: |
|
|||
431 | completed_ev.wait() |
|
|||
432 | return False |
|
|||
433 |
|
||||
434 | def runcode(self): |
|
|||
435 | """Execute a code object. |
|
|||
436 |
|
||||
437 | Multithreaded wrapper around IPython's runcode().""" |
|
|||
438 |
|
||||
439 | global CODE_RUN |
|
|||
440 |
|
||||
441 | # we are in worker thread, stash out the id for runsource() |
|
|||
442 | self.worker_ident = thread.get_ident() |
|
|||
443 |
|
||||
444 | if self._kill: |
|
|||
445 | print >>Term.cout, 'Closing threads...', |
|
|||
446 | Term.cout.flush() |
|
|||
447 | for tokill in self.on_kill: |
|
|||
448 | tokill() |
|
|||
449 | print >>Term.cout, 'Done.' |
|
|||
450 | # allow kill() to return |
|
|||
451 | self._kill.set() |
|
|||
452 | return True |
|
|||
453 |
|
||||
454 | # Install sigint handler. We do it every time to ensure that if user |
|
|||
455 | # code modifies it, we restore our own handling. |
|
|||
456 | try: |
|
|||
457 | signal(SIGINT,sigint_handler) |
|
|||
458 | except SystemError: |
|
|||
459 | # This happens under Windows, which seems to have all sorts |
|
|||
460 | # of problems with signal handling. Oh well... |
|
|||
461 | pass |
|
|||
462 |
|
||||
463 | # Flush queue of pending code by calling the run methood of the parent |
|
|||
464 | # class with all items which may be in the queue. |
|
|||
465 | code_to_run = None |
|
|||
466 | while 1: |
|
|||
467 | try: |
|
|||
468 | code_to_run, completed_ev, received_ev = self.code_queue.get_nowait() |
|
|||
469 | except Queue.Empty: |
|
|||
470 | break |
|
|||
471 | received_ev.set() |
|
|||
472 |
|
||||
473 | # Exceptions need to be raised differently depending on which |
|
|||
474 | # thread is active. This convoluted try/except is only there to |
|
|||
475 | # protect against asynchronous exceptions, to ensure that a KBINT |
|
|||
476 | # at the wrong time doesn't deadlock everything. The global |
|
|||
477 | # CODE_TO_RUN is set to true/false as close as possible to the |
|
|||
478 | # runcode() call, so that the KBINT handler is correctly informed. |
|
|||
479 | try: |
|
|||
480 | try: |
|
|||
481 | CODE_RUN = True |
|
|||
482 | InteractiveShell.runcode(self,code_to_run) |
|
|||
483 | except KeyboardInterrupt: |
|
|||
484 | print "Keyboard interrupted in mainloop" |
|
|||
485 | while not self.code_queue.empty(): |
|
|||
486 | code, ev1,ev2 = self.code_queue.get_nowait() |
|
|||
487 | ev1.set() |
|
|||
488 | ev2.set() |
|
|||
489 | break |
|
|||
490 | finally: |
|
|||
491 | CODE_RUN = False |
|
|||
492 | # allow runsource() return from wait |
|
|||
493 | completed_ev.set() |
|
|||
494 |
|
||||
495 |
|
||||
496 | # This MUST return true for gtk threading to work |
|
|||
497 | return True |
|
|||
498 |
|
||||
499 | def kill(self): |
|
|||
500 | """Kill the thread, returning when it has been shut down.""" |
|
|||
501 | self._kill = threading.Event() |
|
|||
502 | self._kill.wait() |
|
|||
503 |
|
||||
504 | class MatplotlibShellBase: |
|
|||
505 | """Mixin class to provide the necessary modifications to regular IPython |
|
|||
506 | shell classes for matplotlib support. |
|
|||
507 |
|
||||
508 | Given Python's MRO, this should be used as the FIRST class in the |
|
|||
509 | inheritance hierarchy, so that it overrides the relevant methods.""" |
|
|||
510 |
|
||||
511 | def _matplotlib_config(self,name,user_ns,user_global_ns=None): |
|
|||
512 | """Return items needed to setup the user's shell with matplotlib""" |
|
|||
513 |
|
||||
514 | # Initialize matplotlib to interactive mode always |
|
|||
515 | import matplotlib |
|
|||
516 | from matplotlib import backends |
|
|||
517 | matplotlib.interactive(True) |
|
|||
518 |
|
||||
519 | def use(arg): |
|
|||
520 | """IPython wrapper for matplotlib's backend switcher. |
|
|||
521 |
|
||||
522 | In interactive use, we can not allow switching to a different |
|
|||
523 | interactive backend, since thread conflicts will most likely crash |
|
|||
524 | the python interpreter. This routine does a safety check first, |
|
|||
525 | and refuses to perform a dangerous switch. It still allows |
|
|||
526 | switching to non-interactive backends.""" |
|
|||
527 |
|
||||
528 | if arg in backends.interactive_bk and arg != self.mpl_backend: |
|
|||
529 | m=('invalid matplotlib backend switch.\n' |
|
|||
530 | 'This script attempted to switch to the interactive ' |
|
|||
531 | 'backend: `%s`\n' |
|
|||
532 | 'Your current choice of interactive backend is: `%s`\n\n' |
|
|||
533 | 'Switching interactive matplotlib backends at runtime\n' |
|
|||
534 | 'would crash the python interpreter, ' |
|
|||
535 | 'and IPython has blocked it.\n\n' |
|
|||
536 | 'You need to either change your choice of matplotlib backend\n' |
|
|||
537 | 'by editing your .matplotlibrc file, or run this script as a \n' |
|
|||
538 | 'standalone file from the command line, not using IPython.\n' % |
|
|||
539 | (arg,self.mpl_backend) ) |
|
|||
540 | raise RuntimeError, m |
|
|||
541 | else: |
|
|||
542 | self.mpl_use(arg) |
|
|||
543 | self.mpl_use._called = True |
|
|||
544 |
|
||||
545 | self.matplotlib = matplotlib |
|
|||
546 | self.mpl_backend = matplotlib.rcParams['backend'] |
|
|||
547 |
|
||||
548 | # we also need to block switching of interactive backends by use() |
|
|||
549 | self.mpl_use = matplotlib.use |
|
|||
550 | self.mpl_use._called = False |
|
|||
551 | # overwrite the original matplotlib.use with our wrapper |
|
|||
552 | matplotlib.use = use |
|
|||
553 |
|
||||
554 | # This must be imported last in the matplotlib series, after |
|
|||
555 | # backend/interactivity choices have been made |
|
|||
556 | import matplotlib.pylab as pylab |
|
|||
557 | self.pylab = pylab |
|
|||
558 |
|
||||
559 | self.pylab.show._needmain = False |
|
|||
560 | # We need to detect at runtime whether show() is called by the user. |
|
|||
561 | # For this, we wrap it into a decorator which adds a 'called' flag. |
|
|||
562 | self.pylab.draw_if_interactive = flag_calls(self.pylab.draw_if_interactive) |
|
|||
563 |
|
||||
564 | # Build a user namespace initialized with matplotlib/matlab features. |
|
|||
565 | user_ns, user_global_ns = IPython.ipapi.make_user_namespaces(user_ns, |
|
|||
566 | user_global_ns) |
|
|||
567 |
|
||||
568 | # Import numpy as np/pyplot as plt are conventions we're trying to |
|
|||
569 | # somewhat standardize on. Making them available to users by default |
|
|||
570 | # will greatly help this. |
|
|||
571 | exec ("import numpy\n" |
|
|||
572 | "import numpy as np\n" |
|
|||
573 | "import matplotlib\n" |
|
|||
574 | "import matplotlib.pylab as pylab\n" |
|
|||
575 | "try:\n" |
|
|||
576 | " import matplotlib.pyplot as plt\n" |
|
|||
577 | "except ImportError:\n" |
|
|||
578 | " pass\n" |
|
|||
579 | ) in user_ns |
|
|||
580 |
|
||||
581 | # Build matplotlib info banner |
|
|||
582 | b=""" |
|
|||
583 | Welcome to pylab, a matplotlib-based Python environment. |
|
|||
584 | For more information, type 'help(pylab)'. |
|
|||
585 | """ |
|
|||
586 | return user_ns,user_global_ns,b |
|
|||
587 |
|
||||
588 | def mplot_exec(self,fname,*where,**kw): |
|
|||
589 | """Execute a matplotlib script. |
|
|||
590 |
|
||||
591 | This is a call to execfile(), but wrapped in safeties to properly |
|
|||
592 | handle interactive rendering and backend switching.""" |
|
|||
593 |
|
||||
594 | #print '*** Matplotlib runner ***' # dbg |
|
|||
595 | # turn off rendering until end of script |
|
|||
596 | isInteractive = self.matplotlib.rcParams['interactive'] |
|
|||
597 | self.matplotlib.interactive(False) |
|
|||
598 | self.safe_execfile(fname,*where,**kw) |
|
|||
599 | self.matplotlib.interactive(isInteractive) |
|
|||
600 | # make rendering call now, if the user tried to do it |
|
|||
601 | if self.pylab.draw_if_interactive.called: |
|
|||
602 | self.pylab.draw() |
|
|||
603 | self.pylab.draw_if_interactive.called = False |
|
|||
604 |
|
||||
605 | # if a backend switch was performed, reverse it now |
|
|||
606 | if self.mpl_use._called: |
|
|||
607 | self.matplotlib.rcParams['backend'] = self.mpl_backend |
|
|||
608 |
|
||||
609 | @testdec.skip_doctest |
|
|||
610 | def magic_run(self,parameter_s=''): |
|
|||
611 | Magic.magic_run(self,parameter_s,runner=self.mplot_exec) |
|
|||
612 |
|
||||
613 | # Fix the docstring so users see the original as well |
|
|||
614 | magic_run.__doc__ = "%s\n%s" % (Magic.magic_run.__doc__, |
|
|||
615 | "\n *** Modified %run for Matplotlib," |
|
|||
616 | " with proper interactive handling ***") |
|
|||
617 |
|
||||
618 | # Now we provide 2 versions of a matplotlib-aware IPython base shells, single |
|
|||
619 | # and multithreaded. Note that these are meant for internal use, the IPShell* |
|
|||
620 | # classes below are the ones meant for public consumption. |
|
|||
621 |
|
||||
622 | class MatplotlibShell(MatplotlibShellBase,InteractiveShell): |
|
|||
623 | """Single-threaded shell with matplotlib support.""" |
|
|||
624 |
|
||||
625 | def __init__(self,name,usage=None,rc=Struct(opts=None,args=None), |
|
|||
626 | user_ns=None,user_global_ns=None,**kw): |
|
|||
627 | user_ns,user_global_ns,b2 = self._matplotlib_config(name,user_ns,user_global_ns) |
|
|||
628 | InteractiveShell.__init__(self,name,usage,rc,user_ns,user_global_ns, |
|
|||
629 | banner2=b2,**kw) |
|
|||
630 |
|
||||
631 | class MatplotlibMTShell(MatplotlibShellBase,MTInteractiveShell): |
|
|||
632 | """Multi-threaded shell with matplotlib support.""" |
|
|||
633 |
|
||||
634 | def __init__(self,name,usage=None,rc=Struct(opts=None,args=None), |
|
|||
635 | user_ns=None,user_global_ns=None, **kw): |
|
|||
636 | user_ns,user_global_ns,b2 = self._matplotlib_config(name,user_ns,user_global_ns) |
|
|||
637 | MTInteractiveShell.__init__(self,name,usage,rc,user_ns,user_global_ns, |
|
|||
638 | banner2=b2,**kw) |
|
|||
639 |
|
||||
640 | #----------------------------------------------------------------------------- |
|
|||
641 | # Utility functions for the different GUI enabled IPShell* classes. |
|
|||
642 |
|
||||
643 | def get_tk(): |
|
|||
644 | """Tries to import Tkinter and returns a withdrawn Tkinter root |
|
|||
645 | window. If Tkinter is already imported or not available, this |
|
|||
646 | returns None. This function calls `hijack_tk` underneath. |
|
|||
647 | """ |
|
|||
648 | if not USE_TK or sys.modules.has_key('Tkinter'): |
|
|||
649 | return None |
|
|||
650 | else: |
|
|||
651 | try: |
|
|||
652 | import Tkinter |
|
|||
653 | except ImportError: |
|
|||
654 | return None |
|
|||
655 | else: |
|
|||
656 | hijack_tk() |
|
|||
657 | r = Tkinter.Tk() |
|
|||
658 | r.withdraw() |
|
|||
659 | return r |
|
|||
660 |
|
||||
661 | def hijack_tk(): |
|
|||
662 | """Modifies Tkinter's mainloop with a dummy so when a module calls |
|
|||
663 | mainloop, it does not block. |
|
|||
664 |
|
||||
665 | """ |
|
|||
666 | def misc_mainloop(self, n=0): |
|
|||
667 | pass |
|
|||
668 | def tkinter_mainloop(n=0): |
|
|||
669 | pass |
|
|||
670 |
|
||||
671 | import Tkinter |
|
|||
672 | Tkinter.Misc.mainloop = misc_mainloop |
|
|||
673 | Tkinter.mainloop = tkinter_mainloop |
|
|||
674 |
|
||||
675 | def update_tk(tk): |
|
|||
676 | """Updates the Tkinter event loop. This is typically called from |
|
|||
677 | the respective WX or GTK mainloops. |
|
|||
678 | """ |
|
|||
679 | if tk: |
|
|||
680 | tk.update() |
|
|||
681 |
|
||||
682 | def hijack_wx(): |
|
|||
683 | """Modifies wxPython's MainLoop with a dummy so user code does not |
|
|||
684 | block IPython. The hijacked mainloop function is returned. |
|
|||
685 | """ |
|
|||
686 | def dummy_mainloop(*args, **kw): |
|
|||
687 | pass |
|
|||
688 |
|
||||
689 | try: |
|
|||
690 | import wx |
|
|||
691 | except ImportError: |
|
|||
692 | # For very old versions of WX |
|
|||
693 | import wxPython as wx |
|
|||
694 |
|
||||
695 | ver = wx.__version__ |
|
|||
696 | orig_mainloop = None |
|
|||
697 | if ver[:3] >= '2.5': |
|
|||
698 | import wx |
|
|||
699 | if hasattr(wx, '_core_'): core = getattr(wx, '_core_') |
|
|||
700 | elif hasattr(wx, '_core'): core = getattr(wx, '_core') |
|
|||
701 | else: raise AttributeError('Could not find wx core module') |
|
|||
702 | orig_mainloop = core.PyApp_MainLoop |
|
|||
703 | core.PyApp_MainLoop = dummy_mainloop |
|
|||
704 | elif ver[:3] == '2.4': |
|
|||
705 | orig_mainloop = wx.wxc.wxPyApp_MainLoop |
|
|||
706 | wx.wxc.wxPyApp_MainLoop = dummy_mainloop |
|
|||
707 | else: |
|
|||
708 | warn("Unable to find either wxPython version 2.4 or >= 2.5.") |
|
|||
709 | return orig_mainloop |
|
|||
710 |
|
||||
711 | def hijack_gtk(): |
|
|||
712 | """Modifies pyGTK's mainloop with a dummy so user code does not |
|
|||
713 | block IPython. This function returns the original `gtk.mainloop` |
|
|||
714 | function that has been hijacked. |
|
|||
715 | """ |
|
|||
716 | def dummy_mainloop(*args, **kw): |
|
|||
717 | pass |
|
|||
718 | import gtk |
|
|||
719 | if gtk.pygtk_version >= (2,4,0): orig_mainloop = gtk.main |
|
|||
720 | else: orig_mainloop = gtk.mainloop |
|
|||
721 | gtk.mainloop = dummy_mainloop |
|
|||
722 | gtk.main = dummy_mainloop |
|
|||
723 | return orig_mainloop |
|
|||
724 |
|
||||
725 | def hijack_qt(): |
|
|||
726 | """Modifies PyQt's mainloop with a dummy so user code does not |
|
|||
727 | block IPython. This function returns the original |
|
|||
728 | `qt.qApp.exec_loop` function that has been hijacked. |
|
|||
729 | """ |
|
|||
730 | def dummy_mainloop(*args, **kw): |
|
|||
731 | pass |
|
|||
732 | import qt |
|
|||
733 | orig_mainloop = qt.qApp.exec_loop |
|
|||
734 | qt.qApp.exec_loop = dummy_mainloop |
|
|||
735 | qt.QApplication.exec_loop = dummy_mainloop |
|
|||
736 | return orig_mainloop |
|
|||
737 |
|
||||
738 | def hijack_qt4(): |
|
|||
739 | """Modifies PyQt4's mainloop with a dummy so user code does not |
|
|||
740 | block IPython. This function returns the original |
|
|||
741 | `QtGui.qApp.exec_` function that has been hijacked. |
|
|||
742 | """ |
|
|||
743 | def dummy_mainloop(*args, **kw): |
|
|||
744 | pass |
|
|||
745 | from PyQt4 import QtGui, QtCore |
|
|||
746 | orig_mainloop = QtGui.qApp.exec_ |
|
|||
747 | QtGui.qApp.exec_ = dummy_mainloop |
|
|||
748 | QtGui.QApplication.exec_ = dummy_mainloop |
|
|||
749 | QtCore.QCoreApplication.exec_ = dummy_mainloop |
|
|||
750 | return orig_mainloop |
|
|||
751 |
|
||||
752 | #----------------------------------------------------------------------------- |
|
|||
753 | # The IPShell* classes below are the ones meant to be run by external code as |
|
|||
754 | # IPython instances. Note that unless a specific threading strategy is |
|
|||
755 | # desired, the factory function start() below should be used instead (it |
|
|||
756 | # selects the proper threaded class). |
|
|||
757 |
|
||||
758 | class IPThread(threading.Thread): |
|
|||
759 | def run(self): |
|
|||
760 | self.IP.mainloop(self._banner) |
|
|||
761 | self.IP.kill() |
|
|||
762 |
|
||||
763 | class IPShellGTK(IPThread): |
|
|||
764 | """Run a gtk mainloop() in a separate thread. |
|
|||
765 |
|
||||
766 | Python commands can be passed to the thread where they will be executed. |
|
|||
767 | This is implemented by periodically checking for passed code using a |
|
|||
768 | GTK timeout callback.""" |
|
|||
769 |
|
||||
770 | TIMEOUT = 100 # Millisecond interval between timeouts. |
|
|||
771 |
|
||||
772 | def __init__(self,argv=None,user_ns=None,user_global_ns=None, |
|
|||
773 | debug=1,shell_class=MTInteractiveShell): |
|
|||
774 |
|
||||
775 | import gtk |
|
|||
776 | # Check for set_interactive, coming up in new pygtk. |
|
|||
777 | # Disable it so that this code works, but notify |
|
|||
778 | # the user that he has a better option as well. |
|
|||
779 | # XXX TODO better support when set_interactive is released |
|
|||
780 | try: |
|
|||
781 | gtk.set_interactive(False) |
|
|||
782 | print "Your PyGtk has set_interactive(), so you can use the" |
|
|||
783 | print "more stable single-threaded Gtk mode." |
|
|||
784 | print "See https://bugs.launchpad.net/ipython/+bug/270856" |
|
|||
785 | except AttributeError: |
|
|||
786 | pass |
|
|||
787 |
|
||||
788 | self.gtk = gtk |
|
|||
789 | self.gtk_mainloop = hijack_gtk() |
|
|||
790 |
|
||||
791 | # Allows us to use both Tk and GTK. |
|
|||
792 | self.tk = get_tk() |
|
|||
793 |
|
||||
794 | if gtk.pygtk_version >= (2,4,0): mainquit = self.gtk.main_quit |
|
|||
795 | else: mainquit = self.gtk.mainquit |
|
|||
796 |
|
||||
797 | self.IP = make_IPython(argv,user_ns=user_ns, |
|
|||
798 | user_global_ns=user_global_ns, |
|
|||
799 | debug=debug, |
|
|||
800 | shell_class=shell_class, |
|
|||
801 | on_kill=[mainquit]) |
|
|||
802 |
|
||||
803 | # HACK: slot for banner in self; it will be passed to the mainloop |
|
|||
804 | # method only and .run() needs it. The actual value will be set by |
|
|||
805 | # .mainloop(). |
|
|||
806 | self._banner = None |
|
|||
807 |
|
||||
808 | threading.Thread.__init__(self) |
|
|||
809 |
|
||||
810 | def mainloop(self,sys_exit=0,banner=None): |
|
|||
811 |
|
||||
812 | self._banner = banner |
|
|||
813 |
|
||||
814 | if self.gtk.pygtk_version >= (2,4,0): |
|
|||
815 | import gobject |
|
|||
816 | gobject.idle_add(self.on_timer) |
|
|||
817 | else: |
|
|||
818 | self.gtk.idle_add(self.on_timer) |
|
|||
819 |
|
||||
820 | if sys.platform != 'win32': |
|
|||
821 | try: |
|
|||
822 | if self.gtk.gtk_version[0] >= 2: |
|
|||
823 | self.gtk.gdk.threads_init() |
|
|||
824 | except AttributeError: |
|
|||
825 | pass |
|
|||
826 | except RuntimeError: |
|
|||
827 | error('Your pyGTK likely has not been compiled with ' |
|
|||
828 | 'threading support.\n' |
|
|||
829 | 'The exception printout is below.\n' |
|
|||
830 | 'You can either rebuild pyGTK with threads, or ' |
|
|||
831 | 'try using \n' |
|
|||
832 | 'matplotlib with a different backend (like Tk or WX).\n' |
|
|||
833 | 'Note that matplotlib will most likely not work in its ' |
|
|||
834 | 'current state!') |
|
|||
835 | self.IP.InteractiveTB() |
|
|||
836 |
|
||||
837 | self.start() |
|
|||
838 | self.gtk.gdk.threads_enter() |
|
|||
839 | self.gtk_mainloop() |
|
|||
840 | self.gtk.gdk.threads_leave() |
|
|||
841 | self.join() |
|
|||
842 |
|
||||
843 | def on_timer(self): |
|
|||
844 | """Called when GTK is idle. |
|
|||
845 |
|
||||
846 | Must return True always, otherwise GTK stops calling it""" |
|
|||
847 |
|
||||
848 | update_tk(self.tk) |
|
|||
849 | self.IP.runcode() |
|
|||
850 | time.sleep(0.01) |
|
|||
851 | return True |
|
|||
852 |
|
||||
853 |
|
||||
854 | class IPShellWX(IPThread): |
|
|||
855 | """Run a wx mainloop() in a separate thread. |
|
|||
856 |
|
||||
857 | Python commands can be passed to the thread where they will be executed. |
|
|||
858 | This is implemented by periodically checking for passed code using a |
|
|||
859 | GTK timeout callback.""" |
|
|||
860 |
|
||||
861 | TIMEOUT = 100 # Millisecond interval between timeouts. |
|
|||
862 |
|
||||
863 | def __init__(self,argv=None,user_ns=None,user_global_ns=None, |
|
|||
864 | debug=1,shell_class=MTInteractiveShell): |
|
|||
865 |
|
||||
866 | self.IP = make_IPython(argv,user_ns=user_ns, |
|
|||
867 | user_global_ns=user_global_ns, |
|
|||
868 | debug=debug, |
|
|||
869 | shell_class=shell_class, |
|
|||
870 | on_kill=[self.wxexit]) |
|
|||
871 |
|
||||
872 | wantedwxversion=self.IP.rc.wxversion |
|
|||
873 | if wantedwxversion!="0": |
|
|||
874 | try: |
|
|||
875 | import wxversion |
|
|||
876 | except ImportError: |
|
|||
877 | error('The wxversion module is needed for WX version selection') |
|
|||
878 | else: |
|
|||
879 | try: |
|
|||
880 | wxversion.select(wantedwxversion) |
|
|||
881 | except: |
|
|||
882 | self.IP.InteractiveTB() |
|
|||
883 | error('Requested wxPython version %s could not be loaded' % |
|
|||
884 | wantedwxversion) |
|
|||
885 |
|
||||
886 | import wx |
|
|||
887 |
|
||||
888 | threading.Thread.__init__(self) |
|
|||
889 | self.wx = wx |
|
|||
890 | self.wx_mainloop = hijack_wx() |
|
|||
891 |
|
||||
892 | # Allows us to use both Tk and GTK. |
|
|||
893 | self.tk = get_tk() |
|
|||
894 |
|
||||
895 | # HACK: slot for banner in self; it will be passed to the mainloop |
|
|||
896 | # method only and .run() needs it. The actual value will be set by |
|
|||
897 | # .mainloop(). |
|
|||
898 | self._banner = None |
|
|||
899 |
|
||||
900 | self.app = None |
|
|||
901 |
|
||||
902 | def wxexit(self, *args): |
|
|||
903 | if self.app is not None: |
|
|||
904 | self.app.agent.timer.Stop() |
|
|||
905 | self.app.ExitMainLoop() |
|
|||
906 |
|
||||
907 | def mainloop(self,sys_exit=0,banner=None): |
|
|||
908 |
|
||||
909 | self._banner = banner |
|
|||
910 |
|
||||
911 | self.start() |
|
|||
912 |
|
||||
913 | class TimerAgent(self.wx.MiniFrame): |
|
|||
914 | wx = self.wx |
|
|||
915 | IP = self.IP |
|
|||
916 | tk = self.tk |
|
|||
917 | def __init__(self, parent, interval): |
|
|||
918 | style = self.wx.DEFAULT_FRAME_STYLE | self.wx.TINY_CAPTION_HORIZ |
|
|||
919 | self.wx.MiniFrame.__init__(self, parent, -1, ' ', pos=(200, 200), |
|
|||
920 | size=(100, 100),style=style) |
|
|||
921 | self.Show(False) |
|
|||
922 | self.interval = interval |
|
|||
923 | self.timerId = self.wx.NewId() |
|
|||
924 |
|
||||
925 | def StartWork(self): |
|
|||
926 | self.timer = self.wx.Timer(self, self.timerId) |
|
|||
927 | self.wx.EVT_TIMER(self, self.timerId, self.OnTimer) |
|
|||
928 | self.timer.Start(self.interval) |
|
|||
929 |
|
||||
930 | def OnTimer(self, event): |
|
|||
931 | update_tk(self.tk) |
|
|||
932 | self.IP.runcode() |
|
|||
933 |
|
||||
934 | class App(self.wx.App): |
|
|||
935 | wx = self.wx |
|
|||
936 | TIMEOUT = self.TIMEOUT |
|
|||
937 | def OnInit(self): |
|
|||
938 | 'Create the main window and insert the custom frame' |
|
|||
939 | self.agent = TimerAgent(None, self.TIMEOUT) |
|
|||
940 | self.agent.Show(False) |
|
|||
941 | self.agent.StartWork() |
|
|||
942 | return True |
|
|||
943 |
|
||||
944 | self.app = App(redirect=False) |
|
|||
945 | self.wx_mainloop(self.app) |
|
|||
946 | self.join() |
|
|||
947 |
|
||||
948 |
|
||||
949 | class IPShellQt(IPThread): |
|
|||
950 | """Run a Qt event loop in a separate thread. |
|
|||
951 |
|
||||
952 | Python commands can be passed to the thread where they will be executed. |
|
|||
953 | This is implemented by periodically checking for passed code using a |
|
|||
954 | Qt timer / slot.""" |
|
|||
955 |
|
||||
956 | TIMEOUT = 100 # Millisecond interval between timeouts. |
|
|||
957 |
|
||||
958 | def __init__(self, argv=None, user_ns=None, user_global_ns=None, |
|
|||
959 | debug=0, shell_class=MTInteractiveShell): |
|
|||
960 |
|
||||
961 | import qt |
|
|||
962 |
|
||||
963 | self.exec_loop = hijack_qt() |
|
|||
964 |
|
||||
965 | # Allows us to use both Tk and QT. |
|
|||
966 | self.tk = get_tk() |
|
|||
967 |
|
||||
968 | self.IP = make_IPython(argv, |
|
|||
969 | user_ns=user_ns, |
|
|||
970 | user_global_ns=user_global_ns, |
|
|||
971 | debug=debug, |
|
|||
972 | shell_class=shell_class, |
|
|||
973 | on_kill=[qt.qApp.exit]) |
|
|||
974 |
|
||||
975 | # HACK: slot for banner in self; it will be passed to the mainloop |
|
|||
976 | # method only and .run() needs it. The actual value will be set by |
|
|||
977 | # .mainloop(). |
|
|||
978 | self._banner = None |
|
|||
979 |
|
||||
980 | threading.Thread.__init__(self) |
|
|||
981 |
|
||||
982 | def mainloop(self, sys_exit=0, banner=None): |
|
|||
983 |
|
||||
984 | import qt |
|
|||
985 |
|
||||
986 | self._banner = banner |
|
|||
987 |
|
||||
988 | if qt.QApplication.startingUp(): |
|
|||
989 | a = qt.QApplication(sys.argv) |
|
|||
990 |
|
||||
991 | self.timer = qt.QTimer() |
|
|||
992 | qt.QObject.connect(self.timer, |
|
|||
993 | qt.SIGNAL('timeout()'), |
|
|||
994 | self.on_timer) |
|
|||
995 |
|
||||
996 | self.start() |
|
|||
997 | self.timer.start(self.TIMEOUT, True) |
|
|||
998 | while True: |
|
|||
999 | if self.IP._kill: break |
|
|||
1000 | self.exec_loop() |
|
|||
1001 | self.join() |
|
|||
1002 |
|
||||
1003 | def on_timer(self): |
|
|||
1004 | update_tk(self.tk) |
|
|||
1005 | result = self.IP.runcode() |
|
|||
1006 | self.timer.start(self.TIMEOUT, True) |
|
|||
1007 | return result |
|
|||
1008 |
|
||||
1009 |
|
||||
1010 | class IPShellQt4(IPThread): |
|
|||
1011 | """Run a Qt event loop in a separate thread. |
|
|||
1012 |
|
||||
1013 | Python commands can be passed to the thread where they will be executed. |
|
|||
1014 | This is implemented by periodically checking for passed code using a |
|
|||
1015 | Qt timer / slot.""" |
|
|||
1016 |
|
||||
1017 | TIMEOUT = 100 # Millisecond interval between timeouts. |
|
|||
1018 |
|
||||
1019 | def __init__(self, argv=None, user_ns=None, user_global_ns=None, |
|
|||
1020 | debug=0, shell_class=MTInteractiveShell): |
|
|||
1021 |
|
||||
1022 | from PyQt4 import QtCore, QtGui |
|
|||
1023 |
|
||||
1024 | try: |
|
|||
1025 | # present in PyQt4-4.2.1 or later |
|
|||
1026 | QtCore.pyqtRemoveInputHook() |
|
|||
1027 | except AttributeError: |
|
|||
1028 | pass |
|
|||
1029 |
|
||||
1030 | if QtCore.PYQT_VERSION_STR == '4.3': |
|
|||
1031 | warn('''PyQt4 version 4.3 detected. |
|
|||
1032 | If you experience repeated threading warnings, please update PyQt4. |
|
|||
1033 | ''') |
|
|||
1034 |
|
||||
1035 | self.exec_ = hijack_qt4() |
|
|||
1036 |
|
||||
1037 | # Allows us to use both Tk and QT. |
|
|||
1038 | self.tk = get_tk() |
|
|||
1039 |
|
||||
1040 | self.IP = make_IPython(argv, |
|
|||
1041 | user_ns=user_ns, |
|
|||
1042 | user_global_ns=user_global_ns, |
|
|||
1043 | debug=debug, |
|
|||
1044 | shell_class=shell_class, |
|
|||
1045 | on_kill=[QtGui.qApp.exit]) |
|
|||
1046 |
|
||||
1047 | # HACK: slot for banner in self; it will be passed to the mainloop |
|
|||
1048 | # method only and .run() needs it. The actual value will be set by |
|
|||
1049 | # .mainloop(). |
|
|||
1050 | self._banner = None |
|
|||
1051 |
|
||||
1052 | threading.Thread.__init__(self) |
|
|||
1053 |
|
||||
1054 | def mainloop(self, sys_exit=0, banner=None): |
|
|||
1055 |
|
||||
1056 | from PyQt4 import QtCore, QtGui |
|
|||
1057 |
|
||||
1058 | self._banner = banner |
|
|||
1059 |
|
||||
1060 | if QtGui.QApplication.startingUp(): |
|
|||
1061 | a = QtGui.QApplication(sys.argv) |
|
|||
1062 |
|
||||
1063 | self.timer = QtCore.QTimer() |
|
|||
1064 | QtCore.QObject.connect(self.timer, |
|
|||
1065 | QtCore.SIGNAL('timeout()'), |
|
|||
1066 | self.on_timer) |
|
|||
1067 |
|
||||
1068 | self.start() |
|
|||
1069 | self.timer.start(self.TIMEOUT) |
|
|||
1070 | while True: |
|
|||
1071 | if self.IP._kill: break |
|
|||
1072 | self.exec_() |
|
|||
1073 | self.join() |
|
|||
1074 |
|
||||
1075 | def on_timer(self): |
|
|||
1076 | update_tk(self.tk) |
|
|||
1077 | result = self.IP.runcode() |
|
|||
1078 | self.timer.start(self.TIMEOUT) |
|
|||
1079 | return result |
|
|||
1080 |
|
||||
1081 |
|
||||
1082 | # A set of matplotlib public IPython shell classes, for single-threaded (Tk* |
|
|||
1083 | # and FLTK*) and multithreaded (GTK*, WX* and Qt*) backends to use. |
|
|||
1084 | def _load_pylab(user_ns): |
|
|||
1085 | """Allow users to disable pulling all of pylab into the top-level |
|
|||
1086 | namespace. |
|
|||
1087 |
|
||||
1088 | This little utility must be called AFTER the actual ipython instance is |
|
|||
1089 | running, since only then will the options file have been fully parsed.""" |
|
|||
1090 |
|
||||
1091 | ip = IPython.ipapi.get() |
|
|||
1092 | if ip.options.pylab_import_all: |
|
|||
1093 | ip.ex("from matplotlib.pylab import *") |
|
|||
1094 | ip.IP.user_config_ns.update(ip.user_ns) |
|
|||
1095 |
|
||||
1096 |
|
||||
1097 | class IPShellMatplotlib(IPShell): |
|
|||
1098 | """Subclass IPShell with MatplotlibShell as the internal shell. |
|
|||
1099 |
|
||||
1100 | Single-threaded class, meant for the Tk* and FLTK* backends. |
|
|||
1101 |
|
||||
1102 | Having this on a separate class simplifies the external driver code.""" |
|
|||
1103 |
|
||||
1104 | def __init__(self,argv=None,user_ns=None,user_global_ns=None,debug=1): |
|
|||
1105 | IPShell.__init__(self,argv,user_ns,user_global_ns,debug, |
|
|||
1106 | shell_class=MatplotlibShell) |
|
|||
1107 | _load_pylab(self.IP.user_ns) |
|
|||
1108 |
|
||||
1109 | class IPShellMatplotlibGTK(IPShellGTK): |
|
|||
1110 | """Subclass IPShellGTK with MatplotlibMTShell as the internal shell. |
|
|||
1111 |
|
||||
1112 | Multi-threaded class, meant for the GTK* backends.""" |
|
|||
1113 |
|
||||
1114 | def __init__(self,argv=None,user_ns=None,user_global_ns=None,debug=1): |
|
|||
1115 | IPShellGTK.__init__(self,argv,user_ns,user_global_ns,debug, |
|
|||
1116 | shell_class=MatplotlibMTShell) |
|
|||
1117 | _load_pylab(self.IP.user_ns) |
|
|||
1118 |
|
||||
1119 | class IPShellMatplotlibWX(IPShellWX): |
|
|||
1120 | """Subclass IPShellWX with MatplotlibMTShell as the internal shell. |
|
|||
1121 |
|
||||
1122 | Multi-threaded class, meant for the WX* backends.""" |
|
|||
1123 |
|
||||
1124 | def __init__(self,argv=None,user_ns=None,user_global_ns=None,debug=1): |
|
|||
1125 | IPShellWX.__init__(self,argv,user_ns,user_global_ns,debug, |
|
|||
1126 | shell_class=MatplotlibMTShell) |
|
|||
1127 | _load_pylab(self.IP.user_ns) |
|
|||
1128 |
|
||||
1129 | class IPShellMatplotlibQt(IPShellQt): |
|
|||
1130 | """Subclass IPShellQt with MatplotlibMTShell as the internal shell. |
|
|||
1131 |
|
||||
1132 | Multi-threaded class, meant for the Qt* backends.""" |
|
|||
1133 |
|
||||
1134 | def __init__(self,argv=None,user_ns=None,user_global_ns=None,debug=1): |
|
|||
1135 | IPShellQt.__init__(self,argv,user_ns,user_global_ns,debug, |
|
|||
1136 | shell_class=MatplotlibMTShell) |
|
|||
1137 | _load_pylab(self.IP.user_ns) |
|
|||
1138 |
|
||||
1139 | class IPShellMatplotlibQt4(IPShellQt4): |
|
|||
1140 | """Subclass IPShellQt4 with MatplotlibMTShell as the internal shell. |
|
|||
1141 |
|
||||
1142 | Multi-threaded class, meant for the Qt4* backends.""" |
|
|||
1143 |
|
||||
1144 | def __init__(self,argv=None,user_ns=None,user_global_ns=None,debug=1): |
|
|||
1145 | IPShellQt4.__init__(self,argv,user_ns,user_global_ns,debug, |
|
|||
1146 | shell_class=MatplotlibMTShell) |
|
|||
1147 | _load_pylab(self.IP.user_ns) |
|
|||
1148 |
|
||||
1149 | #----------------------------------------------------------------------------- |
|
17 | #----------------------------------------------------------------------------- | |
1150 | # Factory functions to actually start the proper thread-aware shell |
|
|||
1151 |
|
||||
1152 | def _select_shell(argv): |
|
|||
1153 | """Select a shell from the given argv vector. |
|
|||
1154 |
|
||||
1155 | This function implements the threading selection policy, allowing runtime |
|
|||
1156 | control of the threading mode, both for general users and for matplotlib. |
|
|||
1157 |
|
||||
1158 | Return: |
|
|||
1159 | Shell class to be instantiated for runtime operation. |
|
|||
1160 | """ |
|
|||
1161 |
|
||||
1162 | global USE_TK |
|
|||
1163 |
|
||||
1164 | mpl_shell = {'gthread' : IPShellMatplotlibGTK, |
|
|||
1165 | 'wthread' : IPShellMatplotlibWX, |
|
|||
1166 | 'qthread' : IPShellMatplotlibQt, |
|
|||
1167 | 'q4thread' : IPShellMatplotlibQt4, |
|
|||
1168 | 'tkthread' : IPShellMatplotlib, # Tk is built-in |
|
|||
1169 | } |
|
|||
1170 |
|
||||
1171 | th_shell = {'gthread' : IPShellGTK, |
|
|||
1172 | 'wthread' : IPShellWX, |
|
|||
1173 | 'qthread' : IPShellQt, |
|
|||
1174 | 'q4thread' : IPShellQt4, |
|
|||
1175 | 'tkthread' : IPShell, # Tk is built-in |
|
|||
1176 | } |
|
|||
1177 |
|
||||
1178 | backends = {'gthread' : 'GTKAgg', |
|
|||
1179 | 'wthread' : 'WXAgg', |
|
|||
1180 | 'qthread' : 'QtAgg', |
|
|||
1181 | 'q4thread' :'Qt4Agg', |
|
|||
1182 | 'tkthread' :'TkAgg', |
|
|||
1183 | } |
|
|||
1184 |
|
||||
1185 | all_opts = set(['tk','pylab','gthread','qthread','q4thread','wthread', |
|
|||
1186 | 'tkthread']) |
|
|||
1187 | user_opts = set([s.replace('-','') for s in argv[:3]]) |
|
|||
1188 | special_opts = user_opts & all_opts |
|
|||
1189 |
|
||||
1190 | if 'tk' in special_opts: |
|
|||
1191 | USE_TK = True |
|
|||
1192 | special_opts.remove('tk') |
|
|||
1193 |
|
||||
1194 | if 'pylab' in special_opts: |
|
|||
1195 |
|
||||
1196 | try: |
|
|||
1197 | import matplotlib |
|
|||
1198 | except ImportError: |
|
|||
1199 | error('matplotlib could NOT be imported! Starting normal IPython.') |
|
|||
1200 | return IPShell |
|
|||
1201 |
|
||||
1202 | special_opts.remove('pylab') |
|
|||
1203 | # If there's any option left, it means the user wants to force the |
|
|||
1204 | # threading backend, else it's auto-selected from the rc file |
|
|||
1205 | if special_opts: |
|
|||
1206 | th_mode = special_opts.pop() |
|
|||
1207 | matplotlib.rcParams['backend'] = backends[th_mode] |
|
|||
1208 | else: |
|
|||
1209 | backend = matplotlib.rcParams['backend'] |
|
|||
1210 | if backend.startswith('GTK'): |
|
|||
1211 | th_mode = 'gthread' |
|
|||
1212 | elif backend.startswith('WX'): |
|
|||
1213 | th_mode = 'wthread' |
|
|||
1214 | elif backend.startswith('Qt4'): |
|
|||
1215 | th_mode = 'q4thread' |
|
|||
1216 | elif backend.startswith('Qt'): |
|
|||
1217 | th_mode = 'qthread' |
|
|||
1218 | else: |
|
|||
1219 | # Any other backend, use plain Tk |
|
|||
1220 | th_mode = 'tkthread' |
|
|||
1221 |
|
||||
1222 | return mpl_shell[th_mode] |
|
|||
1223 | else: |
|
|||
1224 | # No pylab requested, just plain threads |
|
|||
1225 | try: |
|
|||
1226 | th_mode = special_opts.pop() |
|
|||
1227 | except KeyError: |
|
|||
1228 | th_mode = 'tkthread' |
|
|||
1229 | return th_shell[th_mode] |
|
|||
1230 |
|
18 | |||
|
19 | from warnings import warn | |||
1231 |
|
20 | |||
1232 | # This is the one which should be called by external code. |
|
21 | msg = """ | |
1233 | def start(user_ns = None): |
|
22 | This module (IPython.Shell) has been moved to a new location | |
1234 | """Return a running shell instance, dealing with threading options. |
|
23 | (IPython.core.shell) and is being refactored. Please update your code | |
|
24 | to use the new IPython.core.shell module""" | |||
1235 |
|
25 | |||
1236 | This is a factory function which will instantiate the proper IPython shell |
|
26 | warn(msg, category=DeprecationWarning, stacklevel=1) | |
1237 | based on the user's threading choice. Such a selector is needed because |
|
|||
1238 | different GUI toolkits require different thread handling details.""" |
|
|||
1239 |
|
27 | |||
1240 | shell = _select_shell(sys.argv) |
|
28 | from IPython.core.shell import * | |
1241 | return shell(user_ns = user_ns) |
|
|||
1242 |
|
29 | |||
1243 | # Some aliases for backwards compatibility |
|
|||
1244 | IPythonShell = IPShell |
|
|||
1245 | IPythonShellEmbed = IPShellEmbed |
|
|||
1246 | #************************ End of file <Shell.py> *************************** |
|
@@ -1,4 +1,4 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 | """ |
|
2 | """ | |
3 | IPython -- An enhanced Interactive Python |
|
3 | IPython -- An enhanced Interactive Python | |
4 |
|
4 | |||
@@ -43,12 +43,13 b" if sys.version[0:3] < '2.4':" | |||||
43 | raise ImportError('Python Version 2.4 or above is required for IPython.') |
|
43 | raise ImportError('Python Version 2.4 or above is required for IPython.') | |
44 |
|
44 | |||
45 | # Make it easy to import extensions - they are always directly on pythonpath. |
|
45 | # Make it easy to import extensions - they are always directly on pythonpath. | |
46 |
# Therefore, non-IPython modules can be added to |
|
46 | # Therefore, non-IPython modules can be added to extensions directory | |
47 | import os |
|
47 | import os | |
48 |
sys.path.append(os.path.dirname(__file__) |
|
48 | sys.path.append(os.path.join(os.path.dirname(__file__), "extensions")) | |
49 |
|
49 | |||
50 | # Define what gets imported with a 'from IPython import *' |
|
50 | # Define what gets imported with a 'from IPython import *' | |
51 |
__all__ = ['ipapi','generics','ipstruct', |
|
51 | __all__ = ['IPython.core.ipapi','utils.generics','utils.ipstruct', | |
|
52 | 'core.release','core.shell'] | |||
52 |
|
53 | |||
53 | # Load __all__ in IPython namespace so that a simple 'import IPython' gives |
|
54 | # Load __all__ in IPython namespace so that a simple 'import IPython' gives | |
54 | # access to them via IPython.<name> |
|
55 | # access to them via IPython.<name> | |
@@ -57,16 +58,19 b' for name in __all__:' | |||||
57 | #print 'Importing: ',name # dbg |
|
58 | #print 'Importing: ',name # dbg | |
58 | __import__(name,glob,loc,[]) |
|
59 | __import__(name,glob,loc,[]) | |
59 |
|
60 | |||
60 | import Shell |
|
61 | from IPython.core import shell | |
|
62 | Shell = shell | |||
|
63 | from IPython.core import ipapi | |||
|
64 | from IPython.core import iplib | |||
61 |
|
65 | |||
62 | # Release data |
|
66 | # Release data | |
63 |
from IPython import |
|
67 | from IPython.core import release # do it explicitly so pydoc can see it - pydoc bug | |
64 | __author__ = '%s <%s>\n%s <%s>\n%s <%s>' % \ |
|
68 | __author__ = '%s <%s>\n%s <%s>\n%s <%s>' % \ | |
65 |
( |
|
69 | ( release.authors['Fernando'] + release.authors['Janko'] + \ | |
66 |
|
|
70 | release.authors['Nathan'] ) | |
67 |
__license__ = |
|
71 | __license__ = release.license | |
68 |
__version__ = |
|
72 | __version__ = release.version | |
69 |
__revision__ = |
|
73 | __revision__ = release.revision | |
70 |
|
74 | |||
71 | # Namespace cleanup |
|
75 | # Namespace cleanup | |
72 | del name,glob,loc |
|
76 | del name,glob,loc |
@@ -18,7 +18,7 b' __docformat__ = "restructuredtext en"' | |||||
18 | import os |
|
18 | import os | |
19 | from os.path import join as pjoin |
|
19 | from os.path import join as pjoin | |
20 |
|
20 | |||
21 | from IPython.genutils import get_home_dir, get_ipython_dir |
|
21 | from IPython.utils.genutils import get_home_dir, get_ipython_dir | |
22 | from IPython.external.configobj import ConfigObj |
|
22 | from IPython.external.configobj import ConfigObj | |
23 |
|
23 | |||
24 |
|
24 |
@@ -13,9 +13,9 b' import exceptions' | |||||
13 | import os |
|
13 | import os | |
14 | from pprint import pprint |
|
14 | from pprint import pprint | |
15 |
|
15 | |||
16 |
from IPython import ultra |
|
16 | from IPython.core import ultratb | |
17 | from IPython.ipstruct import Struct |
|
17 | from IPython.utils.ipstruct import Struct | |
18 | from IPython.genutils import * |
|
18 | from IPython.utils.genutils import * | |
19 |
|
19 | |||
20 | class ConfigLoaderError(exceptions.Exception): |
|
20 | class ConfigLoaderError(exceptions.Exception): | |
21 | """Exception for ConfigLoader class.""" |
|
21 | """Exception for ConfigLoader class.""" | |
@@ -68,7 +68,7 b' class ConfigLoader:' | |||||
68 | # avoid including the same file more than once |
|
68 | # avoid including the same file more than once | |
69 | if fname in self.included: |
|
69 | if fname in self.included: | |
70 | return data |
|
70 | return data | |
71 |
Xinfo = ultra |
|
71 | Xinfo = ultratb.AutoFormattedTB(color_scheme='NoColor') | |
72 | if convert==None and recurse_key : convert = {qwflat:recurse_key} |
|
72 | if convert==None and recurse_key : convert = {qwflat:recurse_key} | |
73 | # for production, change warn to 0: |
|
73 | # for production, change warn to 0: | |
74 | data.merge(read_dict(fname,convert,fs=self.field_sep,strip=1, |
|
74 | data.merge(read_dict(fname,convert,fs=self.field_sep,strip=1, |
1 | NO CONTENT: file renamed from IPython/UserConfig/__init__.py to IPython/config/userconfig/__init__.py |
|
NO CONTENT: file renamed from IPython/UserConfig/__init__.py to IPython/config/userconfig/__init__.py |
@@ -4,7 +4,7 b' This is a more flexible and safe way to configure ipython than *rc files' | |||||
4 | (ipythonrc, ipythonrc-pysh etc.) |
|
4 | (ipythonrc, ipythonrc-pysh etc.) | |
5 |
|
5 | |||
6 | This file is always imported on ipython startup. You can import the |
|
6 | This file is always imported on ipython startup. You can import the | |
7 |
ipython extensions you need here (see IPython/ |
|
7 | ipython extensions you need here (see IPython/extensions directory). | |
8 |
|
8 | |||
9 | Feel free to edit this file to customize your ipython experience. |
|
9 | Feel free to edit this file to customize your ipython experience. | |
10 |
|
10 | |||
@@ -18,8 +18,8 b' description on what you could do here.' | |||||
18 |
|
18 | |||
19 | # Most of your config files and extensions will probably start with this import |
|
19 | # Most of your config files and extensions will probably start with this import | |
20 |
|
20 | |||
21 |
|
|
21 | from IPython.core import ipapi | |
22 |
ip = |
|
22 | ip = ipapi.get() | |
23 |
|
23 | |||
24 | # You probably want to uncomment this if you did %upgrade -nolegacy |
|
24 | # You probably want to uncomment this if you did %upgrade -nolegacy | |
25 | # import ipy_defaults |
|
25 | # import ipy_defaults |
@@ -504,9 +504,9 b' import_mod' | |||||
504 |
|
504 | |||
505 | # Example: |
|
505 | # Example: | |
506 |
|
506 | |||
507 | # import_some IPython.genutils timing timings |
|
507 | # import_some IPython.utils.genutils timing timings | |
508 | # will produce internally the statement |
|
508 | # will produce internally the statement | |
509 | # from IPython.genutils import timing, timings |
|
509 | # from IPython.utils.genutils import timing, timings | |
510 |
|
510 | |||
511 | # timing() and timings() are two IPython utilities for timing the execution of |
|
511 | # timing() and timings() are two IPython utilities for timing the execution of | |
512 | # your own functions, which you may find useful. Just commment out the above |
|
512 | # your own functions, which you may find useful. Just commment out the above | |
@@ -593,8 +593,8 b' execfile' | |||||
593 |
|
593 | |||
594 | # execfile example-magic.py |
|
594 | # execfile example-magic.py | |
595 |
|
595 | |||
596 |
# Look at the examples in IPython/iplib.py for more details on how |
|
596 | # Look at the examples in IPython/core/iplib.py for more details on how | |
597 | # functions need to process their arguments. |
|
597 | # these magic functions need to process their arguments. | |
598 |
|
598 | |||
599 | #--------------------------------------------------------------------------- |
|
599 | #--------------------------------------------------------------------------- | |
600 | # Section: aliases for system shell commands |
|
600 | # Section: aliases for system shell commands |
1 | NO CONTENT: file renamed from IPython/UserConfig/ipythonrc-math to IPython/config/userconfig/ipythonrc-math |
|
NO CONTENT: file renamed from IPython/UserConfig/ipythonrc-math to IPython/config/userconfig/ipythonrc-math |
1 | NO CONTENT: file renamed from IPython/UserConfig/ipythonrc-numeric to IPython/config/userconfig/ipythonrc-numeric |
|
NO CONTENT: file renamed from IPython/UserConfig/ipythonrc-numeric to IPython/config/userconfig/ipythonrc-numeric |
@@ -21,12 +21,12 b' include ipythonrc' | |||||
21 |
|
21 | |||
22 | # import ... |
|
22 | # import ... | |
23 | # Module with alternate input syntax for PhysicalQuantity objects. |
|
23 | # Module with alternate input syntax for PhysicalQuantity objects. | |
24 |
import_mod IPython. |
|
24 | import_mod IPython.extensions.PhysicalQInput | |
25 |
|
25 | |||
26 | # from ... import * |
|
26 | # from ... import * | |
27 | # math CANNOT be imported after PhysicalQInteractive. It will override the |
|
27 | # math CANNOT be imported after PhysicalQInteractive. It will override the | |
28 | # functions defined there. |
|
28 | # functions defined there. | |
29 |
import_all math IPython. |
|
29 | import_all math IPython.extensions.PhysicalQInteractive | |
30 |
|
30 | |||
31 | # from ... import ... |
|
31 | # from ... import ... | |
32 | import_some |
|
32 | import_some |
@@ -25,7 +25,7 b' include ipythonrc' | |||||
25 | ############################################################################ |
|
25 | ############################################################################ | |
26 | # Load all the actual syntax extensions for shell-like operation, which live |
|
26 | # Load all the actual syntax extensions for shell-like operation, which live | |
27 | # in the InterpreterExec standard extension. |
|
27 | # in the InterpreterExec standard extension. | |
28 |
import_all IPython. |
|
28 | import_all IPython.extensions.InterpreterExec | |
29 |
|
29 | |||
30 | ############################################################################ |
|
30 | ############################################################################ | |
31 | # PROMPTS |
|
31 | # PROMPTS | |
@@ -87,7 +87,7 b' multi_line_specials 1' | |||||
87 | #fperez[IPython]16> ldir |
|
87 | #fperez[IPython]16> ldir | |
88 | #/usr/local/home/fperez/ipython/ipython/IPython |
|
88 | #/usr/local/home/fperez/ipython/ipython/IPython | |
89 | #drwxr-xr-x 2 fperez 4096 Jun 21 01:01 CVS/ |
|
89 | #drwxr-xr-x 2 fperez 4096 Jun 21 01:01 CVS/ | |
90 |
#drwxr-xr-x 3 fperez 4096 Jun 21 01:10 |
|
90 | #drwxr-xr-x 3 fperez 4096 Jun 21 01:10 extensions/ | |
91 | #drwxr-xr-x 3 fperez 4096 Jun 21 01:27 UserConfig/ |
|
91 | #drwxr-xr-x 3 fperez 4096 Jun 21 01:27 UserConfig/ | |
92 |
|
92 | |||
93 | #fperez[IPython]17> parts Hello world and goodbye |
|
93 | #fperez[IPython]17> parts Hello world and goodbye |
@@ -22,7 +22,7 b' include ipythonrc' | |||||
22 |
|
22 | |||
23 | # import ... |
|
23 | # import ... | |
24 | # Module with alternate input syntax for pasting python input |
|
24 | # Module with alternate input syntax for pasting python input | |
25 |
import_mod IPython. |
|
25 | import_mod IPython.extensions.InterpreterPasteInput | |
26 |
|
26 | |||
27 | # from ... import * |
|
27 | # from ... import * | |
28 | import_all |
|
28 | import_all |
1 | NO CONTENT: file renamed from IPython/tests/__init__.py to IPython/core/__init__.py |
|
NO CONTENT: file renamed from IPython/tests/__init__.py to IPython/core/__init__.py |
@@ -70,11 +70,11 b' import os' | |||||
70 | import re |
|
70 | import re | |
71 | import shlex |
|
71 | import shlex | |
72 | import sys |
|
72 | import sys | |
73 | import IPython.rlineimpl as readline |
|
73 | import IPython.utils.rlineimpl as readline | |
74 | import itertools |
|
74 | import itertools | |
75 | from IPython.ipstruct import Struct |
|
75 | from IPython.utils.ipstruct import Struct | |
76 | from IPython import ipapi |
|
76 | from IPython.core import ipapi | |
77 | from IPython import generics |
|
77 | from IPython.utils import generics | |
78 | import types |
|
78 | import types | |
79 |
|
79 | |||
80 | # Python 2.4 offers sets as a builtin |
|
80 | # Python 2.4 offers sets as a builtin | |
@@ -83,7 +83,7 b' try:' | |||||
83 | except NameError: |
|
83 | except NameError: | |
84 | from sets import Set as set |
|
84 | from sets import Set as set | |
85 |
|
85 | |||
86 | from IPython.genutils import debugx, dir2 |
|
86 | from IPython.utils.genutils import debugx, dir2 | |
87 |
|
87 | |||
88 | __all__ = ['Completer','IPCompleter'] |
|
88 | __all__ = ['Completer','IPCompleter'] | |
89 |
|
89 | |||
@@ -632,7 +632,7 b' class IPCompleter(Completer):' | |||||
632 | except IndexError: |
|
632 | except IndexError: | |
633 | return None |
|
633 | return None | |
634 | except: |
|
634 | except: | |
635 |
#from IPython. |
|
635 | #from IPython.core.ultratb import AutoFormattedTB; # dbg | |
636 | #tb=AutoFormattedTB('Verbose');tb() #dbg |
|
636 | #tb=AutoFormattedTB('Verbose');tb() #dbg | |
637 |
|
637 | |||
638 | # If completion fails, don't annoy the user. |
|
638 | # If completion fails, don't annoy the user. |
@@ -21,15 +21,14 b' Authors' | |||||
21 | # From the standard library |
|
21 | # From the standard library | |
22 | import os |
|
22 | import os | |
23 | import sys |
|
23 | import sys | |
24 |
from pprint import |
|
24 | from pprint import pformat | |
25 |
|
25 | |||
26 | # Our own |
|
26 | # Our own | |
27 |
from IPython import |
|
27 | from IPython.core import release | |
28 |
from IPython import ultra |
|
28 | from IPython.core import ultratb | |
29 | from IPython.ColorANSI import ColorScheme,ColorSchemeTable # too long names |
|
29 | from IPython.external.Itpl import itpl | |
30 | from IPython.Itpl import Itpl,itpl,printpl |
|
|||
31 |
|
30 | |||
32 | from IPython.genutils import * |
|
31 | from IPython.utils.genutils import * | |
33 |
|
32 | |||
34 | #**************************************************************************** |
|
33 | #**************************************************************************** | |
35 | class CrashHandler: |
|
34 | class CrashHandler: | |
@@ -134,7 +133,7 b' $self.bug_tracker' | |||||
134 | # write the report filename into the instance dict so it can get |
|
133 | # write the report filename into the instance dict so it can get | |
135 | # properly expanded out in the user message template |
|
134 | # properly expanded out in the user message template | |
136 | self.crash_report_fname = report_name |
|
135 | self.crash_report_fname = report_name | |
137 |
TBhandler = ultra |
|
136 | TBhandler = ultratb.VerboseTB(color_scheme=color_scheme, | |
138 | long_header=1) |
|
137 | long_header=1) | |
139 | traceback = TBhandler.text(etype,evalue,etb,context=31) |
|
138 | traceback = TBhandler.text(etype,evalue,etb,context=31) | |
140 |
|
139 | |||
@@ -167,8 +166,8 b' $self.bug_tracker' | |||||
167 | rpt_add = report.append |
|
166 | rpt_add = report.append | |
168 |
|
167 | |||
169 | rpt_add('*'*75+'\n\n'+'IPython post-mortem report\n\n') |
|
168 | rpt_add('*'*75+'\n\n'+'IPython post-mortem report\n\n') | |
170 |
rpt_add('IPython version: %s \n\n' % |
|
169 | rpt_add('IPython version: %s \n\n' % release.version) | |
171 |
rpt_add('BZR revision : %s \n\n' % |
|
170 | rpt_add('BZR revision : %s \n\n' % release.revision) | |
172 | rpt_add('Platform info : os.name -> %s, sys.platform -> %s' % |
|
171 | rpt_add('Platform info : os.name -> %s, sys.platform -> %s' % | |
173 | (os.name,sys.platform) ) |
|
172 | (os.name,sys.platform) ) | |
174 | rpt_add(sec_sep+'Current user configuration structure:\n\n') |
|
173 | rpt_add(sec_sep+'Current user configuration structure:\n\n') | |
@@ -196,7 +195,7 b' class IPythonCrashHandler(CrashHandler):' | |||||
196 | # Set argument defaults |
|
195 | # Set argument defaults | |
197 | app_name = 'IPython' |
|
196 | app_name = 'IPython' | |
198 | bug_tracker = 'https://bugs.launchpad.net/ipython/+filebug' |
|
197 | bug_tracker = 'https://bugs.launchpad.net/ipython/+filebug' | |
199 |
contact_name,contact_email = |
|
198 | contact_name,contact_email = release.authors[AUTHOR_CONTACT][:2] | |
200 | crash_report_fname = 'IPython_crash_report.txt' |
|
199 | crash_report_fname = 'IPython_crash_report.txt' | |
201 | # Call parent constructor |
|
200 | # Call parent constructor | |
202 | CrashHandler.__init__(self,IP,app_name,contact_name,contact_email, |
|
201 | CrashHandler.__init__(self,IP,app_name,contact_name,contact_email, | |
@@ -211,8 +210,8 b' class IPythonCrashHandler(CrashHandler):' | |||||
211 | rpt_add = report.append |
|
210 | rpt_add = report.append | |
212 |
|
211 | |||
213 | rpt_add('*'*75+'\n\n'+'IPython post-mortem report\n\n') |
|
212 | rpt_add('*'*75+'\n\n'+'IPython post-mortem report\n\n') | |
214 |
rpt_add('IPython version: %s \n\n' % |
|
213 | rpt_add('IPython version: %s \n\n' % release.version) | |
215 |
rpt_add('BZR revision : %s \n\n' % |
|
214 | rpt_add('BZR revision : %s \n\n' % release.revision) | |
216 | rpt_add('Platform info : os.name -> %s, sys.platform -> %s' % |
|
215 | rpt_add('Platform info : os.name -> %s, sys.platform -> %s' % | |
217 | (os.name,sys.platform) ) |
|
216 | (os.name,sys.platform) ) | |
218 | rpt_add(sec_sep+'Current user configuration structure:\n\n') |
|
217 | rpt_add(sec_sep+'Current user configuration structure:\n\n') |
@@ -31,9 +31,11 b' import linecache' | |||||
31 | import os |
|
31 | import os | |
32 | import sys |
|
32 | import sys | |
33 |
|
33 | |||
34 |
from IPython import PyColorize |
|
34 | from IPython.utils import PyColorize | |
35 |
from IPython. |
|
35 | from IPython.core import ipapi | |
36 |
from IPython. |
|
36 | from IPython.utils import coloransi | |
|
37 | from IPython.utils.genutils import Term | |||
|
38 | from IPython.core.excolors import exception_colors | |||
37 |
|
39 | |||
38 | # See if we can use pydb. |
|
40 | # See if we can use pydb. | |
39 | has_pydb = False |
|
41 | has_pydb = False | |
@@ -93,7 +95,7 b' class Tracer(object):' | |||||
93 |
|
95 | |||
94 | Usage example: |
|
96 | Usage example: | |
95 |
|
97 | |||
96 |
from IPython. |
|
98 | from IPython.core.debugger import Tracer; debug_here = Tracer() | |
97 |
|
99 | |||
98 | ... later in your code |
|
100 | ... later in your code | |
99 | debug_here() # -> will open up the debugger at that point. |
|
101 | debug_here() # -> will open up the debugger at that point. | |
@@ -114,7 +116,7 b' class Tracer(object):' | |||||
114 | def_colors = 'NoColor' |
|
116 | def_colors = 'NoColor' | |
115 | try: |
|
117 | try: | |
116 | # Limited tab completion support |
|
118 | # Limited tab completion support | |
117 |
import |
|
119 | import readline | |
118 | readline.parse_and_bind('tab: complete') |
|
120 | readline.parse_and_bind('tab: complete') | |
119 | except ImportError: |
|
121 | except ImportError: | |
120 | pass |
|
122 | pass | |
@@ -207,7 +209,7 b' class Pdb(OldPdb):' | |||||
207 | self.color_scheme_table = exception_colors() |
|
209 | self.color_scheme_table = exception_colors() | |
208 |
|
210 | |||
209 | # shorthands |
|
211 | # shorthands | |
210 |
C = |
|
212 | C = coloransi.TermColors | |
211 | cst = self.color_scheme_table |
|
213 | cst = self.color_scheme_table | |
212 |
|
214 | |||
213 | cst['NoColor'].colors.breakpoint_enabled = C.NoColor |
|
215 | cst['NoColor'].colors.breakpoint_enabled = C.NoColor | |
@@ -254,7 +256,7 b' class Pdb(OldPdb):' | |||||
254 | self.color_scheme_table = exception_colors() |
|
256 | self.color_scheme_table = exception_colors() | |
255 |
|
257 | |||
256 | # shorthands |
|
258 | # shorthands | |
257 |
C = |
|
259 | C = coloransi.TermColors | |
258 | cst = self.color_scheme_table |
|
260 | cst = self.color_scheme_table | |
259 |
|
261 | |||
260 | cst['NoColor'].colors.breakpoint_enabled = C.NoColor |
|
262 | cst['NoColor'].colors.breakpoint_enabled = C.NoColor |
@@ -12,7 +12,7 b' Color schemes for exception handling code in IPython.' | |||||
12 |
|
12 | |||
13 | #**************************************************************************** |
|
13 | #**************************************************************************** | |
14 | # Required modules |
|
14 | # Required modules | |
15 |
from IPython. |
|
15 | from IPython.utils.coloransi import ColorSchemeTable, TermColors, ColorScheme | |
16 |
|
16 | |||
17 | def exception_colors(): |
|
17 | def exception_colors(): | |
18 | """Return a color table with fields for exception reporting. |
|
18 | """Return a color table with fields for exception reporting. |
1 | NO CONTENT: file renamed from IPython/FakeModule.py to IPython/core/fakemodule.py |
|
NO CONTENT: file renamed from IPython/FakeModule.py to IPython/core/fakemodule.py |
@@ -5,9 +5,8 b'' | |||||
5 | import fnmatch |
|
5 | import fnmatch | |
6 | import os |
|
6 | import os | |
7 |
|
7 | |||
8 | # IPython imports |
|
8 | from IPython.utils.genutils import Term, ask_yes_no, warn | |
9 | from IPython.genutils import Term, ask_yes_no, warn |
|
9 | from IPython.core import ipapi | |
10 | import IPython.ipapi |
|
|||
11 |
|
10 | |||
12 | def magic_history(self, parameter_s = ''): |
|
11 | def magic_history(self, parameter_s = ''): | |
13 | """Print input history (_i<n> variables), with most recent last. |
|
12 | """Print input history (_i<n> variables), with most recent last. | |
@@ -229,7 +228,7 b' class ShadowHist:' | |||||
229 | #print "new",newidx # dbg |
|
228 | #print "new",newidx # dbg | |
230 | self.db.hset('shadowhist',ent, newidx) |
|
229 | self.db.hset('shadowhist',ent, newidx) | |
231 | except: |
|
230 | except: | |
232 |
|
|
231 | ipapi.get().IP.showtraceback() | |
233 | print "WARNING: disabling shadow history" |
|
232 | print "WARNING: disabling shadow history" | |
234 | self.disabled = True |
|
233 | self.disabled = True | |
235 |
|
234 |
@@ -19,8 +19,8 b" For example, suppose that you have a module called 'myiphooks' in your" | |||||
19 | PYTHONPATH, which contains the following definition: |
|
19 | PYTHONPATH, which contains the following definition: | |
20 |
|
20 | |||
21 | import os |
|
21 | import os | |
22 |
|
|
22 | from IPython.core import ipapi | |
23 |
ip = |
|
23 | ip = ipapi.get() | |
24 |
|
24 | |||
25 | def calljed(self,filename, linenum): |
|
25 | def calljed(self,filename, linenum): | |
26 | "My editor hook calls the jed editor directly." |
|
26 | "My editor hook calls the jed editor directly." | |
@@ -41,11 +41,11 b' somewhere in your configuration files or ipython command line.' | |||||
41 | # the file COPYING, distributed as part of this software. |
|
41 | # the file COPYING, distributed as part of this software. | |
42 | #***************************************************************************** |
|
42 | #***************************************************************************** | |
43 |
|
43 | |||
44 | from IPython import ipapi |
|
44 | from IPython.core import ipapi | |
45 |
|
45 | |||
46 | import os,bisect |
|
46 | import os, bisect | |
47 | import sys |
|
47 | import sys | |
48 | from genutils import Term,shell |
|
48 | from IPython.utils.genutils import Term, shell | |
49 | from pprint import PrettyPrinter |
|
49 | from pprint import PrettyPrinter | |
50 |
|
50 | |||
51 | # List here all the default hooks. For now it's just the editor functions |
|
51 | # List here all the default hooks. For now it's just the editor functions | |
@@ -249,8 +249,10 b' def pre_runcode_hook(self):' | |||||
249 | def clipboard_get(self): |
|
249 | def clipboard_get(self): | |
250 | """ Get text from the clipboard. |
|
250 | """ Get text from the clipboard. | |
251 | """ |
|
251 | """ | |
252 |
from IPython.clipboard import ( |
|
252 | from IPython.lib.clipboard import ( | |
253 | win32_clipboard_get) |
|
253 | osx_clipboard_get, tkinter_clipboard_get, | |
|
254 | win32_clipboard_get | |||
|
255 | ) | |||
254 | if sys.platform == 'win32': |
|
256 | if sys.platform == 'win32': | |
255 | chain = [win32_clipboard_get, tkinter_clipboard_get] |
|
257 | chain = [win32_clipboard_get, tkinter_clipboard_get] | |
256 | elif sys.platform == 'darwin': |
|
258 | elif sys.platform == 'darwin': |
@@ -40,20 +40,18 b' except NameError:' | |||||
40 | import __main__ |
|
40 | import __main__ | |
41 | import __builtin__ |
|
41 | import __builtin__ | |
42 | import os |
|
42 | import os | |
43 | import re |
|
|||
44 | import sys |
|
43 | import sys | |
45 | import types |
|
44 | from pprint import pprint | |
46 | from pprint import pprint,pformat |
|
|||
47 |
|
45 | |||
48 | # Our own |
|
46 | # Our own | |
49 | from IPython import DPyGetOpt |
|
47 | from IPython.utils import DPyGetOpt | |
50 |
from IPython import |
|
48 | from IPython.core import release | |
51 | from IPython.ipstruct import Struct |
|
49 | from IPython.utils.ipstruct import Struct | |
52 |
from IPython. |
|
50 | from IPython.core.outputtrap import OutputTrap | |
53 |
from IPython. |
|
51 | from IPython.config.configloader import ConfigLoader | |
54 | from IPython.iplib import InteractiveShell |
|
52 | from IPython.core.iplib import InteractiveShell | |
55 | from IPython.usage import cmd_line_usage,interactive_usage |
|
53 | from IPython.core.usage import cmd_line_usage, interactive_usage | |
56 | from IPython.genutils import * |
|
54 | from IPython.utils.genutils import * | |
57 |
|
55 | |||
58 | def force_import(modname,force_reload=False): |
|
56 | def force_import(modname,force_reload=False): | |
59 | if modname in sys.modules and force_reload: |
|
57 | if modname in sys.modules and force_reload: | |
@@ -108,15 +106,15 b' def make_IPython(argv=None,user_ns=None,user_global_ns=None,debug=1,' | |||||
108 |
|
106 | |||
109 | if DEVDEBUG: |
|
107 | if DEVDEBUG: | |
110 | # For developer debugging only (global flag) |
|
108 | # For developer debugging only (global flag) | |
111 |
from IPython import ultra |
|
109 | from IPython.core import ultratb | |
112 |
sys.excepthook = ultra |
|
110 | sys.excepthook = ultratb.VerboseTB(call_pdb=1) | |
113 |
|
111 | |||
114 | IP.BANNER_PARTS = ['Python %s\n' |
|
112 | IP.BANNER_PARTS = ['Python %s\n' | |
115 | 'Type "copyright", "credits" or "license" ' |
|
113 | 'Type "copyright", "credits" or "license" ' | |
116 | 'for more information.\n' |
|
114 | 'for more information.\n' | |
117 | % (sys.version.split('\n')[0],), |
|
115 | % (sys.version.split('\n')[0],), | |
118 | "IPython %s -- An enhanced Interactive Python." |
|
116 | "IPython %s -- An enhanced Interactive Python." | |
119 |
% ( |
|
117 | % (release.version,), | |
120 | """\ |
|
118 | """\ | |
121 | ? -> Introduction and overview of IPython's features. |
|
119 | ? -> Introduction and overview of IPython's features. | |
122 | %quickref -> Quick reference. |
|
120 | %quickref -> Quick reference. | |
@@ -325,7 +323,7 b" object? -> Details about 'object'. ?object also works, ?? prints more." | |||||
325 | sys.exit() |
|
323 | sys.exit() | |
326 |
|
324 | |||
327 | if opts_all.Version: |
|
325 | if opts_all.Version: | |
328 |
print |
|
326 | print release.version | |
329 | sys.exit() |
|
327 | sys.exit() | |
330 |
|
328 | |||
331 | if opts_all.magic_docstrings: |
|
329 | if opts_all.magic_docstrings: | |
@@ -551,12 +549,12 b" object? -> Details about 'object'. ?object also works, ?? prints more." | |||||
551 |
|
549 | |||
552 | # Recursive reload |
|
550 | # Recursive reload | |
553 | try: |
|
551 | try: | |
554 |
from IPython import deep |
|
552 | from IPython.lib import deepreload | |
555 | if IP_rc.deep_reload: |
|
553 | if IP_rc.deep_reload: | |
556 |
__builtin__.reload = deep |
|
554 | __builtin__.reload = deepreload.reload | |
557 | else: |
|
555 | else: | |
558 |
__builtin__.dreload = deep |
|
556 | __builtin__.dreload = deepreload.reload | |
559 |
del deep |
|
557 | del deepreload | |
560 | except ImportError: |
|
558 | except ImportError: | |
561 | pass |
|
559 | pass | |
562 |
|
560 |
1 | NO CONTENT: file renamed from IPython/Logger.py to IPython/core/logger.py |
|
NO CONTENT: file renamed from IPython/Logger.py to IPython/core/logger.py |
@@ -7,10 +7,10 b'' | |||||
7 | # the file COPYING, distributed as part of this software. |
|
7 | # the file COPYING, distributed as part of this software. | |
8 | #***************************************************************************** |
|
8 | #***************************************************************************** | |
9 |
|
9 | |||
10 |
|
|
10 | from IPython.core import ipapi | |
11 |
|
11 | |||
12 | from IPython.genutils import Term |
|
12 | from IPython.utils.genutils import Term | |
13 | from IPython.ipapi import IPyAutocall |
|
13 | from IPython.core.ipapi import IPyAutocall | |
14 |
|
14 | |||
15 | class Macro(IPyAutocall): |
|
15 | class Macro(IPyAutocall): | |
16 | """Simple class to store the value of macros as strings. |
|
16 | """Simple class to store the value of macros as strings. |
@@ -43,17 +43,18 b' except ImportError:' | |||||
43 |
|
43 | |||
44 | # Homebrewed |
|
44 | # Homebrewed | |
45 | import IPython |
|
45 | import IPython | |
46 |
from IPython import |
|
46 | from IPython.utils import wildcard | |
47 |
from IPython. |
|
47 | from IPython.core import debugger, oinspect | |
48 | from IPython.Itpl import Itpl, itpl, printpl,itplns |
|
48 | from IPython.core.fakemodule import FakeModule | |
49 | from IPython.PyColorize import Parser |
|
49 | from IPython.external.Itpl import Itpl, itpl, printpl,itplns | |
50 |
from IPython. |
|
50 | from IPython.utils.PyColorize import Parser | |
51 |
from IPython. |
|
51 | from IPython.utils.ipstruct import Struct | |
52 |
from IPython. |
|
52 | from IPython.core.macro import Macro | |
53 |
from IPython import |
|
53 | from IPython.utils.genutils import * | |
54 | import IPython.generics |
|
54 | from IPython.utils import platutils | |
55 |
import IPython. |
|
55 | import IPython.utils.generics | |
56 |
from IPython. |
|
56 | from IPython.core import ipapi | |
|
57 | from IPython.core.ipapi import UsageError | |||
57 | from IPython.testing import decorators as testdec |
|
58 | from IPython.testing import decorators as testdec | |
58 |
|
59 | |||
59 | #*************************************************************************** |
|
60 | #*************************************************************************** | |
@@ -717,9 +718,9 b' Currently the magic system has the following functions:\\n"""' | |||||
717 |
|
718 | |||
718 | if info.found: |
|
719 | if info.found: | |
719 | try: |
|
720 | try: | |
720 | IPython.generics.inspect_object(info.obj) |
|
721 | IPython.utils.generics.inspect_object(info.obj) | |
721 | return |
|
722 | return | |
722 |
except |
|
723 | except ipapi.TryNext: | |
723 | pass |
|
724 | pass | |
724 | # Get the docstring of the class property if it exists. |
|
725 | # Get the docstring of the class property if it exists. | |
725 | path = oname.split('.') |
|
726 | path = oname.split('.') | |
@@ -972,7 +973,7 b' Currently the magic system has the following functions:\\n"""' | |||||
972 | return self.shell.user_ns[i] |
|
973 | return self.shell.user_ns[i] | |
973 |
|
974 | |||
974 | # some types are well known and can be shorter |
|
975 | # some types are well known and can be shorter | |
975 | abbrevs = {'IPython.macro.Macro' : 'Macro'} |
|
976 | abbrevs = {'IPython.core.macro.Macro' : 'Macro'} | |
976 | def type_name(v): |
|
977 | def type_name(v): | |
977 | tn = type(v).__name__ |
|
978 | tn = type(v).__name__ | |
978 | return abbrevs.get(tn,tn) |
|
979 | return abbrevs.get(tn,tn) | |
@@ -1561,7 +1562,7 b' Currently the magic system has the following functions:\\n"""' | |||||
1561 | filename = file_finder(arg_lst[0]) |
|
1562 | filename = file_finder(arg_lst[0]) | |
1562 | except IndexError: |
|
1563 | except IndexError: | |
1563 | warn('you must provide at least a filename.') |
|
1564 | warn('you must provide at least a filename.') | |
1564 |
print '\n%run:\n', |
|
1565 | print '\n%run:\n',oinspect.getdoc(self.magic_run) | |
1565 | return |
|
1566 | return | |
1566 | except IOError,msg: |
|
1567 | except IOError,msg: | |
1567 | error(msg) |
|
1568 | error(msg) | |
@@ -1621,7 +1622,7 b' Currently the magic system has the following functions:\\n"""' | |||||
1621 | stats = self.magic_prun('',0,opts,arg_lst,prog_ns) |
|
1622 | stats = self.magic_prun('',0,opts,arg_lst,prog_ns) | |
1622 | else: |
|
1623 | else: | |
1623 | if opts.has_key('d'): |
|
1624 | if opts.has_key('d'): | |
1624 |
deb = |
|
1625 | deb = debugger.Pdb(self.shell.rc.colors) | |
1625 | # reset Breakpoint state, which is moronically kept |
|
1626 | # reset Breakpoint state, which is moronically kept | |
1626 | # in a class |
|
1627 | # in a class | |
1627 | bdb.Breakpoint.next = 1 |
|
1628 | bdb.Breakpoint.next = 1 | |
@@ -2257,7 +2258,7 b' Currently the magic system has the following functions:\\n"""' | |||||
2257 |
|
2258 | |||
2258 | If you wish to write your own editor hook, you can put it in a |
|
2259 | If you wish to write your own editor hook, you can put it in a | |
2259 | configuration file which you load at startup time. The default hook |
|
2260 | configuration file which you load at startup time. The default hook | |
2260 | is defined in the IPython.hooks module, and you can use that as a |
|
2261 | is defined in the IPython.core.hooks module, and you can use that as a | |
2261 | starting example for further modifications. That file also has |
|
2262 | starting example for further modifications. That file also has | |
2262 | general instructions on how to set a new hook for use once you've |
|
2263 | general instructions on how to set a new hook for use once you've | |
2263 | defined it.""" |
|
2264 | defined it.""" | |
@@ -2390,7 +2391,7 b' Currently the magic system has the following functions:\\n"""' | |||||
2390 | sys.stdout.flush() |
|
2391 | sys.stdout.flush() | |
2391 | try: |
|
2392 | try: | |
2392 | self.shell.hooks.editor(filename,lineno) |
|
2393 | self.shell.hooks.editor(filename,lineno) | |
2393 |
except |
|
2394 | except ipapi.TryNext: | |
2394 | warn('Could not open editor') |
|
2395 | warn('Could not open editor') | |
2395 | return |
|
2396 | return | |
2396 |
|
2397 | |||
@@ -2466,7 +2467,7 b' Currently the magic system has the following functions:\\n"""' | |||||
2466 | # local shortcut |
|
2467 | # local shortcut | |
2467 | shell = self.shell |
|
2468 | shell = self.shell | |
2468 |
|
2469 | |||
2469 | import IPython.rlineimpl as readline |
|
2470 | import IPython.utils.rlineimpl as readline | |
2470 |
|
2471 | |||
2471 | if not readline.have_readline and sys.platform == "win32": |
|
2472 | if not readline.have_readline and sys.platform == "win32": | |
2472 | msg = """\ |
|
2473 | msg = """\ | |
@@ -2645,7 +2646,7 b' Defaulting color scheme to \'NoColor\'"""' | |||||
2645 | try: |
|
2646 | try: | |
2646 | alias,cmd = par.split(None,1) |
|
2647 | alias,cmd = par.split(None,1) | |
2647 | except: |
|
2648 | except: | |
2648 |
print |
|
2649 | print oinspect.getdoc(self.magic_alias) | |
2649 | else: |
|
2650 | else: | |
2650 | nargs = cmd.count('%s') |
|
2651 | nargs = cmd.count('%s') | |
2651 | if nargs>0 and cmd.find('%l')>=0: |
|
2652 | if nargs>0 and cmd.find('%l')>=0: | |
@@ -3278,7 +3279,7 b' Defaulting color scheme to \'NoColor\'"""' | |||||
3278 | def _get_pasted_lines(self, sentinel): |
|
3279 | def _get_pasted_lines(self, sentinel): | |
3279 | """ Yield pasted lines until the user enters the given sentinel value. |
|
3280 | """ Yield pasted lines until the user enters the given sentinel value. | |
3280 | """ |
|
3281 | """ | |
3281 | from IPython import iplib |
|
3282 | from IPython.core import iplib | |
3282 | print "Pasting code; enter '%s' alone on the line to stop." % sentinel |
|
3283 | print "Pasting code; enter '%s' alone on the line to stop." % sentinel | |
3283 | while True: |
|
3284 | while True: | |
3284 | l = iplib.raw_input_original(':') |
|
3285 | l = iplib.raw_input_original(':') | |
@@ -3417,8 +3418,8 b' Defaulting color scheme to \'NoColor\'"""' | |||||
3417 |
|
3418 | |||
3418 | def magic_quickref(self,arg): |
|
3419 | def magic_quickref(self,arg): | |
3419 | """ Show a quick reference sheet """ |
|
3420 | """ Show a quick reference sheet """ | |
3420 | import IPython.usage |
|
3421 | import IPython.core.usage | |
3421 | qr = IPython.usage.quick_reference + self.magic_magic('-brief') |
|
3422 | qr = IPython.core.usage.quick_reference + self.magic_magic('-brief') | |
3422 |
|
3423 | |||
3423 | page(qr) |
|
3424 | page(qr) | |
3424 |
|
3425 | |||
@@ -3435,8 +3436,8 b' Defaulting color scheme to \'NoColor\'"""' | |||||
3435 | """ |
|
3436 | """ | |
3436 | ip = self.getapi() |
|
3437 | ip = self.getapi() | |
3437 | ipinstallation = path(IPython.__file__).dirname() |
|
3438 | ipinstallation = path(IPython.__file__).dirname() | |
3438 |
upgrade_script = '%s "%s"' % (sys.executable,ipinstallation / 'upgrade |
|
3439 | upgrade_script = '%s "%s"' % (sys.executable,ipinstallation / 'utils' / 'upgradedir.py') | |
3439 |
src_config = ipinstallation / ' |
|
3440 | src_config = ipinstallation / 'config' / 'userconfig' | |
3440 | userdir = path(ip.options.ipythondir) |
|
3441 | userdir = path(ip.options.ipythondir) | |
3441 | cmd = '%s "%s" "%s"' % (upgrade_script, src_config, userdir) |
|
3442 | cmd = '%s "%s" "%s"' % (upgrade_script, src_config, userdir) | |
3442 | print ">",cmd |
|
3443 | print ">",cmd | |
@@ -3471,8 +3472,8 b' Defaulting color scheme to \'NoColor\'"""' | |||||
3471 | """ |
|
3472 | """ | |
3472 |
|
3473 | |||
3473 | # XXX - Fix this to have cleaner activate/deactivate calls. |
|
3474 | # XXX - Fix this to have cleaner activate/deactivate calls. | |
3474 |
from IPython. |
|
3475 | from IPython.extensions import InterpreterPasteInput as ipaste | |
3475 | from IPython.ipstruct import Struct |
|
3476 | from IPython.utils.ipstruct import Struct | |
3476 |
|
3477 | |||
3477 | # Shorthands |
|
3478 | # Shorthands | |
3478 | shell = self.shell |
|
3479 | shell = self.shell |
@@ -27,11 +27,11 b' import sys' | |||||
27 | import types |
|
27 | import types | |
28 |
|
28 | |||
29 | # IPython's own |
|
29 | # IPython's own | |
30 | from IPython import PyColorize |
|
30 | from IPython.utils import PyColorize | |
31 | from IPython.genutils import page,indent,Term |
|
31 | from IPython.utils.genutils import page,indent,Term | |
32 | from IPython.Itpl import itpl |
|
32 | from IPython.external.Itpl import itpl | |
33 | from IPython.wildcard import list_namespace |
|
33 | from IPython.utils.wildcard import list_namespace | |
34 |
from IPython. |
|
34 | from IPython.utils.coloransi import * | |
35 |
|
35 | |||
36 | #**************************************************************************** |
|
36 | #**************************************************************************** | |
37 | # HACK!!! This is a crude fix for bugs in python 2.3's inspect module. We |
|
37 | # HACK!!! This is a crude fix for bugs in python 2.3's inspect module. We |
1 | NO CONTENT: file renamed from IPython/OutputTrap.py to IPython/core/outputtrap.py |
|
NO CONTENT: file renamed from IPython/OutputTrap.py to IPython/core/outputtrap.py |
@@ -8,7 +8,7 b' transforming work.' | |||||
8 | __docformat__ = "restructuredtext en" |
|
8 | __docformat__ = "restructuredtext en" | |
9 |
|
9 | |||
10 | import re |
|
10 | import re | |
11 |
|
|
11 | from IPython.core import ipapi | |
12 |
|
12 | |||
13 | class LineInfo(object): |
|
13 | class LineInfo(object): | |
14 | """A single line of input and associated info. |
|
14 | """A single line of input and associated info. | |
@@ -178,7 +178,7 b' def checkEmacs(l_info,ip):' | |||||
178 | def checkIPyAutocall(l_info,ip): |
|
178 | def checkIPyAutocall(l_info,ip): | |
179 | "Instances of IPyAutocall in user_ns get autocalled immediately" |
|
179 | "Instances of IPyAutocall in user_ns get autocalled immediately" | |
180 | obj = ip.user_ns.get(l_info.iFun, None) |
|
180 | obj = ip.user_ns.get(l_info.iFun, None) | |
181 |
if isinstance(obj, |
|
181 | if isinstance(obj, ipapi.IPyAutocall): | |
182 | obj.set_ip(ip.api) |
|
182 | obj.set_ip(ip.api) | |
183 | return ip.handle_auto |
|
183 | return ip.handle_auto | |
184 | else: |
|
184 | else: |
@@ -20,23 +20,24 b' import sys' | |||||
20 | import time |
|
20 | import time | |
21 |
|
21 | |||
22 | # IPython's own |
|
22 | # IPython's own | |
23 |
from IPython import |
|
23 | from IPython.utils import coloransi | |
24 |
from IPython import |
|
24 | from IPython.core import release | |
25 | from IPython.external.Itpl import ItplNS |
|
25 | from IPython.external.Itpl import ItplNS | |
26 | from IPython.ipapi import TryNext |
|
26 | from IPython.core.ipapi import TryNext | |
27 | from IPython.ipstruct import Struct |
|
27 | from IPython.utils.ipstruct import Struct | |
28 | from IPython.macro import Macro |
|
28 | from IPython.core.macro import Macro | |
|
29 | import IPython.utils.generics | |||
29 |
|
30 | |||
30 | from IPython.genutils import * |
|
31 | from IPython.utils.genutils import * | |
31 |
|
32 | |||
32 | #**************************************************************************** |
|
33 | #**************************************************************************** | |
33 | #Color schemes for Prompts. |
|
34 | #Color schemes for Prompts. | |
34 |
|
35 | |||
35 |
PromptColors = |
|
36 | PromptColors = coloransi.ColorSchemeTable() | |
36 |
InputColors = |
|
37 | InputColors = coloransi.InputTermColors # just a shorthand | |
37 |
Colors = |
|
38 | Colors = coloransi.TermColors # just a shorthand | |
38 |
|
39 | |||
39 |
PromptColors.add_scheme( |
|
40 | PromptColors.add_scheme(coloransi.ColorScheme( | |
40 | 'NoColor', |
|
41 | 'NoColor', | |
41 | in_prompt = InputColors.NoColor, # Input prompt |
|
42 | in_prompt = InputColors.NoColor, # Input prompt | |
42 | in_number = InputColors.NoColor, # Input prompt number |
|
43 | in_number = InputColors.NoColor, # Input prompt number | |
@@ -50,7 +51,7 b' PromptColors.add_scheme(ColorANSI.ColorScheme(' | |||||
50 | )) |
|
51 | )) | |
51 |
|
52 | |||
52 | # make some schemes as instances so we can copy them for modification easily: |
|
53 | # make some schemes as instances so we can copy them for modification easily: | |
53 |
__PColLinux = |
|
54 | __PColLinux = coloransi.ColorScheme( | |
54 | 'Linux', |
|
55 | 'Linux', | |
55 | in_prompt = InputColors.Green, |
|
56 | in_prompt = InputColors.Green, | |
56 | in_number = InputColors.LightGreen, |
|
57 | in_number = InputColors.LightGreen, | |
@@ -169,7 +170,7 b' prompt_specials_color = {' | |||||
169 | # Carriage return |
|
170 | # Carriage return | |
170 | r'\r': '\r', |
|
171 | r'\r': '\r', | |
171 | # Release version |
|
172 | # Release version | |
172 |
r'\v': |
|
173 | r'\v': release.version, | |
173 | # Root symbol ($ or #) |
|
174 | # Root symbol ($ or #) | |
174 | r'\$': ROOT_SYMBOL, |
|
175 | r'\$': ROOT_SYMBOL, | |
175 | } |
|
176 | } | |
@@ -185,7 +186,7 b" prompt_specials_nocolor[r'\\#'] = '${self.cache.prompt_count}'" | |||||
185 | # with a color name which may begin with a letter used by any other of the |
|
186 | # with a color name which may begin with a letter used by any other of the | |
186 | # allowed specials. This of course means that \\C will never be allowed for |
|
187 | # allowed specials. This of course means that \\C will never be allowed for | |
187 | # anything else. |
|
188 | # anything else. | |
188 |
input_colors = |
|
189 | input_colors = coloransi.InputTermColors | |
189 | for _color in dir(input_colors): |
|
190 | for _color in dir(input_colors): | |
190 | if _color[0] != '_': |
|
191 | if _color[0] != '_': | |
191 | c_name = r'\C_'+_color |
|
192 | c_name = r'\C_'+_color | |
@@ -573,7 +574,7 b' class CachedOutput:' | |||||
573 | display, e.g. when your own objects need special formatting. |
|
574 | display, e.g. when your own objects need special formatting. | |
574 | """ |
|
575 | """ | |
575 | try: |
|
576 | try: | |
576 | return IPython.generics.result_display(arg) |
|
577 | return IPython.utils.generics.result_display(arg) | |
577 | except TryNext: |
|
578 | except TryNext: | |
578 | return self.shell.hooks.result_display(arg) |
|
579 | return self.shell.hooks.result_display(arg) | |
579 |
|
580 |
1 | NO CONTENT: file renamed from IPython/Release.py to IPython/core/release.py |
|
NO CONTENT: file renamed from IPython/Release.py to IPython/core/release.py |
1 | NO CONTENT: file renamed from IPython/shadowns.py to IPython/core/shadowns.py |
|
NO CONTENT: file renamed from IPython/shadowns.py to IPython/core/shadowns.py |
@@ -16,7 +16,7 b' except ImportError:' | |||||
16 | HAS_CTYPES = False |
|
16 | HAS_CTYPES = False | |
17 |
|
17 | |||
18 | # our own |
|
18 | # our own | |
19 | from IPython.genutils import Term,warn,error,flag_calls, ask_yes_no |
|
19 | from IPython.utils.genutils import Term,warn,error,flag_calls, ask_yes_no | |
20 |
|
20 | |||
21 | #----------------------------------------------------------------------------- |
|
21 | #----------------------------------------------------------------------------- | |
22 | # Globals |
|
22 | # Globals |
1 | NO CONTENT: file renamed from IPython/tools/__init__.py to IPython/core/tests/__init__.py |
|
NO CONTENT: file renamed from IPython/tools/__init__.py to IPython/core/tests/__init__.py |
1 | NO CONTENT: file renamed from IPython/tests/obj_del.py to IPython/core/tests/obj_del.py |
|
NO CONTENT: file renamed from IPython/tests/obj_del.py to IPython/core/tests/obj_del.py |
@@ -18,7 +18,7 b' test_magic.py calls it.' | |||||
18 | #----------------------------------------------------------------------------- |
|
18 | #----------------------------------------------------------------------------- | |
19 | import sys |
|
19 | import sys | |
20 |
|
20 | |||
21 | from IPython import ipapi |
|
21 | from IPython.core import ipapi | |
22 |
|
22 | |||
23 | #----------------------------------------------------------------------------- |
|
23 | #----------------------------------------------------------------------------- | |
24 | # Globals |
|
24 | # Globals |
1 | NO CONTENT: file renamed from IPython/tests/tclass.py to IPython/core/tests/tclass.py |
|
NO CONTENT: file renamed from IPython/tests/tclass.py to IPython/core/tests/tclass.py |
@@ -3,7 +3,7 b'' | |||||
3 |
|
3 | |||
4 | import nose.tools as nt |
|
4 | import nose.tools as nt | |
5 |
|
5 | |||
6 |
from IPython. |
|
6 | from IPython.core.fakemodule import FakeModule, init_fakemod_dict | |
7 |
|
7 | |||
8 | # Make a fakemod and check a few properties |
|
8 | # Make a fakemod and check a few properties | |
9 | def test_mk_fakemod(): |
|
9 | def test_mk_fakemod(): |
@@ -13,7 +13,8 b' import tempfile' | |||||
13 | import nose.tools as nt |
|
13 | import nose.tools as nt | |
14 |
|
14 | |||
15 | # our own packages |
|
15 | # our own packages | |
16 |
from IPython import |
|
16 | from IPython.core import iplib | |
|
17 | from IPython.core import ipapi | |||
17 |
|
18 | |||
18 | #----------------------------------------------------------------------------- |
|
19 | #----------------------------------------------------------------------------- | |
19 | # Globals |
|
20 | # Globals |
@@ -11,7 +11,7 b' from cStringIO import StringIO' | |||||
11 |
|
11 | |||
12 | import nose.tools as nt |
|
12 | import nose.tools as nt | |
13 |
|
13 | |||
14 | from IPython.platutils import find_cmd, get_long_path_name |
|
14 | from IPython.utils.platutils import find_cmd, get_long_path_name | |
15 | from IPython.testing import decorators as dec |
|
15 | from IPython.testing import decorators as dec | |
16 | from IPython.testing import tools as tt |
|
16 | from IPython.testing import tools as tt | |
17 |
|
17 | |||
@@ -77,8 +77,8 b' def test_shist():' | |||||
77 | # Simple tests of ShadowHist class - test generator. |
|
77 | # Simple tests of ShadowHist class - test generator. | |
78 | import os, shutil, tempfile |
|
78 | import os, shutil, tempfile | |
79 |
|
79 | |||
80 |
from IPython. |
|
80 | from IPython.extensions import pickleshare | |
81 | from IPython.history import ShadowHist |
|
81 | from IPython.core.history import ShadowHist | |
82 |
|
82 | |||
83 | tfile = tempfile.mktemp('','tmp-ipython-') |
|
83 | tfile = tempfile.mktemp('','tmp-ipython-') | |
84 |
|
84 | |||
@@ -98,7 +98,7 b' def test_shist():' | |||||
98 |
|
98 | |||
99 | @dec.skipif_not_numpy |
|
99 | @dec.skipif_not_numpy | |
100 | def test_numpy_clear_array_undec(): |
|
100 | def test_numpy_clear_array_undec(): | |
101 |
from IPython. |
|
101 | from IPython.extensions import clearcmd | |
102 |
|
102 | |||
103 | _ip.ex('import numpy as np') |
|
103 | _ip.ex('import numpy as np') | |
104 | _ip.ex('a = np.empty(2)') |
|
104 | _ip.ex('a = np.empty(2)') |
@@ -1,6 +1,6 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 | """ |
|
2 | """ | |
3 |
ultra |
|
3 | ultratb.py -- Spice up your tracebacks! | |
4 |
|
4 | |||
5 | * ColorTB |
|
5 | * ColorTB | |
6 | I've always found it a bit hard to visually parse tracebacks in Python. The |
|
6 | I've always found it a bit hard to visually parse tracebacks in Python. The | |
@@ -9,8 +9,8 b' traceback in a manner similar to what you would expect from a syntax-highlightin' | |||||
9 | text editor. |
|
9 | text editor. | |
10 |
|
10 | |||
11 | Installation instructions for ColorTB: |
|
11 | Installation instructions for ColorTB: | |
12 |
import sys,ultra |
|
12 | import sys,ultratb | |
13 |
sys.excepthook = ultra |
|
13 | sys.excepthook = ultratb.ColorTB() | |
14 |
|
14 | |||
15 | * VerboseTB |
|
15 | * VerboseTB | |
16 | I've also included a port of Ka-Ping Yee's "cgitb.py" that produces all kinds |
|
16 | I've also included a port of Ka-Ping Yee's "cgitb.py" that produces all kinds | |
@@ -37,8 +37,8 b' Note:' | |||||
37 |
|
37 | |||
38 |
|
38 | |||
39 | Installation instructions for ColorTB: |
|
39 | Installation instructions for ColorTB: | |
40 |
import sys,ultra |
|
40 | import sys,ultratb | |
41 |
sys.excepthook = ultra |
|
41 | sys.excepthook = ultratb.VerboseTB() | |
42 |
|
42 | |||
43 | Note: Much of the code in this module was lifted verbatim from the standard |
|
43 | Note: Much of the code in this module was lifted verbatim from the standard | |
44 | library module 'traceback.py' and Ka-Ping Yee's 'cgitb.py'. |
|
44 | library module 'traceback.py' and Ka-Ping Yee's 'cgitb.py'. | |
@@ -90,10 +90,11 b' from inspect import getsourcefile, getfile, getmodule,\\' | |||||
90 |
|
90 | |||
91 | # IPython's own modules |
|
91 | # IPython's own modules | |
92 | # Modified pdb which doesn't damage IPython's readline handling |
|
92 | # Modified pdb which doesn't damage IPython's readline handling | |
93 |
from IPython import |
|
93 | from IPython.utils import PyColorize | |
94 |
from IPython. |
|
94 | from IPython.core import debugger, ipapi | |
95 | from IPython.excolors import exception_colors |
|
95 | from IPython.utils.ipstruct import Struct | |
96 | from IPython.genutils import Term,uniq_stable,error,info |
|
96 | from IPython.core.excolors import exception_colors | |
|
97 | from IPython.utils.genutils import Term,uniq_stable,error,info | |||
97 |
|
98 | |||
98 | # Globals |
|
99 | # Globals | |
99 | # amount of space to put line numbers before verbose tracebacks |
|
100 | # amount of space to put line numbers before verbose tracebacks | |
@@ -102,7 +103,7 b' INDENT_SIZE = 8' | |||||
102 | # Default color scheme. This is used, for example, by the traceback |
|
103 | # Default color scheme. This is used, for example, by the traceback | |
103 | # formatter. When running in an actual IPython instance, the user's rc.colors |
|
104 | # formatter. When running in an actual IPython instance, the user's rc.colors | |
104 | # value is used, but havinga module global makes this functionality available |
|
105 | # value is used, but havinga module global makes this functionality available | |
105 |
# to users of ultra |
|
106 | # to users of ultratb who are NOT running inside ipython. | |
106 | DEFAULT_SCHEME = 'NoColor' |
|
107 | DEFAULT_SCHEME = 'NoColor' | |
107 |
|
108 | |||
108 | #--------------------------------------------------------------------------- |
|
109 | #--------------------------------------------------------------------------- | |
@@ -272,6 +273,7 b' def _formatTracebackLines(lnum, index, lines, Colors, lvals=None,scheme=None):' | |||||
272 | scheme = ipinst.IP.rc.colors |
|
273 | scheme = ipinst.IP.rc.colors | |
273 | else: |
|
274 | else: | |
274 | scheme = DEFAULT_SCHEME |
|
275 | scheme = DEFAULT_SCHEME | |
|
276 | ||||
275 | _line_format = _parser.format2 |
|
277 | _line_format = _parser.format2 | |
276 |
|
278 | |||
277 | for line in lines: |
|
279 | for line in lines: | |
@@ -321,7 +323,7 b' class TBTools:' | |||||
321 | self.old_scheme = color_scheme # save initial value for toggles |
|
323 | self.old_scheme = color_scheme # save initial value for toggles | |
322 |
|
324 | |||
323 | if call_pdb: |
|
325 | if call_pdb: | |
324 |
self.pdb = |
|
326 | self.pdb = debugger.Pdb(self.color_scheme_table.active_scheme_name) | |
325 | else: |
|
327 | else: | |
326 | self.pdb = None |
|
328 | self.pdb = None | |
327 |
|
329 | |||
@@ -842,7 +844,7 b' class VerboseTB(TBTools):' | |||||
842 |
|
844 | |||
843 | if force or self.call_pdb: |
|
845 | if force or self.call_pdb: | |
844 | if self.pdb is None: |
|
846 | if self.pdb is None: | |
845 |
self.pdb = |
|
847 | self.pdb = debugger.Pdb( | |
846 | self.color_scheme_table.active_scheme_name) |
|
848 | self.color_scheme_table.active_scheme_name) | |
847 | # the system displayhook may have changed, restore the original |
|
849 | # the system displayhook may have changed, restore the original | |
848 | # for pdb |
|
850 | # for pdb |
@@ -113,7 +113,7 b' A WARNING ABOUT SIGNALS AND THREADS' | |||||
113 | interpreter itself, and it comes from the difficulty of writing |
|
113 | interpreter itself, and it comes from the difficulty of writing | |
114 | portable signal/threaded code. If any user is an expert on this topic |
|
114 | portable signal/threaded code. If any user is an expert on this topic | |
115 | and can suggest a better solution, I would love to hear about it. In |
|
115 | and can suggest a better solution, I would love to hear about it. In | |
116 |
the IPython sources, look at the |
|
116 | the IPython sources, look at the shell.py module, and in particular at | |
117 | the runcode() method. |
|
117 | the runcode() method. | |
118 |
|
118 | |||
119 | REGULAR OPTIONS |
|
119 | REGULAR OPTIONS |
@@ -25,7 +25,7 b' import types' | |||||
25 | import Gnuplot as Gnuplot_ori |
|
25 | import Gnuplot as Gnuplot_ori | |
26 | import Numeric |
|
26 | import Numeric | |
27 |
|
27 | |||
28 | from IPython.genutils import popkey,xsys |
|
28 | from IPython.utils.genutils import popkey,xsys | |
29 |
|
29 | |||
30 | # needed by hardcopy(): |
|
30 | # needed by hardcopy(): | |
31 | gp = Gnuplot_ori.gp |
|
31 | gp = Gnuplot_ori.gp |
@@ -16,7 +16,7 b" __all__ = ['Gnuplot','gp','gp_new','plot','plot2','splot','replot'," | |||||
16 | 'gphelp'] |
|
16 | 'gphelp'] | |
17 |
|
17 | |||
18 | import IPython.GnuplotRuntime as GRun |
|
18 | import IPython.GnuplotRuntime as GRun | |
19 | from IPython.genutils import page,warn |
|
19 | from IPython.utils.genutils import page,warn | |
20 |
|
20 | |||
21 | # Set global names for interactive use |
|
21 | # Set global names for interactive use | |
22 | Gnuplot = GRun.Gnuplot |
|
22 | Gnuplot = GRun.Gnuplot | |
@@ -140,7 +140,7 b' else:' | |||||
140 | print """*** Type `gphelp` for help on the Gnuplot integration features.""" |
|
140 | print """*** Type `gphelp` for help on the Gnuplot integration features.""" | |
141 |
|
141 | |||
142 | # Add the new magic functions to the class dict |
|
142 | # Add the new magic functions to the class dict | |
143 | from IPython.iplib import InteractiveShell |
|
143 | from IPython.core.iplib import InteractiveShell | |
144 | InteractiveShell.magic_gpc = magic_gpc |
|
144 | InteractiveShell.magic_gpc = magic_gpc | |
145 | InteractiveShell.magic_gp_set_default = magic_gp_set_default |
|
145 | InteractiveShell.magic_gp_set_default = magic_gp_set_default | |
146 |
|
146 |
@@ -53,7 +53,7 b" __all__ = ['Gnuplot','gp','gp_new','Data','File','Func','GridData'," | |||||
53 | 'pm3d_config','eps_fix_bbox'] |
|
53 | 'pm3d_config','eps_fix_bbox'] | |
54 |
|
54 | |||
55 | import os,tempfile,sys |
|
55 | import os,tempfile,sys | |
56 | from IPython.genutils import getoutput |
|
56 | from IPython.utils.genutils import getoutput | |
57 |
|
57 | |||
58 | #--------------------------------------------------------------------------- |
|
58 | #--------------------------------------------------------------------------- | |
59 | # Notes on mouse support for Gnuplot.py |
|
59 | # Notes on mouse support for Gnuplot.py |
1 | NO CONTENT: file renamed from IPython/Itpl.py to IPython/deathrow/Itpl.py |
|
NO CONTENT: file renamed from IPython/Itpl.py to IPython/deathrow/Itpl.py |
1 | NO CONTENT: file renamed from IPython/tools/tests/__init__.py to IPython/deathrow/__init__.py |
|
NO CONTENT: file renamed from IPython/tools/tests/__init__.py to IPython/deathrow/__init__.py |
@@ -10,8 +10,8 b' See the idoctest docstring below for usage details.' | |||||
10 | import doctest |
|
10 | import doctest | |
11 | import sys |
|
11 | import sys | |
12 |
|
12 | |||
13 |
|
|
13 | from IPython.core import ipapi | |
14 |
ip = |
|
14 | ip = ipapi.get() | |
15 |
|
15 | |||
16 | def rundoctest(text,ns=None,eraise=False): |
|
16 | def rundoctest(text,ns=None,eraise=False): | |
17 | """Run a the input source as a doctest, in the caller's namespace. |
|
17 | """Run a the input source as a doctest, in the caller's namespace. |
1 | NO CONTENT: file renamed from IPython/numutils.py to IPython/deathrow/numutils.py |
|
NO CONTENT: file renamed from IPython/numutils.py to IPython/deathrow/numutils.py |
@@ -9,13 +9,13 b' import sys' | |||||
9 |
|
9 | |||
10 | from twisted.internet import reactor, threads |
|
10 | from twisted.internet import reactor, threads | |
11 |
|
11 | |||
12 | from IPython.ipmaker import make_IPython |
|
12 | from IPython.core.ipmaker import make_IPython | |
13 | from IPython.iplib import InteractiveShell |
|
13 | from IPython.core.iplib import InteractiveShell | |
14 | from IPython.ipstruct import Struct |
|
14 | from IPython.utils.ipstruct import Struct | |
15 | import Queue,thread,threading,signal |
|
15 | import Queue,thread,threading,signal | |
16 | from signal import signal, SIGINT |
|
16 | from signal import signal, SIGINT | |
17 | from IPython.genutils import Term,warn,error,flag_calls, ask_yes_no |
|
17 | from IPython.utils.genutils import Term,warn,error,flag_calls, ask_yes_no | |
18 | import shellglobals |
|
18 | from IPython.core import shellglobals | |
19 |
|
19 | |||
20 | def install_gtk2(): |
|
20 | def install_gtk2(): | |
21 | """ Install gtk2 reactor, needs to be called bef """ |
|
21 | """ Install gtk2 reactor, needs to be called bef """ |
@@ -43,14 +43,14 b' def prefilter_shell(self,line,continuation):' | |||||
43 | return self._prefilter(line,continuation) |
|
43 | return self._prefilter(line,continuation) | |
44 |
|
44 | |||
45 | # Rebind this to be the new IPython prefilter: |
|
45 | # Rebind this to be the new IPython prefilter: | |
46 | from IPython.iplib import InteractiveShell |
|
46 | from IPython.core.iplib import InteractiveShell | |
47 | InteractiveShell.prefilter = prefilter_shell |
|
47 | InteractiveShell.prefilter = prefilter_shell | |
48 | # Clean up the namespace. |
|
48 | # Clean up the namespace. | |
49 | del InteractiveShell,prefilter_shell |
|
49 | del InteractiveShell,prefilter_shell | |
50 |
|
50 | |||
51 | # Provide pysh and further shell-oriented services |
|
51 | # Provide pysh and further shell-oriented services | |
52 | import os,sys,shutil |
|
52 | import os,sys,shutil | |
53 | from IPython.genutils import system,shell,getoutput,getoutputerror |
|
53 | from IPython.utils.genutils import system,shell,getoutput,getoutputerror | |
54 |
|
54 | |||
55 | # Short aliases for getting shell output as a string and a list |
|
55 | # Short aliases for getting shell output as a string and a list | |
56 | sout = getoutput |
|
56 | sout = getoutput |
@@ -85,7 +85,7 b' Authors' | |||||
85 |
|
85 | |||
86 | import re |
|
86 | import re | |
87 |
|
87 | |||
88 | from IPython.iplib import InteractiveShell |
|
88 | from IPython.core.iplib import InteractiveShell | |
89 |
|
89 | |||
90 | PROMPT_RE = re.compile(r'(^[ \t]*>>> |^[ \t]*\.\.\. )') |
|
90 | PROMPT_RE = re.compile(r'(^[ \t]*>>> |^[ \t]*\.\.\. )') | |
91 |
|
91 |
@@ -52,7 +52,7 b' def prefilter_PQ(self,line,continuation):' | |||||
52 | imported.""" |
|
52 | imported.""" | |
53 |
|
53 | |||
54 | from re import match |
|
54 | from re import match | |
55 | from IPython.iplib import InteractiveShell |
|
55 | from IPython.core.iplib import InteractiveShell | |
56 |
|
56 | |||
57 | # This regexp is what does the real work |
|
57 | # This regexp is what does the real work | |
58 | unit_split = match(r'\s*(\w+)\s*=\s*(-?\d*\.?\d*[eE]?-?\d*)\s+([a-zA-Z].*)', |
|
58 | unit_split = match(r'\s*(\w+)\s*=\s*(-?\d*\.?\d*[eE]?-?\d*)\s+([a-zA-Z].*)', | |
@@ -74,7 +74,7 b' def prefilter_PQ(self,line,continuation):' | |||||
74 | return InteractiveShell._prefilter(self,line,continuation) |
|
74 | return InteractiveShell._prefilter(self,line,continuation) | |
75 |
|
75 | |||
76 | # Rebind this to be the new IPython prefilter: |
|
76 | # Rebind this to be the new IPython prefilter: | |
77 | from IPython.iplib import InteractiveShell |
|
77 | from IPython.core.iplib import InteractiveShell | |
78 | InteractiveShell.prefilter = prefilter_PQ |
|
78 | InteractiveShell.prefilter = prefilter_PQ | |
79 |
|
79 | |||
80 | # Clean up the namespace. |
|
80 | # Clean up the namespace. |
1 | NO CONTENT: file renamed from IPython/Extensions/PhysicalQInteractive.py to IPython/extensions/PhysicalQInteractive.py |
|
NO CONTENT: file renamed from IPython/Extensions/PhysicalQInteractive.py to IPython/extensions/PhysicalQInteractive.py |
@@ -6,7 +6,7 b' PhysicalQ_Input for an example of how to do this).' | |||||
6 |
|
6 | |||
7 | Any file located here can be called with an 'execfile =' option as |
|
7 | Any file located here can be called with an 'execfile =' option as | |
8 |
|
8 | |||
9 |
execfile = |
|
9 | execfile = extensions/filename.py | |
10 |
|
10 | |||
11 | since the IPython directory itself is already part of the search path for |
|
11 | since the IPython directory itself is already part of the search path for | |
12 | files listed as 'execfile ='. |
|
12 | files listed as 'execfile ='. |
1 | NO CONTENT: file renamed from IPython/Extensions/astyle.py to IPython/extensions/astyle.py |
|
NO CONTENT: file renamed from IPython/Extensions/astyle.py to IPython/extensions/astyle.py |
@@ -1,9 +1,9 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 | """ IPython extension: add %clear magic """ |
|
2 | """ IPython extension: add %clear magic """ | |
3 |
|
3 | |||
4 |
|
|
4 | from IPython.core import ipapi | |
5 | import gc |
|
5 | import gc | |
6 |
ip = |
|
6 | ip = ipapi.get() | |
7 |
|
7 | |||
8 | def clear_f(self,arg): |
|
8 | def clear_f(self,arg): | |
9 | """ Clear various data (e.g. stored history data) |
|
9 | """ Clear various data (e.g. stored history data) |
@@ -2,8 +2,8 b'' | |||||
2 | """ %env magic command for storing environment variables persistently |
|
2 | """ %env magic command for storing environment variables persistently | |
3 | """ |
|
3 | """ | |
4 |
|
4 | |||
5 |
|
|
5 | from IPython.core import ipapi | |
6 |
ip = |
|
6 | ip = ipapi.get() | |
7 |
|
7 | |||
8 | import os,sys |
|
8 | import os,sys | |
9 |
|
9 | |||
@@ -16,7 +16,7 b' def restore_env(self):' | |||||
16 | os.environ[k] = os.environ.get(k,"") + v |
|
16 | os.environ[k] = os.environ.get(k,"") + v | |
17 | for k,v in env['pre']: |
|
17 | for k,v in env['pre']: | |
18 | os.environ[k] = v + os.environ.get(k,"") |
|
18 | os.environ[k] = v + os.environ.get(k,"") | |
19 |
raise |
|
19 | raise ipapi.TryNext | |
20 |
|
20 | |||
21 | ip.set_hook('late_startup_hook', restore_env) |
|
21 | ip.set_hook('late_startup_hook', restore_env) | |
22 |
|
22 |
@@ -8,10 +8,10 b' var = %magic blah blah' | |||||
8 | var = !ls |
|
8 | var = !ls | |
9 | """ |
|
9 | """ | |
10 |
|
10 | |||
11 |
|
|
11 | from IPython.core import ipapi | |
12 | from IPython.genutils import * |
|
12 | from IPython.utils.genutils import * | |
13 |
|
13 | |||
14 |
ip = |
|
14 | ip = ipapi.get() | |
15 |
|
15 | |||
16 | import re |
|
16 | import re | |
17 |
|
17 | |||
@@ -58,6 +58,6 b' def regex_prefilter_f(self,line):' | |||||
58 | if mo: |
|
58 | if mo: | |
59 | return handler(line,mo) |
|
59 | return handler(line,mo) | |
60 |
|
60 | |||
61 |
raise |
|
61 | raise ipapi.TryNext | |
62 |
|
62 | |||
63 | ip.set_hook('input_prefilter', regex_prefilter_f) |
|
63 | ip.set_hook('input_prefilter', regex_prefilter_f) |
@@ -2,7 +2,7 b'' | |||||
2 |
|
2 | |||
3 | import curses, fcntl, signal, struct, tty, textwrap, inspect |
|
3 | import curses, fcntl, signal, struct, tty, textwrap, inspect | |
4 |
|
4 | |||
5 | from IPython import ipapi |
|
5 | from IPython.core import ipapi | |
6 |
|
6 | |||
7 | import astyle, ipipe |
|
7 | import astyle, ipipe | |
8 |
|
8 |
@@ -1,7 +1,7 b'' | |||||
1 | # -*- coding: iso-8859-1 -*- |
|
1 | # -*- coding: iso-8859-1 -*- | |
2 |
|
2 | |||
3 | import ipipe, os, webbrowser, urllib |
|
3 | import ipipe, os, webbrowser, urllib | |
4 | from IPython import ipapi |
|
4 | from IPython.core import ipapi | |
5 | import wx |
|
5 | import wx | |
6 | import wx.grid, wx.html |
|
6 | import wx.grid, wx.html | |
7 |
|
7 |
1 | NO CONTENT: file renamed from IPython/Extensions/igrid_help.css to IPython/extensions/igrid_help.css |
|
NO CONTENT: file renamed from IPython/Extensions/igrid_help.css to IPython/extensions/igrid_help.css |
1 | NO CONTENT: file renamed from IPython/Extensions/igrid_help.html to IPython/extensions/igrid_help.html |
|
NO CONTENT: file renamed from IPython/Extensions/igrid_help.html to IPython/extensions/igrid_help.html |
@@ -133,12 +133,13 b' from IPython.external import simplegeneric' | |||||
133 | from IPython.external import path |
|
133 | from IPython.external import path | |
134 |
|
134 | |||
135 | try: |
|
135 | try: | |
136 |
from IPython import genutils |
|
136 | from IPython.utils import genutils | |
|
137 | from IPython.utils import generics | |||
137 | except ImportError: |
|
138 | except ImportError: | |
138 | genutils = None |
|
139 | genutils = None | |
139 | generics = None |
|
140 | generics = None | |
140 |
|
141 | |||
141 | from IPython import ipapi |
|
142 | from IPython.core import ipapi | |
142 |
|
143 | |||
143 |
|
144 | |||
144 | __all__ = [ |
|
145 | __all__ = [ | |
@@ -1216,11 +1217,11 b' class ils(Table):' | |||||
1216 | Examples:: |
|
1217 | Examples:: | |
1217 |
|
1218 | |||
1218 | >>> ils |
|
1219 | >>> ils | |
1219 |
<class 'IPython. |
|
1220 | <class 'IPython.extensions.ipipe.ils'> | |
1220 | >>> ils("/usr/local/lib/python2.4") |
|
1221 | >>> ils("/usr/local/lib/python2.4") | |
1221 |
IPython. |
|
1222 | IPython.extensions.ipipe.ils('/usr/local/lib/python2.4') | |
1222 | >>> ils("~") |
|
1223 | >>> ils("~") | |
1223 |
IPython. |
|
1224 | IPython.extensions.ipipe.ils('/home/fperez') | |
1224 | # all-random |
|
1225 | # all-random | |
1225 | """ |
|
1226 | """ | |
1226 | def __init__(self, base=os.curdir, dirs=True, files=True): |
|
1227 | def __init__(self, base=os.curdir, dirs=True, files=True): | |
@@ -1258,7 +1259,7 b' class iglob(Table):' | |||||
1258 | Examples:: |
|
1259 | Examples:: | |
1259 |
|
1260 | |||
1260 | >>> iglob("*.py") |
|
1261 | >>> iglob("*.py") | |
1261 |
IPython. |
|
1262 | IPython.extensions.ipipe.iglob('*.py') | |
1262 | """ |
|
1263 | """ | |
1263 | def __init__(self, glob): |
|
1264 | def __init__(self, glob): | |
1264 | self.glob = glob |
|
1265 | self.glob = glob | |
@@ -1284,11 +1285,11 b' class iwalk(Table):' | |||||
1284 | List all files and directories in a directory and it's subdirectory:: |
|
1285 | List all files and directories in a directory and it's subdirectory:: | |
1285 |
|
1286 | |||
1286 | >>> iwalk |
|
1287 | >>> iwalk | |
1287 |
<class 'IPython. |
|
1288 | <class 'IPython.extensions.ipipe.iwalk'> | |
1288 | >>> iwalk("/usr/lib") |
|
1289 | >>> iwalk("/usr/lib") | |
1289 |
IPython. |
|
1290 | IPython.extensions.ipipe.iwalk('/usr/lib') | |
1290 | >>> iwalk("~") |
|
1291 | >>> iwalk("~") | |
1291 |
IPython. |
|
1292 | IPython.extensions.ipipe.iwalk('/home/fperez') # random | |
1292 |
|
1293 | |||
1293 | """ |
|
1294 | """ | |
1294 | def __init__(self, base=os.curdir, dirs=True, files=True): |
|
1295 | def __init__(self, base=os.curdir, dirs=True, files=True): | |
@@ -1393,7 +1394,7 b' class ipwd(Table):' | |||||
1393 | Example:: |
|
1394 | Example:: | |
1394 |
|
1395 | |||
1395 | >>> ipwd | isort("uid") |
|
1396 | >>> ipwd | isort("uid") | |
1396 |
<IPython. |
|
1397 | <IPython.extensions.ipipe.isort key='uid' reverse=False at 0x849efec> | |
1397 | # random |
|
1398 | # random | |
1398 | """ |
|
1399 | """ | |
1399 | def __iter__(self): |
|
1400 | def __iter__(self): | |
@@ -1579,7 +1580,7 b' class ienv(Table):' | |||||
1579 | Example:: |
|
1580 | Example:: | |
1580 |
|
1581 | |||
1581 | >>> ienv |
|
1582 | >>> ienv | |
1582 |
<class 'IPython. |
|
1583 | <class 'IPython.extensions.ipipe.ienv'> | |
1583 | """ |
|
1584 | """ | |
1584 |
|
1585 | |||
1585 | def __iter__(self): |
|
1586 | def __iter__(self): | |
@@ -1601,9 +1602,9 b' class ihist(Table):' | |||||
1601 | Example:: |
|
1602 | Example:: | |
1602 |
|
1603 | |||
1603 | >>> ihist |
|
1604 | >>> ihist | |
1604 |
<class 'IPython. |
|
1605 | <class 'IPython.extensions.ipipe.ihist'> | |
1605 | >>> ihist(True) # raw mode |
|
1606 | >>> ihist(True) # raw mode | |
1606 |
<IPython. |
|
1607 | <IPython.extensions.ipipe.ihist object at 0x849602c> # random | |
1607 | """ |
|
1608 | """ | |
1608 | def __init__(self, raw=True): |
|
1609 | def __init__(self, raw=True): | |
1609 | self.raw = raw |
|
1610 | self.raw = raw | |
@@ -1638,7 +1639,7 b' class ialias(Table):' | |||||
1638 | Example:: |
|
1639 | Example:: | |
1639 |
|
1640 | |||
1640 | >>> ialias |
|
1641 | >>> ialias | |
1641 |
<class 'IPython. |
|
1642 | <class 'IPython.extensions.ipipe.ialias'> | |
1642 | """ |
|
1643 | """ | |
1643 | def __iter__(self): |
|
1644 | def __iter__(self): | |
1644 | api = ipapi.get() |
|
1645 | api = ipapi.get() | |
@@ -1701,10 +1702,10 b' class ix(Table):' | |||||
1701 | Examples:: |
|
1702 | Examples:: | |
1702 |
|
1703 | |||
1703 | >>> ix("ps x") |
|
1704 | >>> ix("ps x") | |
1704 |
IPython. |
|
1705 | IPython.extensions.ipipe.ix('ps x') | |
1705 |
|
1706 | |||
1706 | >>> ix("find .") | ifile |
|
1707 | >>> ix("find .") | ifile | |
1707 |
<IPython. |
|
1708 | <IPython.extensions.ipipe.ieval expr=<class 'IPython.extensions.ipipe.ifile'> at 0x8509d2c> | |
1708 | # random |
|
1709 | # random | |
1709 | """ |
|
1710 | """ | |
1710 | def __init__(self, cmd): |
|
1711 | def __init__(self, cmd): | |
@@ -1927,9 +1928,9 b' class isort(Pipe):' | |||||
1927 | Examples:: |
|
1928 | Examples:: | |
1928 |
|
1929 | |||
1929 | >>> ils | isort("size") |
|
1930 | >>> ils | isort("size") | |
1930 |
<IPython. |
|
1931 | <IPython.extensions.ipipe.isort key='size' reverse=False at 0x849ec2c> | |
1931 | >>> ils | isort("_.isdir(), _.lower()", reverse=True) |
|
1932 | >>> ils | isort("_.isdir(), _.lower()", reverse=True) | |
1932 |
<IPython. |
|
1933 | <IPython.extensions.ipipe.isort key='_.isdir(), _.lower()' reverse=True at 0x849eacc> | |
1933 | # all-random |
|
1934 | # all-random | |
1934 | """ |
|
1935 | """ | |
1935 |
|
1936 |
@@ -2,12 +2,12 b'' | |||||
2 |
|
2 | |||
3 | IPython extension that installs the completers related to external apps. |
|
3 | IPython extension that installs the completers related to external apps. | |
4 |
|
4 | |||
5 |
The actual implementations are in |
|
5 | The actual implementations are in extensions/ipy_completers.py | |
6 |
|
6 | |||
7 | """ |
|
7 | """ | |
8 |
|
|
8 | from IPython.core import ipapi | |
9 |
|
9 | |||
10 |
ip = |
|
10 | ip = ipapi.get() | |
11 |
|
11 | |||
12 | from ipy_completers import * |
|
12 | from ipy_completers import * | |
13 |
|
13 |
@@ -224,15 +224,15 b' reloader = ModuleReloader()' | |||||
224 | #------------------------------------------------------------------------------ |
|
224 | #------------------------------------------------------------------------------ | |
225 | # IPython connectivity |
|
225 | # IPython connectivity | |
226 | #------------------------------------------------------------------------------ |
|
226 | #------------------------------------------------------------------------------ | |
227 |
|
|
227 | from IPython.core import ipapi | |
228 |
|
228 | |||
229 |
ip = |
|
229 | ip = ipapi.get() | |
230 |
|
230 | |||
231 | autoreload_enabled = False |
|
231 | autoreload_enabled = False | |
232 |
|
232 | |||
233 | def runcode_hook(self): |
|
233 | def runcode_hook(self): | |
234 | if not autoreload_enabled: |
|
234 | if not autoreload_enabled: | |
235 |
raise |
|
235 | raise ipapi.TryNext | |
236 | try: |
|
236 | try: | |
237 | reloader.check() |
|
237 | reloader.check() | |
238 | except: |
|
238 | except: |
1 | NO CONTENT: file renamed from IPython/Extensions/ipy_bzr.py to IPython/extensions/ipy_bzr.py |
|
NO CONTENT: file renamed from IPython/Extensions/ipy_bzr.py to IPython/extensions/ipy_bzr.py |
@@ -1,18 +1,18 b'' | |||||
1 |
|
1 | |||
2 | """ Implementations for various useful completers |
|
2 | """ Implementations for various useful completers | |
3 |
|
3 | |||
4 |
See |
|
4 | See extensions/ipy_stock_completers.py on examples of how to enable a completer, | |
5 | but the basic idea is to do: |
|
5 | but the basic idea is to do: | |
6 |
|
6 | |||
7 | ip.set_hook('complete_command', svn_completer, str_key = 'svn') |
|
7 | ip.set_hook('complete_command', svn_completer, str_key = 'svn') | |
8 |
|
8 | |||
9 | """ |
|
9 | """ | |
10 |
|
|
10 | from IPython.core import ipapi | |
11 | import glob,os,shlex,sys |
|
11 | import glob,os,shlex,sys | |
12 | import inspect |
|
12 | import inspect | |
13 | from time import time |
|
13 | from time import time | |
14 | from zipimport import zipimporter |
|
14 | from zipimport import zipimporter | |
15 |
ip = |
|
15 | ip = ipapi.get() | |
16 |
|
16 | |||
17 | try: |
|
17 | try: | |
18 | set |
|
18 | set | |
@@ -329,7 +329,7 b' def cd_completer(self, event):' | |||||
329 | if ' ' in d: |
|
329 | if ' ' in d: | |
330 | # we don't want to deal with any of that, complex code |
|
330 | # we don't want to deal with any of that, complex code | |
331 | # for this is elsewhere |
|
331 | # for this is elsewhere | |
332 |
raise |
|
332 | raise ipapi.TryNext | |
333 | found.append( d ) |
|
333 | found.append( d ) | |
334 |
|
334 | |||
335 | if not found: |
|
335 | if not found: | |
@@ -341,7 +341,7 b' def cd_completer(self, event):' | |||||
341 | if bkmatches: |
|
341 | if bkmatches: | |
342 | return bkmatches |
|
342 | return bkmatches | |
343 |
|
343 | |||
344 |
raise |
|
344 | raise ipapi.TryNext | |
345 |
|
345 | |||
346 |
|
346 | |||
347 | def single_dir_expand(matches): |
|
347 | def single_dir_expand(matches): |
@@ -15,7 +15,7 b' Website: physics.nist.gov/constants' | |||||
15 | # inspired by maxima's physconst.mac by Cliff Yapp |
|
15 | # inspired by maxima's physconst.mac by Cliff Yapp | |
16 |
|
16 | |||
17 | #from math import * # math MUST be imported BEFORE PhysicalQInteractive |
|
17 | #from math import * # math MUST be imported BEFORE PhysicalQInteractive | |
18 |
from IPython. |
|
18 | from IPython.extensions.PhysicalQInteractive import PhysicalQuantityInteractive | |
19 |
|
19 | |||
20 | # Math constants: |
|
20 | # Math constants: | |
21 |
|
21 |
@@ -12,9 +12,9 b' ipy_profile_PROFILENAME etc.' | |||||
12 |
|
12 | |||
13 | """ |
|
13 | """ | |
14 |
|
14 | |||
15 | import IPython.rlineimpl as readline |
|
15 | import IPython.utils.rlineimpl as readline | |
16 |
|
|
16 | from IPython.core import ipapi | |
17 |
ip = |
|
17 | ip = ipapi.get() | |
18 |
|
18 | |||
19 | o = ip.options |
|
19 | o = ip.options | |
20 |
|
20 |
@@ -5,10 +5,10 b' They should honor the line number argument, at least.' | |||||
5 | Contributions are *very* welcome. |
|
5 | Contributions are *very* welcome. | |
6 | """ |
|
6 | """ | |
7 |
|
7 | |||
8 |
|
|
8 | from IPython.core import ipapi | |
9 |
ip = |
|
9 | ip = ipapi.get() | |
10 |
|
10 | |||
11 | from IPython.Itpl import itplns |
|
11 | from IPython.external.Itpl import itplns | |
12 | import os |
|
12 | import os | |
13 |
|
13 | |||
14 | def install_editor(run_template, wait = False): |
|
14 | def install_editor(run_template, wait = False): | |
@@ -29,7 +29,7 b' def install_editor(run_template, wait = False):' | |||||
29 | cmd = itplns(run_template, locals()) |
|
29 | cmd = itplns(run_template, locals()) | |
30 | print ">",cmd |
|
30 | print ">",cmd | |
31 | if os.system(cmd) != 0: |
|
31 | if os.system(cmd) != 0: | |
32 |
raise |
|
32 | raise ipapi.TryNext() | |
33 | if wait: |
|
33 | if wait: | |
34 | raw_input("Press Enter when done editing:") |
|
34 | raw_input("Press Enter when done editing:") | |
35 |
|
35 |
@@ -1,11 +1,12 b'' | |||||
1 |
|
|
1 | from IPython.core import ipapi | |
2 | ip = IPython.ipapi.get() |
|
2 | from IPython.core import macro | |
|
3 | ip = ipapi.get() | |||
3 |
|
4 | |||
4 | import os,pprint |
|
5 | import os,pprint | |
5 |
|
6 | |||
6 | def export(filename = None): |
|
7 | def export(filename = None): | |
7 |
|
8 | |||
8 | lines = ['import IPython.ipapi', 'ip = IPython.ipapi.get()',''] |
|
9 | lines = ['import IPython.core.ipapi', 'ip = IPython.core.ipapi.get()',''] | |
9 |
|
10 | |||
10 | vars = ip.db.keys('autorestore/*') |
|
11 | vars = ip.db.keys('autorestore/*') | |
11 | vars.sort() |
|
12 | vars.sort() | |
@@ -21,7 +22,7 b' def export(filename = None):' | |||||
21 |
|
22 | |||
22 | if k.startswith('_'): |
|
23 | if k.startswith('_'): | |
23 | continue |
|
24 | continue | |
24 |
if isinstance(v, |
|
25 | if isinstance(v, macro.Macro): | |
25 | macros.append((k,v)) |
|
26 | macros.append((k,v)) | |
26 | if type(v) in [int, str, float]: |
|
27 | if type(v) in [int, str, float]: | |
27 | variables.append((k,v)) |
|
28 | variables.append((k,v)) |
@@ -7,8 +7,8 b' to.' | |||||
7 | # for the purposes of this module, every module that has the name 'ip' globally |
|
7 | # for the purposes of this module, every module that has the name 'ip' globally | |
8 | # installed as below is an IPython extension |
|
8 | # installed as below is an IPython extension | |
9 |
|
9 | |||
10 |
|
|
10 | from IPython.core import ipapi | |
11 |
ip = |
|
11 | ip = ipapi.get() | |
12 |
|
12 | |||
13 | import sys,textwrap,inspect |
|
13 | import sys,textwrap,inspect | |
14 |
|
14 | |||
@@ -34,7 +34,7 b' class ExtUtil:' | |||||
34 | act = [] |
|
34 | act = [] | |
35 | for mname,m in sys.modules.items(): |
|
35 | for mname,m in sys.modules.items(): | |
36 | o = getattr(m, 'ip', None) |
|
36 | o = getattr(m, 'ip', None) | |
37 |
if isinstance(o, |
|
37 | if isinstance(o, ipapi.IPApi): | |
38 | act.append((mname,m)) |
|
38 | act.append((mname,m)) | |
39 | act.sort() |
|
39 | act.sort() | |
40 | return act |
|
40 | return act |
@@ -15,13 +15,14 b" do some useful tricks on their own, though (like use 'mglob' patterns)." | |||||
15 | Not to be confused with ipipe commands (ils etc.) that also start with i. |
|
15 | Not to be confused with ipipe commands (ils etc.) that also start with i. | |
16 | """ |
|
16 | """ | |
17 |
|
17 | |||
18 |
|
|
18 | from IPython.core import ipapi | |
19 |
ip = |
|
19 | ip = ipapi.get() | |
20 |
|
20 | |||
21 | import shutil,os,shlex |
|
21 | import shutil,os,shlex | |
22 | from IPython.external import mglob |
|
22 | from IPython.external import mglob | |
23 | from IPython.external.path import path |
|
23 | from IPython.external.path import path | |
24 | from IPython.ipapi import UsageError |
|
24 | from IPython.core.ipapi import UsageError | |
|
25 | import IPython.utils.generics | |||
25 |
|
26 | |||
26 | def parse_args(args): |
|
27 | def parse_args(args): | |
27 | """ Given arg string 'CMD files... target', return ([files], target) """ |
|
28 | """ Given arg string 'CMD files... target', return ([files], target) """ | |
@@ -228,9 +229,9 b' def complete_pathobj(obj, prev_completions):' | |||||
228 | if res: |
|
229 | if res: | |
229 | return res |
|
230 | return res | |
230 | # just return normal attributes of 'path' object if the dir is empty |
|
231 | # just return normal attributes of 'path' object if the dir is empty | |
231 |
raise |
|
232 | raise ipapi.TryNext | |
232 |
|
233 | |||
233 | complete_pathobj = IPython.generics.complete_object.when_type(PathObj)(complete_pathobj) |
|
234 | complete_pathobj = IPython.utils.generics.complete_object.when_type(PathObj)(complete_pathobj) | |
234 |
|
235 | |||
235 | def test_pathobj(): |
|
236 | def test_pathobj(): | |
236 | #p = PathObj('c:/prj') |
|
237 | #p = PathObj('c:/prj') |
@@ -8,8 +8,8 b' http://www.gnu.org/software/global/' | |||||
8 |
|
8 | |||
9 | """ |
|
9 | """ | |
10 |
|
10 | |||
11 |
|
|
11 | from IPython.core import ipapi | |
12 |
ip = |
|
12 | ip = ipapi.get() | |
13 | import os |
|
13 | import os | |
14 |
|
14 | |||
15 | # alter to your liking |
|
15 | # alter to your liking |
@@ -9,8 +9,9 b' only whitespace as completer delimiter. If this works well, we will' | |||||
9 | do the same in default completer. |
|
9 | do the same in default completer. | |
10 |
|
10 | |||
11 | """ |
|
11 | """ | |
12 |
from IPython import |
|
12 | from IPython.core import ipapi | |
13 |
from IPython. |
|
13 | from IPython.utils import generics | |
|
14 | from IPython.utils.genutils import dir2 | |||
14 |
|
15 | |||
15 | def attr_matches(self, text): |
|
16 | def attr_matches(self, text): | |
16 | """Compute matches when text contains a dot. |
|
17 | """Compute matches when text contains a dot. | |
@@ -66,10 +67,10 b' def attr_matches(self, text):' | |||||
66 | return res |
|
67 | return res | |
67 |
|
68 | |||
68 | def main(): |
|
69 | def main(): | |
69 | import IPython.rlineimpl as readline |
|
70 | import IPython.utils.rlineimpl as readline | |
70 | readline.set_completer_delims(" \n\t") |
|
71 | readline.set_completer_delims(" \n\t") | |
71 | # monkeypatch - the code will be folded to normal completer later on |
|
72 | # monkeypatch - the code will be folded to normal completer later on | |
72 | import IPython.completer |
|
73 | import IPython.core.completer | |
73 | IPython.completer.Completer.attr_matches = attr_matches |
|
74 | IPython.core.completer.Completer.attr_matches = attr_matches | |
74 |
|
75 | |||
75 | main() No newline at end of file |
|
76 | main() |
@@ -8,14 +8,14 b' Stores variables in Struct with some notes in PicleShare database' | |||||
8 | """ |
|
8 | """ | |
9 |
|
9 | |||
10 | from datetime import datetime |
|
10 | from datetime import datetime | |
11 |
|
|
11 | from IPython.core import ipapi | |
12 |
ip = |
|
12 | ip = ipapi.get() | |
13 |
|
13 | |||
14 | import pickleshare |
|
14 | import pickleshare | |
15 |
|
15 | |||
16 | import inspect,pickle,os,sys,textwrap |
|
16 | import inspect,pickle,os,sys,textwrap | |
17 |
from IPython. |
|
17 | from IPython.core.fakemodule import FakeModule | |
18 | from IPython.ipstruct import Struct |
|
18 | from IPython.utils.ipstruct import Struct | |
19 |
|
19 | |||
20 |
|
20 | |||
21 | def refresh_variables(ip, key=None): |
|
21 | def refresh_variables(ip, key=None): |
1 | NO CONTENT: file renamed from IPython/Extensions/ipy_kitcfg.py to IPython/extensions/ipy_kitcfg.py |
|
NO CONTENT: file renamed from IPython/Extensions/ipy_kitcfg.py to IPython/extensions/ipy_kitcfg.py |
@@ -9,12 +9,12 b' Stuff that is considered obsolete / redundant is gradually moved here.' | |||||
9 |
|
9 | |||
10 | """ |
|
10 | """ | |
11 |
|
11 | |||
12 |
|
|
12 | from IPython.core import ipapi | |
13 |
ip = |
|
13 | ip = ipapi.get() | |
14 |
|
14 | |||
15 | import os,sys |
|
15 | import os,sys | |
16 |
|
16 | |||
17 | from IPython.genutils import * |
|
17 | from IPython.utils.genutils import * | |
18 |
|
18 | |||
19 | # use rehashx |
|
19 | # use rehashx | |
20 |
|
20 |
@@ -201,8 +201,8 b' def _lookfor_generate_cache(module, import_modules, regenerate):' | |||||
201 | # IPython connectivity |
|
201 | # IPython connectivity | |
202 | #------------------------------------------------------------------------------ |
|
202 | #------------------------------------------------------------------------------ | |
203 |
|
203 | |||
204 |
|
|
204 | from IPython.core import ipapi | |
205 |
ip = |
|
205 | ip = ipapi.get() | |
206 |
|
206 | |||
207 | _lookfor_modules = ['numpy', 'scipy'] |
|
207 | _lookfor_modules = ['numpy', 'scipy'] | |
208 |
|
208 |
@@ -3,8 +3,8 b'' | |||||
3 | Add %p4 magic for pythonic p4 (Perforce) usage. |
|
3 | Add %p4 magic for pythonic p4 (Perforce) usage. | |
4 | """ |
|
4 | """ | |
5 |
|
5 | |||
6 |
|
|
6 | from IPython.core import ipapi | |
7 |
ip = |
|
7 | ip = ipapi.get() | |
8 |
|
8 | |||
9 | import os,sys,marshal |
|
9 | import os,sys,marshal | |
10 |
|
10 |
@@ -4,7 +4,7 b' Register pretty-printers for types using ipy_pretty.for_type() or' | |||||
4 | ipy_pretty.for_type_by_name(). For example, to use the example pretty-printer |
|
4 | ipy_pretty.for_type_by_name(). For example, to use the example pretty-printer | |
5 | for numpy dtype objects, add the following to your ipy_user_conf.py:: |
|
5 | for numpy dtype objects, add the following to your ipy_user_conf.py:: | |
6 |
|
6 | |||
7 |
from IPython. |
|
7 | from IPython.extensions import ipy_pretty | |
8 |
|
8 | |||
9 | ipy_pretty.activate() |
|
9 | ipy_pretty.activate() | |
10 |
|
10 | |||
@@ -16,12 +16,12 b' for numpy dtype objects, add the following to your ipy_user_conf.py::' | |||||
16 | ipy_pretty.for_type_by_name('numpy', 'dtype', ipy_pretty.dtype_pprinter) |
|
16 | ipy_pretty.for_type_by_name('numpy', 'dtype', ipy_pretty.dtype_pprinter) | |
17 | """ |
|
17 | """ | |
18 |
|
18 | |||
19 |
|
|
19 | from IPython.core import ipapi | |
20 | from IPython.genutils import Term |
|
20 | from IPython.utils.genutils import Term | |
21 |
|
21 | |||
22 | from IPython.external import pretty |
|
22 | from IPython.external import pretty | |
23 |
|
23 | |||
24 |
ip = |
|
24 | ip = ipapi.get() | |
25 |
|
25 | |||
26 |
|
26 | |||
27 | #### Implementation ############################################################ |
|
27 | #### Implementation ############################################################ | |
@@ -82,7 +82,7 b' def dtype_pprinter(obj, p, cycle):' | |||||
82 |
|
82 | |||
83 | def test_pretty(): |
|
83 | def test_pretty(): | |
84 | """ |
|
84 | """ | |
85 |
In [1]: from IPython. |
|
85 | In [1]: from IPython.extensions import ipy_pretty | |
86 |
|
86 | |||
87 | In [2]: ipy_pretty.activate() |
|
87 | In [2]: ipy_pretty.activate() | |
88 |
|
88 |
@@ -14,9 +14,9 b' similar as possible to the default Python ones, for inclusion in doctests."""' | |||||
14 | # get various stuff that are there for historical / familiarity reasons |
|
14 | # get various stuff that are there for historical / familiarity reasons | |
15 | import ipy_legacy |
|
15 | import ipy_legacy | |
16 |
|
16 | |||
17 |
from |
|
17 | from IPython.core import ipapi | |
18 |
|
18 | |||
19 |
from IPython. |
|
19 | from IPython.extensions import InterpreterPasteInput | |
20 |
|
20 | |||
21 | def main(): |
|
21 | def main(): | |
22 | ip = ipapi.get() |
|
22 | ip = ipapi.get() |
1 | NO CONTENT: file renamed from IPython/Extensions/ipy_profile_none.py to IPython/extensions/ipy_profile_none.py |
|
NO CONTENT: file renamed from IPython/Extensions/ipy_profile_none.py to IPython/extensions/ipy_profile_none.py |
@@ -5,11 +5,11 b' This profile loads the math/cmath modules as well as all of numpy.' | |||||
5 | It exposes numpy via the 'np' shorthand as well for convenience. |
|
5 | It exposes numpy via the 'np' shorthand as well for convenience. | |
6 | """ |
|
6 | """ | |
7 |
|
7 | |||
8 |
|
|
8 | from IPython.core import ipapi | |
9 | import ipy_defaults |
|
9 | import ipy_defaults | |
10 |
|
10 | |||
11 | def main(): |
|
11 | def main(): | |
12 |
ip = |
|
12 | ip = ipapi.get() | |
13 |
|
13 | |||
14 | try: |
|
14 | try: | |
15 | ip.ex("import math,cmath") |
|
15 | ip.ex("import math,cmath") |
@@ -6,11 +6,11 b" It exposes numpy and scipy via the 'np' and 'sp' shorthands as well for" | |||||
6 | convenience. |
|
6 | convenience. | |
7 | """ |
|
7 | """ | |
8 |
|
8 | |||
9 |
|
|
9 | from IPython.core import ipapi | |
10 | import ipy_defaults |
|
10 | import ipy_defaults | |
11 |
|
11 | |||
12 | def main(): |
|
12 | def main(): | |
13 |
ip = |
|
13 | ip = ipapi.get() | |
14 |
|
14 | |||
15 | try: |
|
15 | try: | |
16 | ip.ex("import math,cmath") |
|
16 | ip.ex("import math,cmath") |
@@ -7,7 +7,7 b" shell mode and is recommended for users who don't care about pysh-mode" | |||||
7 | compatibility) |
|
7 | compatibility) | |
8 | """ |
|
8 | """ | |
9 |
|
9 | |||
10 | from IPython import ipapi |
|
10 | from IPython.core import ipapi | |
11 | import os,re,textwrap |
|
11 | import os,re,textwrap | |
12 |
|
12 | |||
13 | # The import below effectively obsoletes your old-style ipythonrc[.ini], |
|
13 | # The import below effectively obsoletes your old-style ipythonrc[.ini], | |
@@ -62,11 +62,11 b' def main():' | |||||
62 | o.prompt_in2= r'\C_Green|\C_LightGreen\D\C_Green> ' |
|
62 | o.prompt_in2= r'\C_Green|\C_LightGreen\D\C_Green> ' | |
63 | o.prompt_out= '<\#> ' |
|
63 | o.prompt_out= '<\#> ' | |
64 |
|
64 | |||
65 |
from IPython import |
|
65 | from IPython.core import release | |
66 |
|
66 | |||
67 | import sys |
|
67 | import sys | |
68 | # Non-chatty banner |
|
68 | # Non-chatty banner | |
69 |
o.banner = "IPython %s [on Py %s]\n" % ( |
|
69 | o.banner = "IPython %s [on Py %s]\n" % (release.version,sys.version.split(None,1)[0]) | |
70 |
|
70 | |||
71 |
|
71 | |||
72 | ip.IP.default_option('cd','-q') |
|
72 | ip.IP.default_option('cd','-q') | |
@@ -156,9 +156,9 b' def slash_prefilter_f(self,line):' | |||||
156 |
|
156 | |||
157 | Removes the need for doing !./foo, !~/foo or !/bin/foo |
|
157 | Removes the need for doing !./foo, !~/foo or !/bin/foo | |
158 | """ |
|
158 | """ | |
159 |
|
|
159 | from IPython.utils import genutils | |
160 | if re.match('(?:[.~]|/[a-zA-Z_0-9]+)/', line): |
|
160 | if re.match('(?:[.~]|/[a-zA-Z_0-9]+)/', line): | |
161 |
return "_ip.system(" + |
|
161 | return "_ip.system(" + genutils.make_quoted_expr(line)+")" | |
162 | raise ipapi.TryNext |
|
162 | raise ipapi.TryNext | |
163 |
|
163 | |||
164 | # XXX You do not need to understand the next function! |
|
164 | # XXX You do not need to understand the next function! | |
@@ -173,8 +173,8 b' def extend_shell_behavior(ip):' | |||||
173 | # mark the IPSHELL with this signature |
|
173 | # mark the IPSHELL with this signature | |
174 | ip.IP.user_ns['__builtins__'].__dict__['__sig__'] = ip.IP.__sig__ |
|
174 | ip.IP.user_ns['__builtins__'].__dict__['__sig__'] = ip.IP.__sig__ | |
175 |
|
175 | |||
176 | from IPython.Itpl import ItplNS |
|
176 | from IPython.external.Itpl import ItplNS | |
177 | from IPython.genutils import shell |
|
177 | from IPython.utils.genutils import shell | |
178 | # utility to expand user variables via Itpl |
|
178 | # utility to expand user variables via Itpl | |
179 | # xxx do something sensible with depth? |
|
179 | # xxx do something sensible with depth? | |
180 | ip.IP.var_expand = lambda cmd, lvars=None, depth=2: \ |
|
180 | ip.IP.var_expand = lambda cmd, lvars=None, depth=2: \ |
@@ -17,8 +17,8 b' Authors' | |||||
17 | # Distributed under the terms of the BSD License. The full license is in |
|
17 | # Distributed under the terms of the BSD License. The full license is in | |
18 | # the file COPYING, distributed as part of this software. |
|
18 | # the file COPYING, distributed as part of this software. | |
19 |
|
19 | |||
20 | from IPython import ipapi |
|
20 | from IPython.core import ipapi | |
21 |
from IPython import |
|
21 | from IPython.core import release | |
22 | from types import StringType |
|
22 | from types import StringType | |
23 | import sys |
|
23 | import sys | |
24 | import os |
|
24 | import os | |
@@ -278,7 +278,8 b' class ZopeDebug(object):' | |||||
278 | zope_debug = None |
|
278 | zope_debug = None | |
279 |
|
279 | |||
280 | def ipy_set_trace(): |
|
280 | def ipy_set_trace(): | |
281 | import IPython; IPython.Debugger.Pdb().set_trace() |
|
281 | from IPython.core import debugger | |
|
282 | debugger.Pdb().set_trace() | |||
282 |
|
283 | |||
283 | def main(): |
|
284 | def main(): | |
284 | global zope_debug |
|
285 | global zope_debug | |
@@ -298,7 +299,7 b' def main():' | |||||
298 | # </HACK ALERT> |
|
299 | # </HACK ALERT> | |
299 |
|
300 | |||
300 | # I like my banner minimal. |
|
301 | # I like my banner minimal. | |
301 |
o.banner = "ZOPE Py %s IPy %s\n" % (sys.version.split('\n')[0], |
|
302 | o.banner = "ZOPE Py %s IPy %s\n" % (sys.version.split('\n')[0],release.version) | |
302 |
|
303 | |||
303 | print textwrap.dedent("""\ |
|
304 | print textwrap.dedent("""\ | |
304 | ZOPE mode iPython shell. |
|
305 | ZOPE mode iPython shell. |
@@ -1,9 +1,9 b'' | |||||
1 | import inspect |
|
1 | import inspect | |
2 |
|
|
2 | from IPython.core import ipapi | |
3 | from IPython.genutils import arg_split |
|
3 | from IPython.utils.genutils import arg_split | |
4 |
ip = |
|
4 | ip = ipapi.get() | |
5 |
|
5 | |||
6 |
from IPython import |
|
6 | from IPython.core import debugger | |
7 |
|
7 | |||
8 | def call_pydb(self, args): |
|
8 | def call_pydb(self, args): | |
9 | """Invoke pydb with the supplied parameters.""" |
|
9 | """Invoke pydb with the supplied parameters.""" | |
@@ -18,7 +18,7 b' def call_pydb(self, args):' | |||||
18 | argl = arg_split(args) |
|
18 | argl = arg_split(args) | |
19 | # print argl # dbg |
|
19 | # print argl # dbg | |
20 | if len(inspect.getargspec(pydb.runv)[0]) == 2: |
|
20 | if len(inspect.getargspec(pydb.runv)[0]) == 2: | |
21 |
pdb = |
|
21 | pdb = debugger.Pdb(color_scheme=self.rc.colors) | |
22 | ip.IP.history_saving_wrapper( lambda : pydb.runv(argl, pdb) )() |
|
22 | ip.IP.history_saving_wrapper( lambda : pydb.runv(argl, pdb) )() | |
23 | else: |
|
23 | else: | |
24 | ip.IP.history_saving_wrapper( lambda : pydb.runv(argl) )() |
|
24 | ip.IP.history_saving_wrapper( lambda : pydb.runv(argl) )() |
@@ -15,8 +15,8 b' extensions are allowed to do that).' | |||||
15 |
|
15 | |||
16 | """ |
|
16 | """ | |
17 |
|
17 | |||
18 |
|
|
18 | from IPython.core import ipapi | |
19 |
ip = |
|
19 | ip = ipapi.get() | |
20 |
|
20 | |||
21 |
|
21 | |||
22 | import os,re,fnmatch,sys |
|
22 | import os,re,fnmatch,sys |
@@ -2,14 +2,14 b'' | |||||
2 |
|
2 | |||
3 | """ IPython extension: Render templates from variables and paste to clipbard """ |
|
3 | """ IPython extension: Render templates from variables and paste to clipbard """ | |
4 |
|
4 | |||
5 |
|
|
5 | from IPython.core import ipapi | |
6 |
|
6 | |||
7 |
ip = |
|
7 | ip = ipapi.get() | |
8 |
|
8 | |||
9 | from string import Template |
|
9 | from string import Template | |
10 | import sys,os |
|
10 | import sys,os | |
11 |
|
11 | |||
12 | from IPython.Itpl import itplns |
|
12 | from IPython.external.Itpl import itplns | |
13 |
|
13 | |||
14 | def toclip_w32(s): |
|
14 | def toclip_w32(s): | |
15 | """ Places contents of s to clipboard |
|
15 | """ Places contents of s to clipboard |
@@ -13,8 +13,8 b' This is a bit like \'M-x server-start" or gnuserv in the emacs world.' | |||||
13 |
|
13 | |||
14 | """ |
|
14 | """ | |
15 |
|
15 | |||
16 |
|
|
16 | from IPython.core import ipapi | |
17 |
ip = |
|
17 | ip = ipapi.get() | |
18 |
|
18 | |||
19 | import SocketServer |
|
19 | import SocketServer | |
20 |
|
20 |
@@ -10,10 +10,10 b' If _ip.options.verbose is true, show exit status if nonzero' | |||||
10 | """ |
|
10 | """ | |
11 |
|
11 | |||
12 | import signal,os,sys |
|
12 | import signal,os,sys | |
13 |
|
|
13 | from IPython.core import ipapi | |
14 | import subprocess |
|
14 | import subprocess | |
15 |
|
15 | |||
16 |
ip = |
|
16 | ip = ipapi.get() | |
17 |
|
17 | |||
18 | def new_ipsystem_posix(cmd): |
|
18 | def new_ipsystem_posix(cmd): | |
19 | """ ctrl+c ignoring replacement for system() command in iplib. |
|
19 | """ ctrl+c ignoring replacement for system() command in iplib. |
@@ -2,12 +2,12 b'' | |||||
2 |
|
2 | |||
3 | IPython extension that installs completers related to core ipython behaviour. |
|
3 | IPython extension that installs completers related to core ipython behaviour. | |
4 |
|
4 | |||
5 |
The actual implementations are in |
|
5 | The actual implementations are in extensions/ipy_completers.py | |
6 |
|
6 | |||
7 | """ |
|
7 | """ | |
8 |
|
|
8 | from IPython.core import ipapi | |
9 |
|
9 | |||
10 |
ip = |
|
10 | ip = ipapi.get() | |
11 |
|
11 | |||
12 | from ipy_completers import * |
|
12 | from ipy_completers import * | |
13 |
|
13 |
@@ -1,5 +1,5 b'' | |||||
1 |
|
|
1 | from IPython.core import ipapi | |
2 |
ip = |
|
2 | ip = ipapi.get() | |
3 |
|
3 | |||
4 | import win32api |
|
4 | import win32api | |
5 | import win32ui |
|
5 | import win32ui |
@@ -7,8 +7,8 b' should reside there.' | |||||
7 |
|
7 | |||
8 | """ |
|
8 | """ | |
9 |
|
9 | |||
10 |
|
|
10 | from IPython.core import ipapi | |
11 |
ip = |
|
11 | ip = ipapi.get() | |
12 |
|
12 | |||
13 | # add system wide configuration information, import extensions etc. here. |
|
13 | # add system wide configuration information, import extensions etc. here. | |
14 | # nothing here is essential |
|
14 | # nothing here is essential | |
@@ -21,4 +21,4 b' import clearcmd # %clear' | |||||
21 |
|
21 | |||
22 | import ipy_stock_completers |
|
22 | import ipy_stock_completers | |
23 |
|
23 | |||
24 | ip.load('IPython.history') |
|
24 | ip.load('IPython.core.history') |
@@ -52,8 +52,8 b' Notes' | |||||
52 | from enthought.traits import api as T |
|
52 | from enthought.traits import api as T | |
53 |
|
53 | |||
54 | # IPython imports |
|
54 | # IPython imports | |
55 | from IPython.ipapi import TryNext, get as ipget |
|
55 | from IPython.core.ipapi import TryNext, get as ipget | |
56 | from IPython.genutils import dir2 |
|
56 | from IPython.utils.genutils import dir2 | |
57 | try: |
|
57 | try: | |
58 | set |
|
58 | set | |
59 | except: |
|
59 | except: |
@@ -67,15 +67,15 b' something. Instead of edit, use the vim magic. Thats it!' | |||||
67 |
|
67 | |||
68 | """ |
|
68 | """ | |
69 |
|
69 | |||
70 |
|
|
70 | from IPython.core import ipapi | |
71 | #import ipythonhooks |
|
71 | ||
72 | import socket, select |
|
72 | import socket, select | |
73 | import os, threading, subprocess |
|
73 | import os, threading, subprocess | |
74 | import re |
|
74 | import re | |
75 |
|
75 | |||
76 | ERRCONDS = select.POLLHUP|select.POLLERR |
|
76 | ERRCONDS = select.POLLHUP|select.POLLERR | |
77 | SERVER = None |
|
77 | SERVER = None | |
78 |
ip = |
|
78 | ip = ipapi.get() | |
79 |
|
79 | |||
80 | # this listens to a unix domain socket in a separate thread, so that comms |
|
80 | # this listens to a unix domain socket in a separate thread, so that comms | |
81 | # between a vim instance and ipython can happen in a fun and productive way |
|
81 | # between a vim instance and ipython can happen in a fun and productive way | |
@@ -161,7 +161,7 b' def shutdown_server(self):' | |||||
161 | if SERVER: |
|
161 | if SERVER: | |
162 | SERVER.stop() |
|
162 | SERVER.stop() | |
163 | SERVER.join(3) |
|
163 | SERVER.join(3) | |
164 |
raise |
|
164 | raise ipapi.TryNext | |
165 |
|
165 | |||
166 | ip.set_hook('shutdown_hook', shutdown_server, 10) |
|
166 | ip.set_hook('shutdown_hook', shutdown_server, 10) | |
167 |
|
167 |
@@ -4,8 +4,8 b' r""" %which magic command' | |||||
4 |
|
4 | |||
5 | """ |
|
5 | """ | |
6 |
|
6 | |||
7 |
|
|
7 | from IPython.core import ipapi | |
8 |
ip = |
|
8 | ip = ipapi.get() | |
9 |
|
9 | |||
10 | import os,sys |
|
10 | import os,sys | |
11 | from fnmatch import fnmatch |
|
11 | from fnmatch import fnmatch |
@@ -21,10 +21,10 b' For more details: https://bugs.launchpad.net/ipython/+bug/249036' | |||||
21 |
|
21 | |||
22 | import os |
|
22 | import os | |
23 |
|
23 | |||
24 |
|
|
24 | from IPython.core import ipapi | |
25 | import rpdb2 |
|
25 | import rpdb2 | |
26 |
|
26 | |||
27 |
ip = |
|
27 | ip = ipapi.get() | |
28 |
|
28 | |||
29 | rpdb_started = False |
|
29 | rpdb_started = False | |
30 |
|
30 | |||
@@ -58,7 +58,7 b' def wdb_f(self, arg):' | |||||
58 |
|
58 | |||
59 | path = os.path.abspath(arg) |
|
59 | path = os.path.abspath(arg) | |
60 | if not os.path.isfile(path): |
|
60 | if not os.path.isfile(path): | |
61 |
raise |
|
61 | raise ipapi.UsageError("%%wdb: file %s does not exist" % path) | |
62 | if not rpdb_started: |
|
62 | if not rpdb_started: | |
63 | passwd = ip.db.get('winpdb_pass', None) |
|
63 | passwd = ip.db.get('winpdb_pass', None) | |
64 | if passwd is None: |
|
64 | if passwd is None: |
@@ -1,7 +1,7 b'' | |||||
1 | #!/usr/bin/env python |
|
1 | #!/usr/bin/env python | |
2 |
|
2 | |||
3 |
|
|
3 | from IPython.core import ipapi | |
4 |
ip = |
|
4 | ip = ipapi.get() | |
5 |
|
5 | |||
6 | import os, subprocess |
|
6 | import os, subprocess | |
7 |
|
7 |
@@ -45,9 +45,9 b' from subprocess import *' | |||||
45 | import os,shlex,sys,time |
|
45 | import os,shlex,sys,time | |
46 | import threading,Queue |
|
46 | import threading,Queue | |
47 |
|
47 | |||
48 | from IPython import genutils |
|
48 | from IPython.utils import genutils | |
49 |
|
49 | |||
50 |
|
|
50 | from IPython.core import ipapi | |
51 |
|
51 | |||
52 | if os.name == 'nt': |
|
52 | if os.name == 'nt': | |
53 | def kill_process(pid): |
|
53 | def kill_process(pid): | |
@@ -128,7 +128,7 b' def jobctrl_prefilter_f(self,line):' | |||||
128 | return '_ip.startjob(%s)' % genutils.make_quoted_expr(line) |
|
128 | return '_ip.startjob(%s)' % genutils.make_quoted_expr(line) | |
129 | return '_ip.jobq(%s)' % genutils.make_quoted_expr(line) |
|
129 | return '_ip.jobq(%s)' % genutils.make_quoted_expr(line) | |
130 |
|
130 | |||
131 |
raise |
|
131 | raise ipapi.TryNext | |
132 |
|
132 | |||
133 | def jobq_output_hook(self): |
|
133 | def jobq_output_hook(self): | |
134 | if not _jobq: |
|
134 | if not _jobq: | |
@@ -230,7 +230,7 b' def jobctrl_shellcmd(ip,cmd):' | |||||
230 |
|
230 | |||
231 | def install(): |
|
231 | def install(): | |
232 | global ip |
|
232 | global ip | |
233 |
ip = |
|
233 | ip = ipapi.get() | |
234 | # needed to make startjob visible as _ip.startjob('blah') |
|
234 | # needed to make startjob visible as _ip.startjob('blah') | |
235 | ip.startjob = startjob |
|
235 | ip.startjob = startjob | |
236 | ip.set_hook('input_prefilter', jobctrl_prefilter_f) |
|
236 | ip.set_hook('input_prefilter', jobctrl_prefilter_f) |
@@ -43,9 +43,9 b' l.__class__ l.__hash__ l.__repr__ l.expandtabs l.lj' | |||||
43 | ... (completions for string variable shown ) ... |
|
43 | ... (completions for string variable shown ) ... | |
44 |
|
44 | |||
45 | """ |
|
45 | """ | |
46 |
|
|
46 | from IPython.core import ipapi | |
47 | import pprint |
|
47 | import pprint | |
48 |
ip = |
|
48 | ip = ipapi.get() | |
49 |
|
49 | |||
50 | curdata = [] |
|
50 | curdata = [] | |
51 |
|
51 |
1 | NO CONTENT: file renamed from IPython/Extensions/numeric_formats.py to IPython/extensions/numeric_formats.py |
|
NO CONTENT: file renamed from IPython/Extensions/numeric_formats.py to IPython/extensions/numeric_formats.py |
1 | NO CONTENT: file renamed from IPython/Extensions/pickleshare.py to IPython/extensions/pickleshare.py |
|
NO CONTENT: file renamed from IPython/Extensions/pickleshare.py to IPython/extensions/pickleshare.py |
@@ -5,14 +5,14 b'' | |||||
5 | Stores variables, aliases etc. in PickleShare database. |
|
5 | Stores variables, aliases etc. in PickleShare database. | |
6 | """ |
|
6 | """ | |
7 |
|
7 | |||
8 |
|
|
8 | from IPython.core import ipapi | |
9 | from IPython.ipapi import UsageError |
|
9 | from IPython.core.ipapi import UsageError | |
10 |
ip = |
|
10 | ip = ipapi.get() | |
11 |
|
11 | |||
12 | import pickleshare |
|
12 | import pickleshare | |
13 |
|
13 | |||
14 | import inspect,pickle,os,sys,textwrap |
|
14 | import inspect,pickle,os,sys,textwrap | |
15 |
from IPython. |
|
15 | from IPython.core.fakemodule import FakeModule | |
16 |
|
16 | |||
17 | def restore_aliases(self): |
|
17 | def restore_aliases(self): | |
18 | ip = self.getapi() |
|
18 | ip = self.getapi() | |
@@ -47,7 +47,7 b' def restore_data(self):' | |||||
47 | refresh_variables(ip) |
|
47 | refresh_variables(ip) | |
48 | restore_aliases(self) |
|
48 | restore_aliases(self) | |
49 | restore_dhist(self) |
|
49 | restore_dhist(self) | |
50 |
raise |
|
50 | raise ipapi.TryNext | |
51 |
|
51 | |||
52 | ip.set_hook('late_startup_hook', restore_data) |
|
52 | ip.set_hook('late_startup_hook', restore_data) | |
53 |
|
53 |
1 | NO CONTENT: file renamed from IPython/Extensions/scitedirector.py to IPython/extensions/scitedirector.py |
|
NO CONTENT: file renamed from IPython/Extensions/scitedirector.py to IPython/extensions/scitedirector.py |
@@ -1,6 +1,6 b'' | |||||
1 |
|
|
1 | from IPython.core import ipapi | |
2 |
|
2 | |||
3 |
ip = |
|
3 | ip = ipapi.get() | |
4 |
|
4 | |||
5 | def clip_f( self, parameter_s = '' ): |
|
5 | def clip_f( self, parameter_s = '' ): | |
6 | """Save a set of lines to the clipboard. |
|
6 | """Save a set of lines to the clipboard. |
@@ -213,7 +213,7 b' def main():' | |||||
213 | print "\n".join(expand(sys.argv[1:])), |
|
213 | print "\n".join(expand(sys.argv[1:])), | |
214 |
|
214 | |||
215 | def mglob_f(self, arg): |
|
215 | def mglob_f(self, arg): | |
216 | from IPython.genutils import SList |
|
216 | from IPython.utils.genutils import SList | |
217 | if arg.strip(): |
|
217 | if arg.strip(): | |
218 | return SList(expand(arg)) |
|
218 | return SList(expand(arg)) | |
219 | print "Please specify pattern!" |
|
219 | print "Please specify pattern!" |
@@ -27,13 +27,13 b' import os' | |||||
27 | import re |
|
27 | import re | |
28 | import __builtin__ |
|
28 | import __builtin__ | |
29 |
|
29 | |||
30 | from IPython.ipmaker import make_IPython |
|
30 | from IPython.core.ipmaker import make_IPython | |
31 | from IPython.ipapi import IPApi |
|
31 | from IPython.core.ipapi import IPApi | |
32 | from IPython.kernel.core.redirector_output_trap import RedirectorOutputTrap |
|
32 | from IPython.kernel.core.redirector_output_trap import RedirectorOutputTrap | |
33 |
|
33 | |||
34 | from IPython.kernel.core.sync_traceback_trap import SyncTracebackTrap |
|
34 | from IPython.kernel.core.sync_traceback_trap import SyncTracebackTrap | |
35 |
|
35 | |||
36 | from IPython.genutils import Term |
|
36 | from IPython.utils.genutils import Term | |
37 |
|
37 | |||
38 | from linefrontendbase import LineFrontEndBase, common_prefix |
|
38 | from linefrontendbase import LineFrontEndBase, common_prefix | |
39 |
|
39 | |||
@@ -80,7 +80,7 b' class PrefilterFrontEnd(LineFrontEndBase):' | |||||
80 | # on exceptions (https://bugs.launchpad.net/bugs/337105) |
|
80 | # on exceptions (https://bugs.launchpad.net/bugs/337105) | |
81 | # XXX: This is horrible: module-leve monkey patching -> side |
|
81 | # XXX: This is horrible: module-leve monkey patching -> side | |
82 | # effects. |
|
82 | # effects. | |
83 | from IPython import iplib |
|
83 | from IPython.core import iplib | |
84 | iplib.InteractiveShell.isthreaded = True |
|
84 | iplib.InteractiveShell.isthreaded = True | |
85 |
|
85 | |||
86 | LineFrontEndBase.__init__(self, *args, **kwargs) |
|
86 | LineFrontEndBase.__init__(self, *args, **kwargs) |
@@ -20,7 +20,7 b' import sys' | |||||
20 | from nose.tools import assert_equal |
|
20 | from nose.tools import assert_equal | |
21 |
|
21 | |||
22 | from IPython.frontend.prefilterfrontend import PrefilterFrontEnd |
|
22 | from IPython.frontend.prefilterfrontend import PrefilterFrontEnd | |
23 | from IPython.ipapi import get as get_ipython0 |
|
23 | from IPython.core.ipapi import get as get_ipython0 | |
24 | from IPython.testing.plugin.ipdoctest import default_argv |
|
24 | from IPython.testing.plugin.ipdoctest import default_argv | |
25 |
|
25 | |||
26 |
|
26 | |||
@@ -86,7 +86,7 b' def isolate_ipython0(func):' | |||||
86 | for k in new_globals: |
|
86 | for k in new_globals: | |
87 | del user_global_ns[k] |
|
87 | del user_global_ns[k] | |
88 | # Undo the hack at creation of PrefilterFrontEnd |
|
88 | # Undo the hack at creation of PrefilterFrontEnd | |
89 | from IPython import iplib |
|
89 | from IPython.core import iplib | |
90 | iplib.InteractiveShell.isthreaded = False |
|
90 | iplib.InteractiveShell.isthreaded = False | |
91 | return out |
|
91 | return out | |
92 |
|
92 |
@@ -105,8 +105,8 b" ANSI_STYLES = {'0;30': [0, 'BLACK'], '0;31': [1, 'RED']," | |||||
105 | [13, 'MEDIUM VIOLET RED'], |
|
105 | [13, 'MEDIUM VIOLET RED'], | |
106 | '1;36': [14, 'LIGHT STEEL BLUE'], '1;37': [15, 'YELLOW']} |
|
106 | '1;36': [14, 'LIGHT STEEL BLUE'], '1;37': [15, 'YELLOW']} | |
107 |
|
107 | |||
108 |
# XXX: Maybe one day we should factor this code with |
|
108 | # XXX: Maybe one day we should factor this code with coloransi. Right now | |
109 |
# |
|
109 | # coloransi is hard to reuse and makes our code more complex. | |
110 |
|
110 | |||
111 | #we define platform specific fonts |
|
111 | #we define platform specific fonts | |
112 | if wx.Platform == '__WXMSW__': |
|
112 | if wx.Platform == '__WXMSW__': |
@@ -25,6 +25,8 b' from thread_ex import ThreadEx' | |||||
25 |
|
25 | |||
26 | try: |
|
26 | try: | |
27 | import IPython |
|
27 | import IPython | |
|
28 | from IPython.utils import genutils | |||
|
29 | from IPython.core import iplib | |||
28 | except Exception,e: |
|
30 | except Exception,e: | |
29 | print "Error importing IPython (%s)" % str(e) |
|
31 | print "Error importing IPython (%s)" % str(e) | |
30 | raise Exception, e |
|
32 | raise Exception, e | |
@@ -143,22 +145,22 b' class NonBlockingIPShell(object):' | |||||
143 | #only one instance can be instanciated else tehre will be |
|
145 | #only one instance can be instanciated else tehre will be | |
144 | #cin/cout/cerr clash... |
|
146 | #cin/cout/cerr clash... | |
145 | if cin: |
|
147 | if cin: | |
146 |
|
|
148 | genutils.Term.cin = cin | |
147 | if cout: |
|
149 | if cout: | |
148 |
|
|
150 | genutils.Term.cout = cout | |
149 | if cerr: |
|
151 | if cerr: | |
150 |
|
|
152 | genutils.Term.cerr = cerr | |
151 |
|
153 | |||
152 | excepthook = sys.excepthook |
|
154 | excepthook = sys.excepthook | |
153 |
|
155 | |||
154 | #Hack to save sys.displayhook, because ipython seems to overwrite it... |
|
156 | #Hack to save sys.displayhook, because ipython seems to overwrite it... | |
155 | self.sys_displayhook_ori = sys.displayhook |
|
157 | self.sys_displayhook_ori = sys.displayhook | |
156 |
|
158 | |||
157 |
self._IP = IPython. |
|
159 | self._IP = IPython.shell.make_IPython( | |
158 | argv,user_ns=user_ns, |
|
160 | argv,user_ns=user_ns, | |
159 | user_global_ns=user_global_ns, |
|
161 | user_global_ns=user_global_ns, | |
160 | embedded=True, |
|
162 | embedded=True, | |
161 |
shell_class=IPython. |
|
163 | shell_class=IPython.shell.InteractiveShell) | |
162 |
|
164 | |||
163 | #we save ipython0 displayhook and we restore sys.displayhook |
|
165 | #we save ipython0 displayhook and we restore sys.displayhook | |
164 | self.displayhook = sys.displayhook |
|
166 | self.displayhook = sys.displayhook | |
@@ -176,15 +178,15 b' class NonBlockingIPShell(object):' | |||||
176 | self._IP.set_hook('shell_hook', self._shell) |
|
178 | self._IP.set_hook('shell_hook', self._shell) | |
177 |
|
179 | |||
178 | #we replace the ipython default input command caller by our method |
|
180 | #we replace the ipython default input command caller by our method | |
179 |
|
|
181 | iplib.raw_input_original = self._raw_input_original | |
180 | #we replace the ipython default exit command by our method |
|
182 | #we replace the ipython default exit command by our method | |
181 | self._IP.exit = ask_exit_handler |
|
183 | self._IP.exit = ask_exit_handler | |
182 | #we replace the help command |
|
184 | #we replace the help command | |
183 | self._IP.user_ns['help'] = _Helper(self._pager_help) |
|
185 | self._IP.user_ns['help'] = _Helper(self._pager_help) | |
184 |
|
186 | |||
185 | #we disable cpase magic... until we found a way to use it properly. |
|
187 | #we disable cpase magic... until we found a way to use it properly. | |
186 |
|
|
188 | from IPython.core import ipapi | |
187 |
ip = |
|
189 | ip = ipapi.get() | |
188 | def bypass_magic(self, arg): |
|
190 | def bypass_magic(self, arg): | |
189 | print '%this magic is currently disabled.' |
|
191 | print '%this magic is currently disabled.' | |
190 | ip.expose_magic('cpaste', bypass_magic) |
|
192 | ip.expose_magic('cpaste', bypass_magic) | |
@@ -468,7 +470,7 b' class NonBlockingIPShell(object):' | |||||
468 | ''' |
|
470 | ''' | |
469 |
|
471 | |||
470 | orig_stdout = sys.stdout |
|
472 | orig_stdout = sys.stdout | |
471 |
sys.stdout = IPython. |
|
473 | sys.stdout = IPython.shell.Term.cout | |
472 | #self.sys_displayhook_ori = sys.displayhook |
|
474 | #self.sys_displayhook_ori = sys.displayhook | |
473 | #sys.displayhook = self.displayhook |
|
475 | #sys.displayhook = self.displayhook | |
474 |
|
476 |
@@ -19,7 +19,7 b' except ImportError:' | |||||
19 | is_sync_frontend_ok = False |
|
19 | is_sync_frontend_ok = False | |
20 |
|
20 | |||
21 | #used to create options.conf file in user directory |
|
21 | #used to create options.conf file in user directory | |
22 | from IPython.ipapi import get |
|
22 | from IPython.core.ipapi import get | |
23 |
|
23 | |||
24 | __version__ = 0.91 |
|
24 | __version__ = 0.91 | |
25 | __author__ = "Laurent Dufrechou" |
|
25 | __author__ = "Laurent Dufrechou" |
This diff has been collapsed as it changes many lines, (694 lines changed) Show them Hide them | |||||
@@ -1,685 +1,29 b'' | |||||
1 | """IPython customization API |
|
1 | #!/usr/bin/env python | |
2 |
|
2 | # encoding: utf-8 | ||
3 | Your one-stop module for configuring & extending ipython |
|
3 | """ | |
4 |
|
4 | A backwards compatibility layer for IPython.ipapi. | ||
5 | The API will probably break when ipython 1.0 is released, but so |
|
|||
6 | will the other configuration method (rc files). |
|
|||
7 |
|
||||
8 | All names prefixed by underscores are for internal use, not part |
|
|||
9 | of the public api. |
|
|||
10 |
|
||||
11 | Below is an example that you can just put to a module and import from ipython. |
|
|||
12 |
|
||||
13 | A good practice is to install the config script below as e.g. |
|
|||
14 |
|
||||
15 | ~/.ipython/my_private_conf.py |
|
|||
16 |
|
||||
17 | And do |
|
|||
18 |
|
||||
19 | import_mod my_private_conf |
|
|||
20 |
|
||||
21 | in ~/.ipython/ipythonrc |
|
|||
22 |
|
||||
23 | That way the module is imported at startup and you can have all your |
|
|||
24 | personal configuration (as opposed to boilerplate ipythonrc-PROFILENAME |
|
|||
25 | stuff) in there. |
|
|||
26 |
|
||||
27 | import IPython.ipapi |
|
|||
28 | ip = IPython.ipapi.get() |
|
|||
29 |
|
||||
30 | def ankka_f(self, arg): |
|
|||
31 | print 'Ankka',self,'says uppercase:',arg.upper() |
|
|||
32 |
|
||||
33 | ip.expose_magic('ankka',ankka_f) |
|
|||
34 |
|
||||
35 | ip.magic('alias sayhi echo "Testing, hi ok"') |
|
|||
36 | ip.magic('alias helloworld echo "Hello world"') |
|
|||
37 | ip.system('pwd') |
|
|||
38 |
|
||||
39 | ip.ex('import re') |
|
|||
40 | ip.ex(''' |
|
|||
41 | def funcci(a,b): |
|
|||
42 | print a+b |
|
|||
43 | print funcci(3,4) |
|
|||
44 | ''') |
|
|||
45 | ip.ex('funcci(348,9)') |
|
|||
46 |
|
||||
47 | def jed_editor(self,filename, linenum=None): |
|
|||
48 | print 'Calling my own editor, jed ... via hook!' |
|
|||
49 | import os |
|
|||
50 | if linenum is None: linenum = 0 |
|
|||
51 | os.system('jed +%d %s' % (linenum, filename)) |
|
|||
52 | print 'exiting jed' |
|
|||
53 |
|
||||
54 | ip.set_hook('editor',jed_editor) |
|
|||
55 |
|
||||
56 | o = ip.options |
|
|||
57 | o.autocall = 2 # FULL autocall mode |
|
|||
58 |
|
5 | |||
59 | print 'done!' |
|
6 | Previously, IPython had an IPython.ipapi module. IPython.ipapi has been moved | |
|
7 | to IPython.core.ipapi and is being refactored. This new module is provided | |||
|
8 | for backwards compatability. We strongly encourage everyone to start using | |||
|
9 | the new code in IPython.core.ipapi. | |||
60 | """ |
|
10 | """ | |
61 |
|
11 | |||
62 | #----------------------------------------------------------------------------- |
|
12 | #----------------------------------------------------------------------------- | |
63 | # Modules and globals |
|
13 | # Copyright (C) 2008-2009 The IPython Development Team | |
64 |
|
14 | # | ||
65 | # stdlib imports |
|
15 | # Distributed under the terms of the BSD License. The full license is in | |
66 | import __builtin__ |
|
16 | # the file COPYING, distributed as part of this software. | |
67 | import sys |
|
|||
68 |
|
||||
69 | # contains the most recently instantiated IPApi |
|
|||
70 | _RECENT_IP = None |
|
|||
71 |
|
||||
72 | #----------------------------------------------------------------------------- |
|
17 | #----------------------------------------------------------------------------- | |
73 | # Code begins |
|
|||
74 |
|
||||
75 | class TryNext(Exception): |
|
|||
76 | """Try next hook exception. |
|
|||
77 |
|
||||
78 | Raise this in your hook function to indicate that the next hook handler |
|
|||
79 | should be used to handle the operation. If you pass arguments to the |
|
|||
80 | constructor those arguments will be used by the next hook instead of the |
|
|||
81 | original ones. |
|
|||
82 | """ |
|
|||
83 |
|
||||
84 | def __init__(self, *args, **kwargs): |
|
|||
85 | self.args = args |
|
|||
86 | self.kwargs = kwargs |
|
|||
87 |
|
||||
88 |
|
||||
89 | class UsageError(Exception): |
|
|||
90 | """ Error in magic function arguments, etc. |
|
|||
91 |
|
||||
92 | Something that probably won't warrant a full traceback, but should |
|
|||
93 | nevertheless interrupt a macro / batch file. |
|
|||
94 | """ |
|
|||
95 |
|
||||
96 |
|
||||
97 | class IPyAutocall: |
|
|||
98 | """ Instances of this class are always autocalled |
|
|||
99 |
|
||||
100 | This happens regardless of 'autocall' variable state. Use this to |
|
|||
101 | develop macro-like mechanisms. |
|
|||
102 | """ |
|
|||
103 |
|
||||
104 | def set_ip(self,ip): |
|
|||
105 | """ Will be used to set _ip point to current ipython instance b/f call |
|
|||
106 |
|
||||
107 | Override this method if you don't want this to happen. |
|
|||
108 |
|
||||
109 | """ |
|
|||
110 | self._ip = ip |
|
|||
111 |
|
||||
112 |
|
||||
113 | class IPythonNotRunning: |
|
|||
114 | """Dummy do-nothing class. |
|
|||
115 |
|
||||
116 | Instances of this class return a dummy attribute on all accesses, which |
|
|||
117 | can be called and warns. This makes it easier to write scripts which use |
|
|||
118 | the ipapi.get() object for informational purposes to operate both with and |
|
|||
119 | without ipython. Obviously code which uses the ipython object for |
|
|||
120 | computations will not work, but this allows a wider range of code to |
|
|||
121 | transparently work whether ipython is being used or not.""" |
|
|||
122 |
|
||||
123 | def __init__(self,warn=True): |
|
|||
124 | if warn: |
|
|||
125 | self.dummy = self._dummy_warn |
|
|||
126 | else: |
|
|||
127 | self.dummy = self._dummy_silent |
|
|||
128 |
|
||||
129 | def __str__(self): |
|
|||
130 | return "<IPythonNotRunning>" |
|
|||
131 |
|
||||
132 | __repr__ = __str__ |
|
|||
133 |
|
||||
134 | def __getattr__(self,name): |
|
|||
135 | return self.dummy |
|
|||
136 |
|
||||
137 | def _dummy_warn(self,*args,**kw): |
|
|||
138 | """Dummy function, which doesn't do anything but warn.""" |
|
|||
139 |
|
||||
140 | print ("IPython is not running, this is a dummy no-op function") |
|
|||
141 |
|
||||
142 | def _dummy_silent(self,*args,**kw): |
|
|||
143 | """Dummy function, which doesn't do anything and emits no warnings.""" |
|
|||
144 | pass |
|
|||
145 |
|
||||
146 |
|
||||
147 | def get(allow_dummy=False,dummy_warn=True): |
|
|||
148 | """Get an IPApi object. |
|
|||
149 |
|
||||
150 | If allow_dummy is true, returns an instance of IPythonNotRunning |
|
|||
151 | instead of None if not running under IPython. |
|
|||
152 |
|
||||
153 | If dummy_warn is false, the dummy instance will be completely silent. |
|
|||
154 |
|
||||
155 | Running this should be the first thing you do when writing extensions that |
|
|||
156 | can be imported as normal modules. You can then direct all the |
|
|||
157 | configuration operations against the returned object. |
|
|||
158 | """ |
|
|||
159 | global _RECENT_IP |
|
|||
160 | if allow_dummy and not _RECENT_IP: |
|
|||
161 | _RECENT_IP = IPythonNotRunning(dummy_warn) |
|
|||
162 | return _RECENT_IP |
|
|||
163 |
|
||||
164 |
|
||||
165 | class IPApi(object): |
|
|||
166 | """ The actual API class for configuring IPython |
|
|||
167 |
|
||||
168 | You should do all of the IPython configuration by getting an IPApi object |
|
|||
169 | with IPython.ipapi.get() and using the attributes and methods of the |
|
|||
170 | returned object.""" |
|
|||
171 |
|
||||
172 | def __init__(self,ip): |
|
|||
173 |
|
||||
174 | global _RECENT_IP |
|
|||
175 |
|
||||
176 | # All attributes exposed here are considered to be the public API of |
|
|||
177 | # IPython. As needs dictate, some of these may be wrapped as |
|
|||
178 | # properties. |
|
|||
179 |
|
||||
180 | self.magic = ip.ipmagic |
|
|||
181 |
|
||||
182 | self.system = ip.system |
|
|||
183 |
|
||||
184 | self.set_hook = ip.set_hook |
|
|||
185 |
|
||||
186 | self.set_custom_exc = ip.set_custom_exc |
|
|||
187 |
|
||||
188 | self.user_ns = ip.user_ns |
|
|||
189 |
|
||||
190 | self.set_crash_handler = ip.set_crash_handler |
|
|||
191 |
|
||||
192 | # Session-specific data store, which can be used to store |
|
|||
193 | # data that should persist through the ipython session. |
|
|||
194 | self.meta = ip.meta |
|
|||
195 |
|
||||
196 | # The ipython instance provided |
|
|||
197 | self.IP = ip |
|
|||
198 |
|
||||
199 | self.extensions = {} |
|
|||
200 |
|
||||
201 | self.dbg = DebugTools(self) |
|
|||
202 |
|
||||
203 | _RECENT_IP = self |
|
|||
204 |
|
||||
205 | # Use a property for some things which are added to the instance very |
|
|||
206 | # late. I don't have time right now to disentangle the initialization |
|
|||
207 | # order issues, so a property lets us delay item extraction while |
|
|||
208 | # providing a normal attribute API. |
|
|||
209 | def get_db(self): |
|
|||
210 | """A handle to persistent dict-like database (a PickleShareDB object)""" |
|
|||
211 | return self.IP.db |
|
|||
212 |
|
||||
213 | db = property(get_db,None,None,get_db.__doc__) |
|
|||
214 |
|
||||
215 | def get_options(self): |
|
|||
216 | """All configurable variables.""" |
|
|||
217 |
|
||||
218 | # catch typos by disabling new attribute creation. If new attr creation |
|
|||
219 | # is in fact wanted (e.g. when exposing new options), do |
|
|||
220 | # allow_new_attr(True) for the received rc struct. |
|
|||
221 |
|
||||
222 | self.IP.rc.allow_new_attr(False) |
|
|||
223 | return self.IP.rc |
|
|||
224 |
|
||||
225 | options = property(get_options,None,None,get_options.__doc__) |
|
|||
226 |
|
||||
227 | def expose_magic(self,magicname, func): |
|
|||
228 | """Expose own function as magic function for ipython |
|
|||
229 |
|
||||
230 | def foo_impl(self,parameter_s=''): |
|
|||
231 | 'My very own magic!. (Use docstrings, IPython reads them).' |
|
|||
232 | print 'Magic function. Passed parameter is between < >:' |
|
|||
233 | print '<%s>' % parameter_s |
|
|||
234 | print 'The self object is:',self |
|
|||
235 |
|
||||
236 | ipapi.expose_magic('foo',foo_impl) |
|
|||
237 | """ |
|
|||
238 |
|
||||
239 | import new |
|
|||
240 | im = new.instancemethod(func,self.IP, self.IP.__class__) |
|
|||
241 | old = getattr(self.IP, "magic_" + magicname, None) |
|
|||
242 | if old: |
|
|||
243 | self.dbg.debug_stack("Magic redefinition '%s', old %s" % |
|
|||
244 | (magicname,old) ) |
|
|||
245 |
|
||||
246 | setattr(self.IP, "magic_" + magicname, im) |
|
|||
247 |
|
||||
248 | def ex(self,cmd): |
|
|||
249 | """ Execute a normal python statement in user namespace """ |
|
|||
250 | exec cmd in self.user_ns |
|
|||
251 |
|
||||
252 | def ev(self,expr): |
|
|||
253 | """ Evaluate python expression expr in user namespace |
|
|||
254 |
|
||||
255 | Returns the result of evaluation""" |
|
|||
256 | return eval(expr,self.user_ns) |
|
|||
257 |
|
||||
258 | def runlines(self,lines): |
|
|||
259 | """ Run the specified lines in interpreter, honoring ipython directives. |
|
|||
260 |
|
||||
261 | This allows %magic and !shell escape notations. |
|
|||
262 |
|
||||
263 | Takes either all lines in one string or list of lines. |
|
|||
264 | """ |
|
|||
265 |
|
||||
266 | def cleanup_ipy_script(script): |
|
|||
267 | """ Make a script safe for _ip.runlines() |
|
|||
268 |
|
||||
269 | - Removes empty lines Suffixes all indented blocks that end with |
|
|||
270 | - unindented lines with empty lines |
|
|||
271 | """ |
|
|||
272 |
|
||||
273 | res = [] |
|
|||
274 | lines = script.splitlines() |
|
|||
275 |
|
||||
276 | level = 0 |
|
|||
277 | for l in lines: |
|
|||
278 | lstripped = l.lstrip() |
|
|||
279 | stripped = l.strip() |
|
|||
280 | if not stripped: |
|
|||
281 | continue |
|
|||
282 | newlevel = len(l) - len(lstripped) |
|
|||
283 | def is_secondary_block_start(s): |
|
|||
284 | if not s.endswith(':'): |
|
|||
285 | return False |
|
|||
286 | if (s.startswith('elif') or |
|
|||
287 | s.startswith('else') or |
|
|||
288 | s.startswith('except') or |
|
|||
289 | s.startswith('finally')): |
|
|||
290 | return True |
|
|||
291 |
|
||||
292 | if level > 0 and newlevel == 0 and \ |
|
|||
293 | not is_secondary_block_start(stripped): |
|
|||
294 | # add empty line |
|
|||
295 | res.append('') |
|
|||
296 |
|
||||
297 | res.append(l) |
|
|||
298 | level = newlevel |
|
|||
299 | return '\n'.join(res) + '\n' |
|
|||
300 |
|
||||
301 | if isinstance(lines,basestring): |
|
|||
302 | script = lines |
|
|||
303 | else: |
|
|||
304 | script = '\n'.join(lines) |
|
|||
305 | clean=cleanup_ipy_script(script) |
|
|||
306 | # print "_ip.runlines() script:\n",clean # dbg |
|
|||
307 | self.IP.runlines(clean) |
|
|||
308 |
|
||||
309 | def to_user_ns(self,vars, interactive = True): |
|
|||
310 | """Inject a group of variables into the IPython user namespace. |
|
|||
311 |
|
||||
312 | Inputs: |
|
|||
313 |
|
||||
314 | - vars: string with variable names separated by whitespace, or a |
|
|||
315 | dict with name/value pairs. |
|
|||
316 |
|
||||
317 | - interactive: if True (default), the var will be listed with |
|
|||
318 | %whos et. al. |
|
|||
319 |
|
||||
320 | This utility routine is meant to ease interactive debugging work, |
|
|||
321 | where you want to easily propagate some internal variable in your code |
|
|||
322 | up to the interactive namespace for further exploration. |
|
|||
323 |
|
||||
324 | When you run code via %run, globals in your script become visible at |
|
|||
325 | the interactive prompt, but this doesn't happen for locals inside your |
|
|||
326 | own functions and methods. Yet when debugging, it is common to want |
|
|||
327 | to explore some internal variables further at the interactive propmt. |
|
|||
328 |
|
||||
329 | Examples: |
|
|||
330 |
|
||||
331 | To use this, you first must obtain a handle on the ipython object as |
|
|||
332 | indicated above, via: |
|
|||
333 |
|
||||
334 | import IPython.ipapi |
|
|||
335 | ip = IPython.ipapi.get() |
|
|||
336 |
|
||||
337 | Once this is done, inside a routine foo() where you want to expose |
|
|||
338 | variables x and y, you do the following: |
|
|||
339 |
|
||||
340 | def foo(): |
|
|||
341 | ... |
|
|||
342 | x = your_computation() |
|
|||
343 | y = something_else() |
|
|||
344 |
|
||||
345 | # This pushes x and y to the interactive prompt immediately, even |
|
|||
346 | # if this routine crashes on the next line after: |
|
|||
347 | ip.to_user_ns('x y') |
|
|||
348 | ... |
|
|||
349 |
|
||||
350 | # To expose *ALL* the local variables from the function, use: |
|
|||
351 | ip.to_user_ns(locals()) |
|
|||
352 |
|
||||
353 | ... |
|
|||
354 | # return |
|
|||
355 |
|
||||
356 |
|
||||
357 | If you need to rename variables, the dict input makes it easy. For |
|
|||
358 | example, this call exposes variables 'foo' as 'x' and 'bar' as 'y' |
|
|||
359 | in IPython user namespace: |
|
|||
360 |
|
||||
361 | ip.to_user_ns(dict(x=foo,y=bar)) |
|
|||
362 | """ |
|
|||
363 |
|
||||
364 | # print 'vars given:',vars # dbg |
|
|||
365 |
|
||||
366 | # We need a dict of name/value pairs to do namespace updates. |
|
|||
367 | if isinstance(vars,dict): |
|
|||
368 | # If a dict was given, no need to change anything. |
|
|||
369 | vdict = vars |
|
|||
370 | elif isinstance(vars,basestring): |
|
|||
371 | # If a string with names was given, get the caller's frame to |
|
|||
372 | # evaluate the given names in |
|
|||
373 | cf = sys._getframe(1) |
|
|||
374 | vdict = {} |
|
|||
375 | for name in vars.split(): |
|
|||
376 | try: |
|
|||
377 | vdict[name] = eval(name,cf.f_globals,cf.f_locals) |
|
|||
378 | except: |
|
|||
379 | print ('could not get var. %s from %s' % |
|
|||
380 | (name,cf.f_code.co_name)) |
|
|||
381 | else: |
|
|||
382 | raise ValueError('vars must be a string or a dict') |
|
|||
383 |
|
||||
384 | # Propagate variables to user namespace |
|
|||
385 | self.user_ns.update(vdict) |
|
|||
386 |
|
||||
387 | # And configure interactive visibility |
|
|||
388 | config_ns = self.IP.user_config_ns |
|
|||
389 | if interactive: |
|
|||
390 | for name,val in vdict.iteritems(): |
|
|||
391 | config_ns.pop(name,None) |
|
|||
392 | else: |
|
|||
393 | for name,val in vdict.iteritems(): |
|
|||
394 | config_ns[name] = val |
|
|||
395 |
|
||||
396 | def expand_alias(self,line): |
|
|||
397 | """ Expand an alias in the command line |
|
|||
398 |
|
||||
399 | Returns the provided command line, possibly with the first word |
|
|||
400 | (command) translated according to alias expansion rules. |
|
|||
401 |
|
||||
402 | [ipython]|16> _ip.expand_aliases("np myfile.txt") |
|
|||
403 | <16> 'q:/opt/np/notepad++.exe myfile.txt' |
|
|||
404 | """ |
|
|||
405 |
|
||||
406 | pre,fn,rest = self.IP.split_user_input(line) |
|
|||
407 | res = pre + self.IP.expand_aliases(fn,rest) |
|
|||
408 | return res |
|
|||
409 |
|
||||
410 | def itpl(self, s, depth = 1): |
|
|||
411 | """ Expand Itpl format string s. |
|
|||
412 |
|
||||
413 | Only callable from command line (i.e. prefilter results); |
|
|||
414 | If you use in your scripts, you need to use a bigger depth! |
|
|||
415 | """ |
|
|||
416 | return self.IP.var_expand(s, depth) |
|
|||
417 |
|
||||
418 | def defalias(self, name, cmd): |
|
|||
419 | """ Define a new alias |
|
|||
420 |
|
||||
421 | _ip.defalias('bb','bldmake bldfiles') |
|
|||
422 |
|
||||
423 | Creates a new alias named 'bb' in ipython user namespace |
|
|||
424 | """ |
|
|||
425 |
|
||||
426 | self.dbg.check_hotname(name) |
|
|||
427 |
|
||||
428 | if name in self.IP.alias_table: |
|
|||
429 | self.dbg.debug_stack("Alias redefinition: '%s' => '%s' (old '%s')" |
|
|||
430 | % (name, cmd, self.IP.alias_table[name])) |
|
|||
431 |
|
||||
432 | if callable(cmd): |
|
|||
433 | self.IP.alias_table[name] = cmd |
|
|||
434 | import IPython.shadowns |
|
|||
435 | setattr(IPython.shadowns, name,cmd) |
|
|||
436 | return |
|
|||
437 |
|
||||
438 | if isinstance(cmd,basestring): |
|
|||
439 | nargs = cmd.count('%s') |
|
|||
440 | if nargs>0 and cmd.find('%l')>=0: |
|
|||
441 | raise Exception('The %s and %l specifiers are mutually ' |
|
|||
442 | 'exclusive in alias definitions.') |
|
|||
443 |
|
||||
444 | self.IP.alias_table[name] = (nargs,cmd) |
|
|||
445 | return |
|
|||
446 |
|
||||
447 | # just put it in - it's probably (0,'foo') |
|
|||
448 | self.IP.alias_table[name] = cmd |
|
|||
449 |
|
||||
450 | def defmacro(self, *args): |
|
|||
451 | """ Define a new macro |
|
|||
452 |
|
||||
453 | 2 forms of calling: |
|
|||
454 |
|
||||
455 | mac = _ip.defmacro('print "hello"\nprint "world"') |
|
|||
456 |
|
||||
457 | (doesn't put the created macro on user namespace) |
|
|||
458 |
|
||||
459 | _ip.defmacro('build', 'bldmake bldfiles\nabld build winscw udeb') |
|
|||
460 |
|
||||
461 | (creates a macro named 'build' in user namespace) |
|
|||
462 | """ |
|
|||
463 |
|
||||
464 | import IPython.macro |
|
|||
465 |
|
||||
466 | if len(args) == 1: |
|
|||
467 | return IPython.macro.Macro(args[0]) |
|
|||
468 | elif len(args) == 2: |
|
|||
469 | self.user_ns[args[0]] = IPython.macro.Macro(args[1]) |
|
|||
470 | else: |
|
|||
471 | return Exception("_ip.defmacro must be called with 1 or 2 arguments") |
|
|||
472 |
|
||||
473 | def set_next_input(self, s): |
|
|||
474 | """ Sets the 'default' input string for the next command line. |
|
|||
475 |
|
||||
476 | Requires readline. |
|
|||
477 |
|
||||
478 | Example: |
|
|||
479 |
|
||||
480 | [D:\ipython]|1> _ip.set_next_input("Hello Word") |
|
|||
481 | [D:\ipython]|2> Hello Word_ # cursor is here |
|
|||
482 | """ |
|
|||
483 |
|
||||
484 | self.IP.rl_next_input = s |
|
|||
485 |
|
||||
486 | def load(self, mod): |
|
|||
487 | """ Load an extension. |
|
|||
488 |
|
||||
489 | Some modules should (or must) be 'load()':ed, rather than just imported. |
|
|||
490 |
|
||||
491 | Loading will do: |
|
|||
492 |
|
||||
493 | - run init_ipython(ip) |
|
|||
494 | - run ipython_firstrun(ip) |
|
|||
495 | """ |
|
|||
496 |
|
||||
497 | if mod in self.extensions: |
|
|||
498 | # just to make sure we don't init it twice |
|
|||
499 | # note that if you 'load' a module that has already been |
|
|||
500 | # imported, init_ipython gets run anyway |
|
|||
501 |
|
||||
502 | return self.extensions[mod] |
|
|||
503 | __import__(mod) |
|
|||
504 | m = sys.modules[mod] |
|
|||
505 | if hasattr(m,'init_ipython'): |
|
|||
506 | m.init_ipython(self) |
|
|||
507 |
|
||||
508 | if hasattr(m,'ipython_firstrun'): |
|
|||
509 | already_loaded = self.db.get('firstrun_done', set()) |
|
|||
510 | if mod not in already_loaded: |
|
|||
511 | m.ipython_firstrun(self) |
|
|||
512 | already_loaded.add(mod) |
|
|||
513 | self.db['firstrun_done'] = already_loaded |
|
|||
514 |
|
||||
515 | self.extensions[mod] = m |
|
|||
516 | return m |
|
|||
517 |
|
||||
518 |
|
||||
519 | class DebugTools: |
|
|||
520 | """ Used for debugging mishaps in api usage |
|
|||
521 |
|
||||
522 | So far, tracing redefinitions is supported. |
|
|||
523 | """ |
|
|||
524 |
|
||||
525 | def __init__(self, ip): |
|
|||
526 | self.ip = ip |
|
|||
527 | self.debugmode = False |
|
|||
528 | self.hotnames = set() |
|
|||
529 |
|
||||
530 | def hotname(self, name_to_catch): |
|
|||
531 | self.hotnames.add(name_to_catch) |
|
|||
532 |
|
||||
533 | def debug_stack(self, msg = None): |
|
|||
534 | if not self.debugmode: |
|
|||
535 | return |
|
|||
536 |
|
||||
537 | import traceback |
|
|||
538 | if msg is not None: |
|
|||
539 | print '====== %s ========' % msg |
|
|||
540 | traceback.print_stack() |
|
|||
541 |
|
||||
542 | def check_hotname(self,name): |
|
|||
543 | if name in self.hotnames: |
|
|||
544 | self.debug_stack( "HotName '%s' caught" % name) |
|
|||
545 |
|
||||
546 |
|
||||
547 | def launch_new_instance(user_ns = None,shellclass = None): |
|
|||
548 | """ Make and start a new ipython instance. |
|
|||
549 |
|
||||
550 | This can be called even without having an already initialized |
|
|||
551 | ipython session running. |
|
|||
552 |
|
||||
553 | This is also used as the egg entry point for the 'ipython' script. |
|
|||
554 |
|
||||
555 | """ |
|
|||
556 | ses = make_session(user_ns,shellclass) |
|
|||
557 | ses.mainloop() |
|
|||
558 |
|
||||
559 |
|
||||
560 | def make_user_ns(user_ns = None): |
|
|||
561 | """Return a valid user interactive namespace. |
|
|||
562 |
|
||||
563 | This builds a dict with the minimal information needed to operate as a |
|
|||
564 | valid IPython user namespace, which you can pass to the various embedding |
|
|||
565 | classes in ipython. |
|
|||
566 |
|
||||
567 | This API is currently deprecated. Use ipapi.make_user_namespaces() instead |
|
|||
568 | to make both the local and global namespace objects simultaneously. |
|
|||
569 |
|
||||
570 | :Parameters: |
|
|||
571 | user_ns : dict-like, optional |
|
|||
572 | The current user namespace. The items in this namespace should be |
|
|||
573 | included in the output. If None, an appropriate blank namespace |
|
|||
574 | should be created. |
|
|||
575 |
|
||||
576 | :Returns: |
|
|||
577 | A dictionary-like object to be used as the local namespace of the |
|
|||
578 | interpreter. |
|
|||
579 | """ |
|
|||
580 |
|
||||
581 | raise NotImplementedError |
|
|||
582 |
|
||||
583 |
|
||||
584 | def make_user_global_ns(ns = None): |
|
|||
585 | """Return a valid user global namespace. |
|
|||
586 |
|
||||
587 | Similar to make_user_ns(), but global namespaces are really only needed in |
|
|||
588 | embedded applications, where there is a distinction between the user's |
|
|||
589 | interactive namespace and the global one where ipython is running. |
|
|||
590 |
|
||||
591 | This API is currently deprecated. Use ipapi.make_user_namespaces() instead |
|
|||
592 | to make both the local and global namespace objects simultaneously. |
|
|||
593 |
|
||||
594 | :Parameters: |
|
|||
595 | ns : dict, optional |
|
|||
596 | The current user global namespace. The items in this namespace |
|
|||
597 | should be included in the output. If None, an appropriate blank |
|
|||
598 | namespace should be created. |
|
|||
599 |
|
||||
600 | :Returns: |
|
|||
601 | A true dict to be used as the global namespace of the interpreter. |
|
|||
602 | """ |
|
|||
603 |
|
||||
604 | raise NotImplementedError |
|
|||
605 |
|
||||
606 | # Record the true objects in order to be able to test if the user has overridden |
|
|||
607 | # these API functions. |
|
|||
608 | _make_user_ns = make_user_ns |
|
|||
609 | _make_user_global_ns = make_user_global_ns |
|
|||
610 |
|
||||
611 |
|
||||
612 | def make_user_namespaces(user_ns = None,user_global_ns = None): |
|
|||
613 | """Return a valid local and global user interactive namespaces. |
|
|||
614 |
|
||||
615 | This builds a dict with the minimal information needed to operate as a |
|
|||
616 | valid IPython user namespace, which you can pass to the various embedding |
|
|||
617 | classes in ipython. The default implementation returns the same dict for |
|
|||
618 | both the locals and the globals to allow functions to refer to variables in |
|
|||
619 | the namespace. Customized implementations can return different dicts. The |
|
|||
620 | locals dictionary can actually be anything following the basic mapping |
|
|||
621 | protocol of a dict, but the globals dict must be a true dict, not even |
|
|||
622 | a subclass. It is recommended that any custom object for the locals |
|
|||
623 | namespace synchronize with the globals dict somehow. |
|
|||
624 |
|
||||
625 | Raises TypeError if the provided globals namespace is not a true dict. |
|
|||
626 |
|
||||
627 | :Parameters: |
|
|||
628 | user_ns : dict-like, optional |
|
|||
629 | The current user namespace. The items in this namespace should be |
|
|||
630 | included in the output. If None, an appropriate blank namespace |
|
|||
631 | should be created. |
|
|||
632 | user_global_ns : dict, optional |
|
|||
633 | The current user global namespace. The items in this namespace |
|
|||
634 | should be included in the output. If None, an appropriate blank |
|
|||
635 | namespace should be created. |
|
|||
636 |
|
||||
637 | :Returns: |
|
|||
638 | A tuple pair of dictionary-like object to be used as the local namespace |
|
|||
639 | of the interpreter and a dict to be used as the global namespace. |
|
|||
640 | """ |
|
|||
641 |
|
||||
642 | if user_ns is None: |
|
|||
643 | if make_user_ns is not _make_user_ns: |
|
|||
644 | # Old API overridden. |
|
|||
645 | # FIXME: Issue DeprecationWarning, or just let the old API live on? |
|
|||
646 | user_ns = make_user_ns(user_ns) |
|
|||
647 | else: |
|
|||
648 | # Set __name__ to __main__ to better match the behavior of the |
|
|||
649 | # normal interpreter. |
|
|||
650 | user_ns = {'__name__' :'__main__', |
|
|||
651 | '__builtins__' : __builtin__, |
|
|||
652 | } |
|
|||
653 | else: |
|
|||
654 | user_ns.setdefault('__name__','__main__') |
|
|||
655 | user_ns.setdefault('__builtins__',__builtin__) |
|
|||
656 |
|
||||
657 | if user_global_ns is None: |
|
|||
658 | if make_user_global_ns is not _make_user_global_ns: |
|
|||
659 | # Old API overridden. |
|
|||
660 | user_global_ns = make_user_global_ns(user_global_ns) |
|
|||
661 | else: |
|
|||
662 | user_global_ns = user_ns |
|
|||
663 | if type(user_global_ns) is not dict: |
|
|||
664 | raise TypeError("user_global_ns must be a true dict; got %r" |
|
|||
665 | % type(user_global_ns)) |
|
|||
666 |
|
||||
667 | return user_ns, user_global_ns |
|
|||
668 |
|
18 | |||
|
19 | from warnings import warn | |||
669 |
|
20 | |||
670 | def make_session(user_ns = None, shellclass = None): |
|
21 | msg = """ | |
671 | """Makes, but does not launch an IPython session. |
|
22 | This module (IPython.ipapi) has been moved to a new location | |
672 |
|
23 | (IPython.core.ipapi) and is being refactored. Please update your code | ||
673 | Later on you can call obj.mainloop() on the returned object. |
|
24 | to use the new IPython.core.ipapi module""" | |
674 |
|
25 | |||
675 | Inputs: |
|
26 | warn(msg, category=DeprecationWarning, stacklevel=1) | |
676 |
|
27 | |||
677 | - user_ns(None): a dict to be used as the user's namespace with initial |
|
28 | from IPython.core.ipapi import * | |
678 | data. |
|
|||
679 |
|
||||
680 | WARNING: This should *not* be run when a session exists already.""" |
|
|||
681 |
|
29 | |||
682 | import IPython.Shell |
|
|||
683 | if shellclass is None: |
|
|||
684 | return IPython.Shell.start(user_ns) |
|
|||
685 | return shellclass(user_ns = user_ns) |
|
This diff has been collapsed as it changes many lines, (2876 lines changed) Show them Hide them | |||||
@@ -1,2870 +1,28 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | #!/usr/bin/env python | |
|
2 | # encoding: utf-8 | |||
2 | """ |
|
3 | """ | |
3 | IPython -- An enhanced Interactive Python |
|
4 | A backwards compatibility layer for IPython.iplib. | |
4 |
|
5 | |||
5 | Requires Python 2.4 or newer. |
|
6 | Previously, IPython had an IPython.iplib module. IPython.iplib has been moved | |
6 |
|
7 | to IPython.core.iplib and is being refactored. This new module is provided | ||
7 | This file contains all the classes and helper functions specific to IPython. |
|
8 | for backwards compatability. We strongly encourage everyone to start using | |
|
9 | the new code in IPython.core.iplib. | |||
8 | """ |
|
10 | """ | |
9 |
|
11 | |||
10 | #***************************************************************************** |
|
12 | #----------------------------------------------------------------------------- | |
11 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and |
|
13 | # Copyright (C) 2008-2009 The IPython Development Team | |
12 | # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu> |
|
|||
13 | # |
|
14 | # | |
14 | # Distributed under the terms of the BSD License. The full license is in |
|
15 | # Distributed under the terms of the BSD License. The full license is in | |
15 | # the file COPYING, distributed as part of this software. |
|
16 | # the file COPYING, distributed as part of this software. | |
16 | # |
|
17 | #----------------------------------------------------------------------------- | |
17 | # Note: this code originally subclassed code.InteractiveConsole from the |
|
|||
18 | # Python standard library. Over time, all of that class has been copied |
|
|||
19 | # verbatim here for modifications which could not be accomplished by |
|
|||
20 | # subclassing. At this point, there are no dependencies at all on the code |
|
|||
21 | # module anymore (it is not even imported). The Python License (sec. 2) |
|
|||
22 | # allows for this, but it's always nice to acknowledge credit where credit is |
|
|||
23 | # due. |
|
|||
24 | #***************************************************************************** |
|
|||
25 |
|
||||
26 | #**************************************************************************** |
|
|||
27 | # Modules and globals |
|
|||
28 |
|
||||
29 | # Python standard modules |
|
|||
30 | import __main__ |
|
|||
31 | import __builtin__ |
|
|||
32 | import StringIO |
|
|||
33 | import bdb |
|
|||
34 | import cPickle as pickle |
|
|||
35 | import codeop |
|
|||
36 | import exceptions |
|
|||
37 | import glob |
|
|||
38 | import inspect |
|
|||
39 | import keyword |
|
|||
40 | import new |
|
|||
41 | import os |
|
|||
42 | import pydoc |
|
|||
43 | import re |
|
|||
44 | import shutil |
|
|||
45 | import string |
|
|||
46 | import sys |
|
|||
47 | import tempfile |
|
|||
48 | import traceback |
|
|||
49 | import types |
|
|||
50 | from pprint import pprint, pformat |
|
|||
51 |
|
||||
52 | # IPython's own modules |
|
|||
53 | #import IPython |
|
|||
54 | from IPython import Debugger,OInspect,PyColorize,ultraTB |
|
|||
55 | from IPython.ColorANSI import ColorScheme,ColorSchemeTable # too long names |
|
|||
56 | from IPython.Extensions import pickleshare |
|
|||
57 | from IPython.FakeModule import FakeModule, init_fakemod_dict |
|
|||
58 | from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns |
|
|||
59 | from IPython.Logger import Logger |
|
|||
60 | from IPython.Magic import Magic |
|
|||
61 | from IPython.Prompts import CachedOutput |
|
|||
62 | from IPython.ipstruct import Struct |
|
|||
63 | from IPython.background_jobs import BackgroundJobManager |
|
|||
64 | from IPython.usage import cmd_line_usage,interactive_usage |
|
|||
65 | from IPython.genutils import * |
|
|||
66 | from IPython.strdispatch import StrDispatch |
|
|||
67 | import IPython.ipapi |
|
|||
68 | import IPython.history |
|
|||
69 | import IPython.prefilter as prefilter |
|
|||
70 | import IPython.shadowns |
|
|||
71 | # Globals |
|
|||
72 |
|
||||
73 | # store the builtin raw_input globally, and use this always, in case user code |
|
|||
74 | # overwrites it (like wx.py.PyShell does) |
|
|||
75 | raw_input_original = raw_input |
|
|||
76 |
|
||||
77 | # compiled regexps for autoindent management |
|
|||
78 | dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass') |
|
|||
79 |
|
||||
80 |
|
||||
81 | #**************************************************************************** |
|
|||
82 | # Some utility function definitions |
|
|||
83 |
|
||||
84 | ini_spaces_re = re.compile(r'^(\s+)') |
|
|||
85 |
|
||||
86 | def num_ini_spaces(strng): |
|
|||
87 | """Return the number of initial spaces in a string""" |
|
|||
88 |
|
||||
89 | ini_spaces = ini_spaces_re.match(strng) |
|
|||
90 | if ini_spaces: |
|
|||
91 | return ini_spaces.end() |
|
|||
92 | else: |
|
|||
93 | return 0 |
|
|||
94 |
|
||||
95 | def softspace(file, newvalue): |
|
|||
96 | """Copied from code.py, to remove the dependency""" |
|
|||
97 |
|
||||
98 | oldvalue = 0 |
|
|||
99 | try: |
|
|||
100 | oldvalue = file.softspace |
|
|||
101 | except AttributeError: |
|
|||
102 | pass |
|
|||
103 | try: |
|
|||
104 | file.softspace = newvalue |
|
|||
105 | except (AttributeError, TypeError): |
|
|||
106 | # "attribute-less object" or "read-only attributes" |
|
|||
107 | pass |
|
|||
108 | return oldvalue |
|
|||
109 |
|
||||
110 |
|
||||
111 | def user_setup(ipythondir,rc_suffix,mode='install',interactive=True): |
|
|||
112 | """Install or upgrade the user configuration directory. |
|
|||
113 |
|
||||
114 | Can be called when running for the first time or to upgrade the user's |
|
|||
115 | .ipython/ directory. |
|
|||
116 |
|
||||
117 | Parameters |
|
|||
118 | ---------- |
|
|||
119 | ipythondir : path |
|
|||
120 | The directory to be used for installation/upgrade. In 'install' mode, |
|
|||
121 | if this path already exists, the function exits immediately. |
|
|||
122 |
|
||||
123 | rc_suffix : str |
|
|||
124 | Extension for the config files. On *nix platforms it is typically the |
|
|||
125 | empty string, while Windows normally uses '.ini'. |
|
|||
126 |
|
||||
127 | mode : str, optional |
|
|||
128 | Valid modes are 'install' and 'upgrade'. |
|
|||
129 |
|
||||
130 | interactive : bool, optional |
|
|||
131 | If False, do not wait for user input on any errors. Normally after |
|
|||
132 | printing its status information, this function waits for the user to |
|
|||
133 | hit Return before proceeding. This is because the default use case is |
|
|||
134 | when first installing the IPython configuration, so we want the user to |
|
|||
135 | acknowledge the initial message, which contains some useful |
|
|||
136 | information. |
|
|||
137 | """ |
|
|||
138 |
|
||||
139 | # For automatic use, deactivate all i/o |
|
|||
140 | if interactive: |
|
|||
141 | def wait(): |
|
|||
142 | try: |
|
|||
143 | raw_input("Please press <RETURN> to start IPython.") |
|
|||
144 | except EOFError: |
|
|||
145 | print >> Term.cout |
|
|||
146 | print '*'*70 |
|
|||
147 |
|
||||
148 | def printf(s): |
|
|||
149 | print s |
|
|||
150 | else: |
|
|||
151 | wait = lambda : None |
|
|||
152 | printf = lambda s : None |
|
|||
153 |
|
||||
154 | # Install mode should be re-entrant: if the install dir already exists, |
|
|||
155 | # bail out cleanly. |
|
|||
156 | # XXX. This is too hasty to return. We need to check to make sure that |
|
|||
157 | # all the expected config files and directories are actually there. We |
|
|||
158 | # currently have a failure mode if someone deletes a needed config file |
|
|||
159 | # but still has the ipythondir. |
|
|||
160 | if mode == 'install' and os.path.isdir(ipythondir): |
|
|||
161 | return |
|
|||
162 |
|
||||
163 | cwd = os.getcwd() # remember where we started |
|
|||
164 | glb = glob.glob |
|
|||
165 |
|
||||
166 | printf('*'*70) |
|
|||
167 | if mode == 'install': |
|
|||
168 | printf( |
|
|||
169 | """Welcome to IPython. I will try to create a personal configuration directory |
|
|||
170 | where you can customize many aspects of IPython's functionality in:\n""") |
|
|||
171 | else: |
|
|||
172 | printf('I am going to upgrade your configuration in:') |
|
|||
173 |
|
||||
174 | printf(ipythondir) |
|
|||
175 |
|
||||
176 | rcdirend = os.path.join('IPython','UserConfig') |
|
|||
177 | cfg = lambda d: os.path.join(d,rcdirend) |
|
|||
178 | try: |
|
|||
179 | rcdir = filter(os.path.isdir,map(cfg,sys.path))[0] |
|
|||
180 | printf("Initializing from configuration: %s" % rcdir) |
|
|||
181 | except IndexError: |
|
|||
182 | warning = """ |
|
|||
183 | Installation error. IPython's directory was not found. |
|
|||
184 |
|
||||
185 | Check the following: |
|
|||
186 |
|
||||
187 | The ipython/IPython directory should be in a directory belonging to your |
|
|||
188 | PYTHONPATH environment variable (that is, it should be in a directory |
|
|||
189 | belonging to sys.path). You can copy it explicitly there or just link to it. |
|
|||
190 |
|
||||
191 | IPython will create a minimal default configuration for you. |
|
|||
192 |
|
||||
193 | """ |
|
|||
194 | warn(warning) |
|
|||
195 | wait() |
|
|||
196 |
|
||||
197 | if sys.platform =='win32': |
|
|||
198 | inif = 'ipythonrc.ini' |
|
|||
199 | else: |
|
|||
200 | inif = 'ipythonrc' |
|
|||
201 | minimal_setup = {'ipy_user_conf.py' : 'import ipy_defaults', |
|
|||
202 | inif : '# intentionally left blank' } |
|
|||
203 | os.makedirs(ipythondir, mode = 0777) |
|
|||
204 | for f, cont in minimal_setup.items(): |
|
|||
205 | # In 2.5, this can be more cleanly done using 'with' |
|
|||
206 | fobj = file(ipythondir + '/' + f,'w') |
|
|||
207 | fobj.write(cont) |
|
|||
208 | fobj.close() |
|
|||
209 |
|
||||
210 | return |
|
|||
211 |
|
||||
212 | if mode == 'install': |
|
|||
213 | try: |
|
|||
214 | shutil.copytree(rcdir,ipythondir) |
|
|||
215 | os.chdir(ipythondir) |
|
|||
216 | rc_files = glb("ipythonrc*") |
|
|||
217 | for rc_file in rc_files: |
|
|||
218 | os.rename(rc_file,rc_file+rc_suffix) |
|
|||
219 | except: |
|
|||
220 | warning = """ |
|
|||
221 |
|
||||
222 | There was a problem with the installation: |
|
|||
223 | %s |
|
|||
224 | Try to correct it or contact the developers if you think it's a bug. |
|
|||
225 | IPython will proceed with builtin defaults.""" % sys.exc_info()[1] |
|
|||
226 | warn(warning) |
|
|||
227 | wait() |
|
|||
228 | return |
|
|||
229 |
|
||||
230 | elif mode == 'upgrade': |
|
|||
231 | try: |
|
|||
232 | os.chdir(ipythondir) |
|
|||
233 | except: |
|
|||
234 | printf(""" |
|
|||
235 | Can not upgrade: changing to directory %s failed. Details: |
|
|||
236 | %s |
|
|||
237 | """ % (ipythondir,sys.exc_info()[1]) ) |
|
|||
238 | wait() |
|
|||
239 | return |
|
|||
240 | else: |
|
|||
241 | sources = glb(os.path.join(rcdir,'[A-Za-z]*')) |
|
|||
242 | for new_full_path in sources: |
|
|||
243 | new_filename = os.path.basename(new_full_path) |
|
|||
244 | if new_filename.startswith('ipythonrc'): |
|
|||
245 | new_filename = new_filename + rc_suffix |
|
|||
246 | # The config directory should only contain files, skip any |
|
|||
247 | # directories which may be there (like CVS) |
|
|||
248 | if os.path.isdir(new_full_path): |
|
|||
249 | continue |
|
|||
250 | if os.path.exists(new_filename): |
|
|||
251 | old_file = new_filename+'.old' |
|
|||
252 | if os.path.exists(old_file): |
|
|||
253 | os.remove(old_file) |
|
|||
254 | os.rename(new_filename,old_file) |
|
|||
255 | shutil.copy(new_full_path,new_filename) |
|
|||
256 | else: |
|
|||
257 | raise ValueError('unrecognized mode for install: %r' % mode) |
|
|||
258 |
|
||||
259 | # Fix line-endings to those native to each platform in the config |
|
|||
260 | # directory. |
|
|||
261 | try: |
|
|||
262 | os.chdir(ipythondir) |
|
|||
263 | except: |
|
|||
264 | printf(""" |
|
|||
265 | Problem: changing to directory %s failed. |
|
|||
266 | Details: |
|
|||
267 | %s |
|
|||
268 |
|
||||
269 | Some configuration files may have incorrect line endings. This should not |
|
|||
270 | cause any problems during execution. """ % (ipythondir,sys.exc_info()[1]) ) |
|
|||
271 | wait() |
|
|||
272 | else: |
|
|||
273 | for fname in glb('ipythonrc*'): |
|
|||
274 | try: |
|
|||
275 | native_line_ends(fname,backup=0) |
|
|||
276 | except IOError: |
|
|||
277 | pass |
|
|||
278 |
|
||||
279 | if mode == 'install': |
|
|||
280 | printf(""" |
|
|||
281 | Successful installation! |
|
|||
282 |
|
||||
283 | Please read the sections 'Initial Configuration' and 'Quick Tips' in the |
|
|||
284 | IPython manual (there are both HTML and PDF versions supplied with the |
|
|||
285 | distribution) to make sure that your system environment is properly configured |
|
|||
286 | to take advantage of IPython's features. |
|
|||
287 |
|
||||
288 | Important note: the configuration system has changed! The old system is |
|
|||
289 | still in place, but its setting may be partly overridden by the settings in |
|
|||
290 | "~/.ipython/ipy_user_conf.py" config file. Please take a look at the file |
|
|||
291 | if some of the new settings bother you. |
|
|||
292 |
|
||||
293 | """) |
|
|||
294 | else: |
|
|||
295 | printf(""" |
|
|||
296 | Successful upgrade! |
|
|||
297 |
|
||||
298 | All files in your directory: |
|
|||
299 | %(ipythondir)s |
|
|||
300 | which would have been overwritten by the upgrade were backed up with a .old |
|
|||
301 | extension. If you had made particular customizations in those files you may |
|
|||
302 | want to merge them back into the new files.""" % locals() ) |
|
|||
303 | wait() |
|
|||
304 | os.chdir(cwd) |
|
|||
305 |
|
||||
306 | #**************************************************************************** |
|
|||
307 | # Local use exceptions |
|
|||
308 | class SpaceInInput(exceptions.Exception): pass |
|
|||
309 |
|
||||
310 |
|
||||
311 | #**************************************************************************** |
|
|||
312 | # Local use classes |
|
|||
313 | class Bunch: pass |
|
|||
314 |
|
||||
315 | class Undefined: pass |
|
|||
316 |
|
||||
317 | class Quitter(object): |
|
|||
318 | """Simple class to handle exit, similar to Python 2.5's. |
|
|||
319 |
|
||||
320 | It handles exiting in an ipython-safe manner, which the one in Python 2.5 |
|
|||
321 | doesn't do (obviously, since it doesn't know about ipython).""" |
|
|||
322 |
|
||||
323 | def __init__(self,shell,name): |
|
|||
324 | self.shell = shell |
|
|||
325 | self.name = name |
|
|||
326 |
|
||||
327 | def __repr__(self): |
|
|||
328 | return 'Type %s() to exit.' % self.name |
|
|||
329 | __str__ = __repr__ |
|
|||
330 |
|
||||
331 | def __call__(self): |
|
|||
332 | self.shell.exit() |
|
|||
333 |
|
||||
334 | class InputList(list): |
|
|||
335 | """Class to store user input. |
|
|||
336 |
|
||||
337 | It's basically a list, but slices return a string instead of a list, thus |
|
|||
338 | allowing things like (assuming 'In' is an instance): |
|
|||
339 |
|
||||
340 | exec In[4:7] |
|
|||
341 |
|
||||
342 | or |
|
|||
343 |
|
||||
344 | exec In[5:9] + In[14] + In[21:25]""" |
|
|||
345 |
|
||||
346 | def __getslice__(self,i,j): |
|
|||
347 | return ''.join(list.__getslice__(self,i,j)) |
|
|||
348 |
|
||||
349 | class SyntaxTB(ultraTB.ListTB): |
|
|||
350 | """Extension which holds some state: the last exception value""" |
|
|||
351 |
|
||||
352 | def __init__(self,color_scheme = 'NoColor'): |
|
|||
353 | ultraTB.ListTB.__init__(self,color_scheme) |
|
|||
354 | self.last_syntax_error = None |
|
|||
355 |
|
||||
356 | def __call__(self, etype, value, elist): |
|
|||
357 | self.last_syntax_error = value |
|
|||
358 | ultraTB.ListTB.__call__(self,etype,value,elist) |
|
|||
359 |
|
||||
360 | def clear_err_state(self): |
|
|||
361 | """Return the current error state and clear it""" |
|
|||
362 | e = self.last_syntax_error |
|
|||
363 | self.last_syntax_error = None |
|
|||
364 | return e |
|
|||
365 |
|
||||
366 | #**************************************************************************** |
|
|||
367 | # Main IPython class |
|
|||
368 |
|
||||
369 | # FIXME: the Magic class is a mixin for now, and will unfortunately remain so |
|
|||
370 | # until a full rewrite is made. I've cleaned all cross-class uses of |
|
|||
371 | # attributes and methods, but too much user code out there relies on the |
|
|||
372 | # equlity %foo == __IP.magic_foo, so I can't actually remove the mixin usage. |
|
|||
373 | # |
|
|||
374 | # But at least now, all the pieces have been separated and we could, in |
|
|||
375 | # principle, stop using the mixin. This will ease the transition to the |
|
|||
376 | # chainsaw branch. |
|
|||
377 |
|
||||
378 | # For reference, the following is the list of 'self.foo' uses in the Magic |
|
|||
379 | # class as of 2005-12-28. These are names we CAN'T use in the main ipython |
|
|||
380 | # class, to prevent clashes. |
|
|||
381 |
|
||||
382 | # ['self.__class__', 'self.__dict__', 'self._inspect', 'self._ofind', |
|
|||
383 | # 'self.arg_err', 'self.extract_input', 'self.format_', 'self.lsmagic', |
|
|||
384 | # 'self.magic_', 'self.options_table', 'self.parse', 'self.shell', |
|
|||
385 | # 'self.value'] |
|
|||
386 |
|
||||
387 | class InteractiveShell(object,Magic): |
|
|||
388 | """An enhanced console for Python.""" |
|
|||
389 |
|
||||
390 | # class attribute to indicate whether the class supports threads or not. |
|
|||
391 | # Subclasses with thread support should override this as needed. |
|
|||
392 | isthreaded = False |
|
|||
393 |
|
||||
394 | def __init__(self,name,usage=None,rc=Struct(opts=None,args=None), |
|
|||
395 | user_ns=None,user_global_ns=None,banner2='', |
|
|||
396 | custom_exceptions=((),None),embedded=False): |
|
|||
397 |
|
||||
398 | # log system |
|
|||
399 | self.logger = Logger(self,logfname='ipython_log.py',logmode='rotate') |
|
|||
400 |
|
||||
401 | # Job manager (for jobs run as background threads) |
|
|||
402 | self.jobs = BackgroundJobManager() |
|
|||
403 |
|
||||
404 | # Store the actual shell's name |
|
|||
405 | self.name = name |
|
|||
406 | self.more = False |
|
|||
407 |
|
||||
408 | # We need to know whether the instance is meant for embedding, since |
|
|||
409 | # global/local namespaces need to be handled differently in that case |
|
|||
410 | self.embedded = embedded |
|
|||
411 | if embedded: |
|
|||
412 | # Control variable so users can, from within the embedded instance, |
|
|||
413 | # permanently deactivate it. |
|
|||
414 | self.embedded_active = True |
|
|||
415 |
|
||||
416 | # command compiler |
|
|||
417 | self.compile = codeop.CommandCompiler() |
|
|||
418 |
|
||||
419 | # User input buffer |
|
|||
420 | self.buffer = [] |
|
|||
421 |
|
||||
422 | # Default name given in compilation of code |
|
|||
423 | self.filename = '<ipython console>' |
|
|||
424 |
|
||||
425 | # Install our own quitter instead of the builtins. For python2.3-2.4, |
|
|||
426 | # this brings in behavior like 2.5, and for 2.5 it's identical. |
|
|||
427 | __builtin__.exit = Quitter(self,'exit') |
|
|||
428 | __builtin__.quit = Quitter(self,'quit') |
|
|||
429 |
|
||||
430 | # Make an empty namespace, which extension writers can rely on both |
|
|||
431 | # existing and NEVER being used by ipython itself. This gives them a |
|
|||
432 | # convenient location for storing additional information and state |
|
|||
433 | # their extensions may require, without fear of collisions with other |
|
|||
434 | # ipython names that may develop later. |
|
|||
435 | self.meta = Struct() |
|
|||
436 |
|
||||
437 | # Create the namespace where the user will operate. user_ns is |
|
|||
438 | # normally the only one used, and it is passed to the exec calls as |
|
|||
439 | # the locals argument. But we do carry a user_global_ns namespace |
|
|||
440 | # given as the exec 'globals' argument, This is useful in embedding |
|
|||
441 | # situations where the ipython shell opens in a context where the |
|
|||
442 | # distinction between locals and globals is meaningful. For |
|
|||
443 | # non-embedded contexts, it is just the same object as the user_ns dict. |
|
|||
444 |
|
||||
445 | # FIXME. For some strange reason, __builtins__ is showing up at user |
|
|||
446 | # level as a dict instead of a module. This is a manual fix, but I |
|
|||
447 | # should really track down where the problem is coming from. Alex |
|
|||
448 | # Schmolck reported this problem first. |
|
|||
449 |
|
||||
450 | # A useful post by Alex Martelli on this topic: |
|
|||
451 | # Re: inconsistent value from __builtins__ |
|
|||
452 | # Von: Alex Martelli <aleaxit@yahoo.com> |
|
|||
453 | # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends |
|
|||
454 | # Gruppen: comp.lang.python |
|
|||
455 |
|
||||
456 | # Michael Hohn <hohn@hooknose.lbl.gov> wrote: |
|
|||
457 | # > >>> print type(builtin_check.get_global_binding('__builtins__')) |
|
|||
458 | # > <type 'dict'> |
|
|||
459 | # > >>> print type(__builtins__) |
|
|||
460 | # > <type 'module'> |
|
|||
461 | # > Is this difference in return value intentional? |
|
|||
462 |
|
||||
463 | # Well, it's documented that '__builtins__' can be either a dictionary |
|
|||
464 | # or a module, and it's been that way for a long time. Whether it's |
|
|||
465 | # intentional (or sensible), I don't know. In any case, the idea is |
|
|||
466 | # that if you need to access the built-in namespace directly, you |
|
|||
467 | # should start with "import __builtin__" (note, no 's') which will |
|
|||
468 | # definitely give you a module. Yeah, it's somewhat confusing:-(. |
|
|||
469 |
|
||||
470 | # These routines return properly built dicts as needed by the rest of |
|
|||
471 | # the code, and can also be used by extension writers to generate |
|
|||
472 | # properly initialized namespaces. |
|
|||
473 | user_ns, user_global_ns = IPython.ipapi.make_user_namespaces(user_ns, |
|
|||
474 | user_global_ns) |
|
|||
475 |
|
||||
476 | # Assign namespaces |
|
|||
477 | # This is the namespace where all normal user variables live |
|
|||
478 | self.user_ns = user_ns |
|
|||
479 | self.user_global_ns = user_global_ns |
|
|||
480 |
|
||||
481 | # An auxiliary namespace that checks what parts of the user_ns were |
|
|||
482 | # loaded at startup, so we can list later only variables defined in |
|
|||
483 | # actual interactive use. Since it is always a subset of user_ns, it |
|
|||
484 | # doesn't need to be seaparately tracked in the ns_table |
|
|||
485 | self.user_config_ns = {} |
|
|||
486 |
|
||||
487 | # A namespace to keep track of internal data structures to prevent |
|
|||
488 | # them from cluttering user-visible stuff. Will be updated later |
|
|||
489 | self.internal_ns = {} |
|
|||
490 |
|
||||
491 | # Namespace of system aliases. Each entry in the alias |
|
|||
492 | # table must be a 2-tuple of the form (N,name), where N is the number |
|
|||
493 | # of positional arguments of the alias. |
|
|||
494 | self.alias_table = {} |
|
|||
495 |
|
||||
496 | # Now that FakeModule produces a real module, we've run into a nasty |
|
|||
497 | # problem: after script execution (via %run), the module where the user |
|
|||
498 | # code ran is deleted. Now that this object is a true module (needed |
|
|||
499 | # so docetst and other tools work correctly), the Python module |
|
|||
500 | # teardown mechanism runs over it, and sets to None every variable |
|
|||
501 | # present in that module. Top-level references to objects from the |
|
|||
502 | # script survive, because the user_ns is updated with them. However, |
|
|||
503 | # calling functions defined in the script that use other things from |
|
|||
504 | # the script will fail, because the function's closure had references |
|
|||
505 | # to the original objects, which are now all None. So we must protect |
|
|||
506 | # these modules from deletion by keeping a cache. |
|
|||
507 | # |
|
|||
508 | # To avoid keeping stale modules around (we only need the one from the |
|
|||
509 | # last run), we use a dict keyed with the full path to the script, so |
|
|||
510 | # only the last version of the module is held in the cache. Note, |
|
|||
511 | # however, that we must cache the module *namespace contents* (their |
|
|||
512 | # __dict__). Because if we try to cache the actual modules, old ones |
|
|||
513 | # (uncached) could be destroyed while still holding references (such as |
|
|||
514 | # those held by GUI objects that tend to be long-lived)> |
|
|||
515 | # |
|
|||
516 | # The %reset command will flush this cache. See the cache_main_mod() |
|
|||
517 | # and clear_main_mod_cache() methods for details on use. |
|
|||
518 |
|
||||
519 | # This is the cache used for 'main' namespaces |
|
|||
520 | self._main_ns_cache = {} |
|
|||
521 | # And this is the single instance of FakeModule whose __dict__ we keep |
|
|||
522 | # copying and clearing for reuse on each %run |
|
|||
523 | self._user_main_module = FakeModule() |
|
|||
524 |
|
||||
525 | # A table holding all the namespaces IPython deals with, so that |
|
|||
526 | # introspection facilities can search easily. |
|
|||
527 | self.ns_table = {'user':user_ns, |
|
|||
528 | 'user_global':user_global_ns, |
|
|||
529 | 'alias':self.alias_table, |
|
|||
530 | 'internal':self.internal_ns, |
|
|||
531 | 'builtin':__builtin__.__dict__ |
|
|||
532 | } |
|
|||
533 |
|
||||
534 | # Similarly, track all namespaces where references can be held and that |
|
|||
535 | # we can safely clear (so it can NOT include builtin). This one can be |
|
|||
536 | # a simple list. |
|
|||
537 | self.ns_refs_table = [ user_ns, user_global_ns, self.user_config_ns, |
|
|||
538 | self.alias_table, self.internal_ns, |
|
|||
539 | self._main_ns_cache ] |
|
|||
540 |
|
||||
541 | # We need to insert into sys.modules something that looks like a |
|
|||
542 | # module but which accesses the IPython namespace, for shelve and |
|
|||
543 | # pickle to work interactively. Normally they rely on getting |
|
|||
544 | # everything out of __main__, but for embedding purposes each IPython |
|
|||
545 | # instance has its own private namespace, so we can't go shoving |
|
|||
546 | # everything into __main__. |
|
|||
547 |
|
||||
548 | # note, however, that we should only do this for non-embedded |
|
|||
549 | # ipythons, which really mimic the __main__.__dict__ with their own |
|
|||
550 | # namespace. Embedded instances, on the other hand, should not do |
|
|||
551 | # this because they need to manage the user local/global namespaces |
|
|||
552 | # only, but they live within a 'normal' __main__ (meaning, they |
|
|||
553 | # shouldn't overtake the execution environment of the script they're |
|
|||
554 | # embedded in). |
|
|||
555 |
|
||||
556 | if not embedded: |
|
|||
557 | try: |
|
|||
558 | main_name = self.user_ns['__name__'] |
|
|||
559 | except KeyError: |
|
|||
560 | raise KeyError,'user_ns dictionary MUST have a "__name__" key' |
|
|||
561 | else: |
|
|||
562 | #print "pickle hack in place" # dbg |
|
|||
563 | #print 'main_name:',main_name # dbg |
|
|||
564 | sys.modules[main_name] = FakeModule(self.user_ns) |
|
|||
565 |
|
||||
566 | # List of input with multi-line handling. |
|
|||
567 | self.input_hist = InputList() |
|
|||
568 | # This one will hold the 'raw' input history, without any |
|
|||
569 | # pre-processing. This will allow users to retrieve the input just as |
|
|||
570 | # it was exactly typed in by the user, with %hist -r. |
|
|||
571 | self.input_hist_raw = InputList() |
|
|||
572 |
|
||||
573 | # list of visited directories |
|
|||
574 | try: |
|
|||
575 | self.dir_hist = [os.getcwd()] |
|
|||
576 | except OSError: |
|
|||
577 | self.dir_hist = [] |
|
|||
578 |
|
||||
579 | # dict of output history |
|
|||
580 | self.output_hist = {} |
|
|||
581 |
|
||||
582 | # Get system encoding at startup time. Certain terminals (like Emacs |
|
|||
583 | # under Win32 have it set to None, and we need to have a known valid |
|
|||
584 | # encoding to use in the raw_input() method |
|
|||
585 | try: |
|
|||
586 | self.stdin_encoding = sys.stdin.encoding or 'ascii' |
|
|||
587 | except AttributeError: |
|
|||
588 | self.stdin_encoding = 'ascii' |
|
|||
589 |
|
||||
590 | # dict of things NOT to alias (keywords, builtins and some magics) |
|
|||
591 | no_alias = {} |
|
|||
592 | no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias'] |
|
|||
593 | for key in keyword.kwlist + no_alias_magics: |
|
|||
594 | no_alias[key] = 1 |
|
|||
595 | no_alias.update(__builtin__.__dict__) |
|
|||
596 | self.no_alias = no_alias |
|
|||
597 |
|
||||
598 | # Object variable to store code object waiting execution. This is |
|
|||
599 | # used mainly by the multithreaded shells, but it can come in handy in |
|
|||
600 | # other situations. No need to use a Queue here, since it's a single |
|
|||
601 | # item which gets cleared once run. |
|
|||
602 | self.code_to_run = None |
|
|||
603 |
|
||||
604 | # escapes for automatic behavior on the command line |
|
|||
605 | self.ESC_SHELL = '!' |
|
|||
606 | self.ESC_SH_CAP = '!!' |
|
|||
607 | self.ESC_HELP = '?' |
|
|||
608 | self.ESC_MAGIC = '%' |
|
|||
609 | self.ESC_QUOTE = ',' |
|
|||
610 | self.ESC_QUOTE2 = ';' |
|
|||
611 | self.ESC_PAREN = '/' |
|
|||
612 |
|
||||
613 | # And their associated handlers |
|
|||
614 | self.esc_handlers = {self.ESC_PAREN : self.handle_auto, |
|
|||
615 | self.ESC_QUOTE : self.handle_auto, |
|
|||
616 | self.ESC_QUOTE2 : self.handle_auto, |
|
|||
617 | self.ESC_MAGIC : self.handle_magic, |
|
|||
618 | self.ESC_HELP : self.handle_help, |
|
|||
619 | self.ESC_SHELL : self.handle_shell_escape, |
|
|||
620 | self.ESC_SH_CAP : self.handle_shell_escape, |
|
|||
621 | } |
|
|||
622 |
|
||||
623 | # class initializations |
|
|||
624 | Magic.__init__(self,self) |
|
|||
625 |
|
||||
626 | # Python source parser/formatter for syntax highlighting |
|
|||
627 | pyformat = PyColorize.Parser().format |
|
|||
628 | self.pycolorize = lambda src: pyformat(src,'str',self.rc['colors']) |
|
|||
629 |
|
||||
630 | # hooks holds pointers used for user-side customizations |
|
|||
631 | self.hooks = Struct() |
|
|||
632 |
|
||||
633 | self.strdispatchers = {} |
|
|||
634 |
|
||||
635 | # Set all default hooks, defined in the IPython.hooks module. |
|
|||
636 | hooks = IPython.hooks |
|
|||
637 | for hook_name in hooks.__all__: |
|
|||
638 | # default hooks have priority 100, i.e. low; user hooks should have |
|
|||
639 | # 0-100 priority |
|
|||
640 | self.set_hook(hook_name,getattr(hooks,hook_name), 100) |
|
|||
641 | #print "bound hook",hook_name |
|
|||
642 |
|
||||
643 | # Flag to mark unconditional exit |
|
|||
644 | self.exit_now = False |
|
|||
645 |
|
||||
646 | self.usage_min = """\ |
|
|||
647 | An enhanced console for Python. |
|
|||
648 | Some of its features are: |
|
|||
649 | - Readline support if the readline library is present. |
|
|||
650 | - Tab completion in the local namespace. |
|
|||
651 | - Logging of input, see command-line options. |
|
|||
652 | - System shell escape via ! , eg !ls. |
|
|||
653 | - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.) |
|
|||
654 | - Keeps track of locally defined variables via %who, %whos. |
|
|||
655 | - Show object information with a ? eg ?x or x? (use ?? for more info). |
|
|||
656 | """ |
|
|||
657 | if usage: self.usage = usage |
|
|||
658 | else: self.usage = self.usage_min |
|
|||
659 |
|
||||
660 | # Storage |
|
|||
661 | self.rc = rc # This will hold all configuration information |
|
|||
662 | self.pager = 'less' |
|
|||
663 | # temporary files used for various purposes. Deleted at exit. |
|
|||
664 | self.tempfiles = [] |
|
|||
665 |
|
||||
666 | # Keep track of readline usage (later set by init_readline) |
|
|||
667 | self.has_readline = False |
|
|||
668 |
|
||||
669 | # template for logfile headers. It gets resolved at runtime by the |
|
|||
670 | # logstart method. |
|
|||
671 | self.loghead_tpl = \ |
|
|||
672 | """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE *** |
|
|||
673 | #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW |
|
|||
674 | #log# opts = %s |
|
|||
675 | #log# args = %s |
|
|||
676 | #log# It is safe to make manual edits below here. |
|
|||
677 | #log#----------------------------------------------------------------------- |
|
|||
678 | """ |
|
|||
679 | # for pushd/popd management |
|
|||
680 | try: |
|
|||
681 | self.home_dir = get_home_dir() |
|
|||
682 | except HomeDirError,msg: |
|
|||
683 | fatal(msg) |
|
|||
684 |
|
||||
685 | self.dir_stack = [] |
|
|||
686 |
|
||||
687 | # Functions to call the underlying shell. |
|
|||
688 |
|
||||
689 | # The first is similar to os.system, but it doesn't return a value, |
|
|||
690 | # and it allows interpolation of variables in the user's namespace. |
|
|||
691 | self.system = lambda cmd: \ |
|
|||
692 | self.hooks.shell_hook(self.var_expand(cmd,depth=2)) |
|
|||
693 |
|
||||
694 | # These are for getoutput and getoutputerror: |
|
|||
695 | self.getoutput = lambda cmd: \ |
|
|||
696 | getoutput(self.var_expand(cmd,depth=2), |
|
|||
697 | header=self.rc.system_header, |
|
|||
698 | verbose=self.rc.system_verbose) |
|
|||
699 |
|
||||
700 | self.getoutputerror = lambda cmd: \ |
|
|||
701 | getoutputerror(self.var_expand(cmd,depth=2), |
|
|||
702 | header=self.rc.system_header, |
|
|||
703 | verbose=self.rc.system_verbose) |
|
|||
704 |
|
||||
705 |
|
||||
706 | # keep track of where we started running (mainly for crash post-mortem) |
|
|||
707 | self.starting_dir = os.getcwd() |
|
|||
708 |
|
||||
709 | # Various switches which can be set |
|
|||
710 | self.CACHELENGTH = 5000 # this is cheap, it's just text |
|
|||
711 | self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__ |
|
|||
712 | self.banner2 = banner2 |
|
|||
713 |
|
||||
714 | # TraceBack handlers: |
|
|||
715 |
|
||||
716 | # Syntax error handler. |
|
|||
717 | self.SyntaxTB = SyntaxTB(color_scheme='NoColor') |
|
|||
718 |
|
||||
719 | # The interactive one is initialized with an offset, meaning we always |
|
|||
720 | # want to remove the topmost item in the traceback, which is our own |
|
|||
721 | # internal code. Valid modes: ['Plain','Context','Verbose'] |
|
|||
722 | self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain', |
|
|||
723 | color_scheme='NoColor', |
|
|||
724 | tb_offset = 1) |
|
|||
725 |
|
||||
726 | # IPython itself shouldn't crash. This will produce a detailed |
|
|||
727 | # post-mortem if it does. But we only install the crash handler for |
|
|||
728 | # non-threaded shells, the threaded ones use a normal verbose reporter |
|
|||
729 | # and lose the crash handler. This is because exceptions in the main |
|
|||
730 | # thread (such as in GUI code) propagate directly to sys.excepthook, |
|
|||
731 | # and there's no point in printing crash dumps for every user exception. |
|
|||
732 | if self.isthreaded: |
|
|||
733 | ipCrashHandler = ultraTB.FormattedTB() |
|
|||
734 | else: |
|
|||
735 | from IPython import CrashHandler |
|
|||
736 | ipCrashHandler = CrashHandler.IPythonCrashHandler(self) |
|
|||
737 | self.set_crash_handler(ipCrashHandler) |
|
|||
738 |
|
||||
739 | # and add any custom exception handlers the user may have specified |
|
|||
740 | self.set_custom_exc(*custom_exceptions) |
|
|||
741 |
|
||||
742 | # indentation management |
|
|||
743 | self.autoindent = False |
|
|||
744 | self.indent_current_nsp = 0 |
|
|||
745 |
|
||||
746 | # Make some aliases automatically |
|
|||
747 | # Prepare list of shell aliases to auto-define |
|
|||
748 | if os.name == 'posix': |
|
|||
749 | auto_alias = ('mkdir mkdir', 'rmdir rmdir', |
|
|||
750 | 'mv mv -i','rm rm -i','cp cp -i', |
|
|||
751 | 'cat cat','less less','clear clear', |
|
|||
752 | # a better ls |
|
|||
753 | 'ls ls -F', |
|
|||
754 | # long ls |
|
|||
755 | 'll ls -lF') |
|
|||
756 | # Extra ls aliases with color, which need special treatment on BSD |
|
|||
757 | # variants |
|
|||
758 | ls_extra = ( # color ls |
|
|||
759 | 'lc ls -F -o --color', |
|
|||
760 | # ls normal files only |
|
|||
761 | 'lf ls -F -o --color %l | grep ^-', |
|
|||
762 | # ls symbolic links |
|
|||
763 | 'lk ls -F -o --color %l | grep ^l', |
|
|||
764 | # directories or links to directories, |
|
|||
765 | 'ldir ls -F -o --color %l | grep /$', |
|
|||
766 | # things which are executable |
|
|||
767 | 'lx ls -F -o --color %l | grep ^-..x', |
|
|||
768 | ) |
|
|||
769 | # The BSDs don't ship GNU ls, so they don't understand the |
|
|||
770 | # --color switch out of the box |
|
|||
771 | if 'bsd' in sys.platform: |
|
|||
772 | ls_extra = ( # ls normal files only |
|
|||
773 | 'lf ls -lF | grep ^-', |
|
|||
774 | # ls symbolic links |
|
|||
775 | 'lk ls -lF | grep ^l', |
|
|||
776 | # directories or links to directories, |
|
|||
777 | 'ldir ls -lF | grep /$', |
|
|||
778 | # things which are executable |
|
|||
779 | 'lx ls -lF | grep ^-..x', |
|
|||
780 | ) |
|
|||
781 | auto_alias = auto_alias + ls_extra |
|
|||
782 | elif os.name in ['nt','dos']: |
|
|||
783 | auto_alias = ('ls dir /on', |
|
|||
784 | 'ddir dir /ad /on', 'ldir dir /ad /on', |
|
|||
785 | 'mkdir mkdir','rmdir rmdir','echo echo', |
|
|||
786 | 'ren ren','cls cls','copy copy') |
|
|||
787 | else: |
|
|||
788 | auto_alias = () |
|
|||
789 | self.auto_alias = [s.split(None,1) for s in auto_alias] |
|
|||
790 |
|
||||
791 | # Produce a public API instance |
|
|||
792 | self.api = IPython.ipapi.IPApi(self) |
|
|||
793 |
|
||||
794 | # Initialize all user-visible namespaces |
|
|||
795 | self.init_namespaces() |
|
|||
796 |
|
||||
797 | # Call the actual (public) initializer |
|
|||
798 | self.init_auto_alias() |
|
|||
799 |
|
||||
800 | # track which builtins we add, so we can clean up later |
|
|||
801 | self.builtins_added = {} |
|
|||
802 | # This method will add the necessary builtins for operation, but |
|
|||
803 | # tracking what it did via the builtins_added dict. |
|
|||
804 |
|
||||
805 | #TODO: remove this, redundant |
|
|||
806 | self.add_builtins() |
|
|||
807 | # end __init__ |
|
|||
808 |
|
||||
809 | def var_expand(self,cmd,depth=0): |
|
|||
810 | """Expand python variables in a string. |
|
|||
811 |
|
||||
812 | The depth argument indicates how many frames above the caller should |
|
|||
813 | be walked to look for the local namespace where to expand variables. |
|
|||
814 |
|
||||
815 | The global namespace for expansion is always the user's interactive |
|
|||
816 | namespace. |
|
|||
817 | """ |
|
|||
818 |
|
||||
819 | return str(ItplNS(cmd, |
|
|||
820 | self.user_ns, # globals |
|
|||
821 | # Skip our own frame in searching for locals: |
|
|||
822 | sys._getframe(depth+1).f_locals # locals |
|
|||
823 | )) |
|
|||
824 |
|
||||
825 | def pre_config_initialization(self): |
|
|||
826 | """Pre-configuration init method |
|
|||
827 |
|
||||
828 | This is called before the configuration files are processed to |
|
|||
829 | prepare the services the config files might need. |
|
|||
830 |
|
||||
831 | self.rc already has reasonable default values at this point. |
|
|||
832 | """ |
|
|||
833 | rc = self.rc |
|
|||
834 | try: |
|
|||
835 | self.db = pickleshare.PickleShareDB(rc.ipythondir + "/db") |
|
|||
836 | except exceptions.UnicodeDecodeError: |
|
|||
837 | print "Your ipythondir can't be decoded to unicode!" |
|
|||
838 | print "Please set HOME environment variable to something that" |
|
|||
839 | print r"only has ASCII characters, e.g. c:\home" |
|
|||
840 | print "Now it is",rc.ipythondir |
|
|||
841 | sys.exit() |
|
|||
842 | self.shadowhist = IPython.history.ShadowHist(self.db) |
|
|||
843 |
|
||||
844 | def post_config_initialization(self): |
|
|||
845 | """Post configuration init method |
|
|||
846 |
|
||||
847 | This is called after the configuration files have been processed to |
|
|||
848 | 'finalize' the initialization.""" |
|
|||
849 |
|
||||
850 | rc = self.rc |
|
|||
851 |
|
||||
852 | # Object inspector |
|
|||
853 | self.inspector = OInspect.Inspector(OInspect.InspectColors, |
|
|||
854 | PyColorize.ANSICodeColors, |
|
|||
855 | 'NoColor', |
|
|||
856 | rc.object_info_string_level) |
|
|||
857 |
|
||||
858 | self.rl_next_input = None |
|
|||
859 | self.rl_do_indent = False |
|
|||
860 | # Load readline proper |
|
|||
861 | if rc.readline: |
|
|||
862 | self.init_readline() |
|
|||
863 |
|
||||
864 | # local shortcut, this is used a LOT |
|
|||
865 | self.log = self.logger.log |
|
|||
866 |
|
||||
867 | # Initialize cache, set in/out prompts and printing system |
|
|||
868 | self.outputcache = CachedOutput(self, |
|
|||
869 | rc.cache_size, |
|
|||
870 | rc.pprint, |
|
|||
871 | input_sep = rc.separate_in, |
|
|||
872 | output_sep = rc.separate_out, |
|
|||
873 | output_sep2 = rc.separate_out2, |
|
|||
874 | ps1 = rc.prompt_in1, |
|
|||
875 | ps2 = rc.prompt_in2, |
|
|||
876 | ps_out = rc.prompt_out, |
|
|||
877 | pad_left = rc.prompts_pad_left) |
|
|||
878 |
|
||||
879 | # user may have over-ridden the default print hook: |
|
|||
880 | try: |
|
|||
881 | self.outputcache.__class__.display = self.hooks.display |
|
|||
882 | except AttributeError: |
|
|||
883 | pass |
|
|||
884 |
|
||||
885 | # I don't like assigning globally to sys, because it means when |
|
|||
886 | # embedding instances, each embedded instance overrides the previous |
|
|||
887 | # choice. But sys.displayhook seems to be called internally by exec, |
|
|||
888 | # so I don't see a way around it. We first save the original and then |
|
|||
889 | # overwrite it. |
|
|||
890 | self.sys_displayhook = sys.displayhook |
|
|||
891 | sys.displayhook = self.outputcache |
|
|||
892 |
|
||||
893 | # Do a proper resetting of doctest, including the necessary displayhook |
|
|||
894 | # monkeypatching |
|
|||
895 | try: |
|
|||
896 | doctest_reload() |
|
|||
897 | except ImportError: |
|
|||
898 | warn("doctest module does not exist.") |
|
|||
899 |
|
||||
900 | # Set user colors (don't do it in the constructor above so that it |
|
|||
901 | # doesn't crash if colors option is invalid) |
|
|||
902 | self.magic_colors(rc.colors) |
|
|||
903 |
|
||||
904 | # Set calling of pdb on exceptions |
|
|||
905 | self.call_pdb = rc.pdb |
|
|||
906 |
|
||||
907 | # Load user aliases |
|
|||
908 | for alias in rc.alias: |
|
|||
909 | self.magic_alias(alias) |
|
|||
910 |
|
||||
911 | self.hooks.late_startup_hook() |
|
|||
912 |
|
||||
913 | for cmd in self.rc.autoexec: |
|
|||
914 | #print "autoexec>",cmd #dbg |
|
|||
915 | self.api.runlines(cmd) |
|
|||
916 |
|
||||
917 | batchrun = False |
|
|||
918 | for batchfile in [path(arg) for arg in self.rc.args |
|
|||
919 | if arg.lower().endswith('.ipy')]: |
|
|||
920 | if not batchfile.isfile(): |
|
|||
921 | print "No such batch file:", batchfile |
|
|||
922 | continue |
|
|||
923 | self.api.runlines(batchfile.text()) |
|
|||
924 | batchrun = True |
|
|||
925 | # without -i option, exit after running the batch file |
|
|||
926 | if batchrun and not self.rc.interact: |
|
|||
927 | self.ask_exit() |
|
|||
928 |
|
||||
929 | def init_namespaces(self): |
|
|||
930 | """Initialize all user-visible namespaces to their minimum defaults. |
|
|||
931 |
|
||||
932 | Certain history lists are also initialized here, as they effectively |
|
|||
933 | act as user namespaces. |
|
|||
934 |
|
||||
935 | Notes |
|
|||
936 | ----- |
|
|||
937 | All data structures here are only filled in, they are NOT reset by this |
|
|||
938 | method. If they were not empty before, data will simply be added to |
|
|||
939 | therm. |
|
|||
940 | """ |
|
|||
941 | # The user namespace MUST have a pointer to the shell itself. |
|
|||
942 | self.user_ns[self.name] = self |
|
|||
943 |
|
||||
944 | # Store the public api instance |
|
|||
945 | self.user_ns['_ip'] = self.api |
|
|||
946 |
|
||||
947 | # make global variables for user access to the histories |
|
|||
948 | self.user_ns['_ih'] = self.input_hist |
|
|||
949 | self.user_ns['_oh'] = self.output_hist |
|
|||
950 | self.user_ns['_dh'] = self.dir_hist |
|
|||
951 |
|
||||
952 | # user aliases to input and output histories |
|
|||
953 | self.user_ns['In'] = self.input_hist |
|
|||
954 | self.user_ns['Out'] = self.output_hist |
|
|||
955 |
|
||||
956 | self.user_ns['_sh'] = IPython.shadowns |
|
|||
957 |
|
||||
958 | # Fill the history zero entry, user counter starts at 1 |
|
|||
959 | self.input_hist.append('\n') |
|
|||
960 | self.input_hist_raw.append('\n') |
|
|||
961 |
|
||||
962 | def add_builtins(self): |
|
|||
963 | """Store ipython references into the builtin namespace. |
|
|||
964 |
|
||||
965 | Some parts of ipython operate via builtins injected here, which hold a |
|
|||
966 | reference to IPython itself.""" |
|
|||
967 |
|
||||
968 | # TODO: deprecate all of these, they are unsafe |
|
|||
969 | builtins_new = dict(__IPYTHON__ = self, |
|
|||
970 | ip_set_hook = self.set_hook, |
|
|||
971 | jobs = self.jobs, |
|
|||
972 | ipmagic = wrap_deprecated(self.ipmagic,'_ip.magic()'), |
|
|||
973 | ipalias = wrap_deprecated(self.ipalias), |
|
|||
974 | ipsystem = wrap_deprecated(self.ipsystem,'_ip.system()'), |
|
|||
975 | #_ip = self.api |
|
|||
976 | ) |
|
|||
977 | for biname,bival in builtins_new.items(): |
|
|||
978 | try: |
|
|||
979 | # store the orignal value so we can restore it |
|
|||
980 | self.builtins_added[biname] = __builtin__.__dict__[biname] |
|
|||
981 | except KeyError: |
|
|||
982 | # or mark that it wasn't defined, and we'll just delete it at |
|
|||
983 | # cleanup |
|
|||
984 | self.builtins_added[biname] = Undefined |
|
|||
985 | __builtin__.__dict__[biname] = bival |
|
|||
986 |
|
||||
987 | # Keep in the builtins a flag for when IPython is active. We set it |
|
|||
988 | # with setdefault so that multiple nested IPythons don't clobber one |
|
|||
989 | # another. Each will increase its value by one upon being activated, |
|
|||
990 | # which also gives us a way to determine the nesting level. |
|
|||
991 | __builtin__.__dict__.setdefault('__IPYTHON__active',0) |
|
|||
992 |
|
||||
993 | def clean_builtins(self): |
|
|||
994 | """Remove any builtins which might have been added by add_builtins, or |
|
|||
995 | restore overwritten ones to their previous values.""" |
|
|||
996 | for biname,bival in self.builtins_added.items(): |
|
|||
997 | if bival is Undefined: |
|
|||
998 | del __builtin__.__dict__[biname] |
|
|||
999 | else: |
|
|||
1000 | __builtin__.__dict__[biname] = bival |
|
|||
1001 | self.builtins_added.clear() |
|
|||
1002 |
|
||||
1003 | def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None): |
|
|||
1004 | """set_hook(name,hook) -> sets an internal IPython hook. |
|
|||
1005 |
|
||||
1006 | IPython exposes some of its internal API as user-modifiable hooks. By |
|
|||
1007 | adding your function to one of these hooks, you can modify IPython's |
|
|||
1008 | behavior to call at runtime your own routines.""" |
|
|||
1009 |
|
||||
1010 | # At some point in the future, this should validate the hook before it |
|
|||
1011 | # accepts it. Probably at least check that the hook takes the number |
|
|||
1012 | # of args it's supposed to. |
|
|||
1013 |
|
||||
1014 | f = new.instancemethod(hook,self,self.__class__) |
|
|||
1015 |
|
||||
1016 | # check if the hook is for strdispatcher first |
|
|||
1017 | if str_key is not None: |
|
|||
1018 | sdp = self.strdispatchers.get(name, StrDispatch()) |
|
|||
1019 | sdp.add_s(str_key, f, priority ) |
|
|||
1020 | self.strdispatchers[name] = sdp |
|
|||
1021 | return |
|
|||
1022 | if re_key is not None: |
|
|||
1023 | sdp = self.strdispatchers.get(name, StrDispatch()) |
|
|||
1024 | sdp.add_re(re.compile(re_key), f, priority ) |
|
|||
1025 | self.strdispatchers[name] = sdp |
|
|||
1026 | return |
|
|||
1027 |
|
||||
1028 | dp = getattr(self.hooks, name, None) |
|
|||
1029 | if name not in IPython.hooks.__all__: |
|
|||
1030 | print "Warning! Hook '%s' is not one of %s" % (name, IPython.hooks.__all__ ) |
|
|||
1031 | if not dp: |
|
|||
1032 | dp = IPython.hooks.CommandChainDispatcher() |
|
|||
1033 |
|
||||
1034 | try: |
|
|||
1035 | dp.add(f,priority) |
|
|||
1036 | except AttributeError: |
|
|||
1037 | # it was not commandchain, plain old func - replace |
|
|||
1038 | dp = f |
|
|||
1039 |
|
||||
1040 | setattr(self.hooks,name, dp) |
|
|||
1041 |
|
||||
1042 |
|
||||
1043 | #setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__)) |
|
|||
1044 |
|
||||
1045 | def set_crash_handler(self,crashHandler): |
|
|||
1046 | """Set the IPython crash handler. |
|
|||
1047 |
|
||||
1048 | This must be a callable with a signature suitable for use as |
|
|||
1049 | sys.excepthook.""" |
|
|||
1050 |
|
||||
1051 | # Install the given crash handler as the Python exception hook |
|
|||
1052 | sys.excepthook = crashHandler |
|
|||
1053 |
|
||||
1054 | # The instance will store a pointer to this, so that runtime code |
|
|||
1055 | # (such as magics) can access it. This is because during the |
|
|||
1056 | # read-eval loop, it gets temporarily overwritten (to deal with GUI |
|
|||
1057 | # frameworks). |
|
|||
1058 | self.sys_excepthook = sys.excepthook |
|
|||
1059 |
|
||||
1060 |
|
||||
1061 | def set_custom_exc(self,exc_tuple,handler): |
|
|||
1062 | """set_custom_exc(exc_tuple,handler) |
|
|||
1063 |
|
||||
1064 | Set a custom exception handler, which will be called if any of the |
|
|||
1065 | exceptions in exc_tuple occur in the mainloop (specifically, in the |
|
|||
1066 | runcode() method. |
|
|||
1067 |
|
||||
1068 | Inputs: |
|
|||
1069 |
|
||||
1070 | - exc_tuple: a *tuple* of valid exceptions to call the defined |
|
|||
1071 | handler for. It is very important that you use a tuple, and NOT A |
|
|||
1072 | LIST here, because of the way Python's except statement works. If |
|
|||
1073 | you only want to trap a single exception, use a singleton tuple: |
|
|||
1074 |
|
||||
1075 | exc_tuple == (MyCustomException,) |
|
|||
1076 |
|
||||
1077 | - handler: this must be defined as a function with the following |
|
|||
1078 | basic interface: def my_handler(self,etype,value,tb). |
|
|||
1079 |
|
||||
1080 | This will be made into an instance method (via new.instancemethod) |
|
|||
1081 | of IPython itself, and it will be called if any of the exceptions |
|
|||
1082 | listed in the exc_tuple are caught. If the handler is None, an |
|
|||
1083 | internal basic one is used, which just prints basic info. |
|
|||
1084 |
|
||||
1085 | WARNING: by putting in your own exception handler into IPython's main |
|
|||
1086 | execution loop, you run a very good chance of nasty crashes. This |
|
|||
1087 | facility should only be used if you really know what you are doing.""" |
|
|||
1088 |
|
||||
1089 | assert type(exc_tuple)==type(()) , \ |
|
|||
1090 | "The custom exceptions must be given AS A TUPLE." |
|
|||
1091 |
|
||||
1092 | def dummy_handler(self,etype,value,tb): |
|
|||
1093 | print '*** Simple custom exception handler ***' |
|
|||
1094 | print 'Exception type :',etype |
|
|||
1095 | print 'Exception value:',value |
|
|||
1096 | print 'Traceback :',tb |
|
|||
1097 | print 'Source code :','\n'.join(self.buffer) |
|
|||
1098 |
|
||||
1099 | if handler is None: handler = dummy_handler |
|
|||
1100 |
|
||||
1101 | self.CustomTB = new.instancemethod(handler,self,self.__class__) |
|
|||
1102 | self.custom_exceptions = exc_tuple |
|
|||
1103 |
|
||||
1104 | def set_custom_completer(self,completer,pos=0): |
|
|||
1105 | """set_custom_completer(completer,pos=0) |
|
|||
1106 |
|
||||
1107 | Adds a new custom completer function. |
|
|||
1108 |
|
||||
1109 | The position argument (defaults to 0) is the index in the completers |
|
|||
1110 | list where you want the completer to be inserted.""" |
|
|||
1111 |
|
||||
1112 | newcomp = new.instancemethod(completer,self.Completer, |
|
|||
1113 | self.Completer.__class__) |
|
|||
1114 | self.Completer.matchers.insert(pos,newcomp) |
|
|||
1115 |
|
||||
1116 | def set_completer(self): |
|
|||
1117 | """reset readline's completer to be our own.""" |
|
|||
1118 | self.readline.set_completer(self.Completer.complete) |
|
|||
1119 |
|
||||
1120 | def _get_call_pdb(self): |
|
|||
1121 | return self._call_pdb |
|
|||
1122 |
|
||||
1123 | def _set_call_pdb(self,val): |
|
|||
1124 |
|
||||
1125 | if val not in (0,1,False,True): |
|
|||
1126 | raise ValueError,'new call_pdb value must be boolean' |
|
|||
1127 |
|
||||
1128 | # store value in instance |
|
|||
1129 | self._call_pdb = val |
|
|||
1130 |
|
||||
1131 | # notify the actual exception handlers |
|
|||
1132 | self.InteractiveTB.call_pdb = val |
|
|||
1133 | if self.isthreaded: |
|
|||
1134 | try: |
|
|||
1135 | self.sys_excepthook.call_pdb = val |
|
|||
1136 | except: |
|
|||
1137 | warn('Failed to activate pdb for threaded exception handler') |
|
|||
1138 |
|
||||
1139 | call_pdb = property(_get_call_pdb,_set_call_pdb,None, |
|
|||
1140 | 'Control auto-activation of pdb at exceptions') |
|
|||
1141 |
|
||||
1142 | # These special functions get installed in the builtin namespace, to |
|
|||
1143 | # provide programmatic (pure python) access to magics, aliases and system |
|
|||
1144 | # calls. This is important for logging, user scripting, and more. |
|
|||
1145 |
|
||||
1146 | # We are basically exposing, via normal python functions, the three |
|
|||
1147 | # mechanisms in which ipython offers special call modes (magics for |
|
|||
1148 | # internal control, aliases for direct system access via pre-selected |
|
|||
1149 | # names, and !cmd for calling arbitrary system commands). |
|
|||
1150 |
|
||||
1151 | def ipmagic(self,arg_s): |
|
|||
1152 | """Call a magic function by name. |
|
|||
1153 |
|
||||
1154 | Input: a string containing the name of the magic function to call and any |
|
|||
1155 | additional arguments to be passed to the magic. |
|
|||
1156 |
|
||||
1157 | ipmagic('name -opt foo bar') is equivalent to typing at the ipython |
|
|||
1158 | prompt: |
|
|||
1159 |
|
||||
1160 | In[1]: %name -opt foo bar |
|
|||
1161 |
|
||||
1162 | To call a magic without arguments, simply use ipmagic('name'). |
|
|||
1163 |
|
||||
1164 | This provides a proper Python function to call IPython's magics in any |
|
|||
1165 | valid Python code you can type at the interpreter, including loops and |
|
|||
1166 | compound statements. It is added by IPython to the Python builtin |
|
|||
1167 | namespace upon initialization.""" |
|
|||
1168 |
|
||||
1169 | args = arg_s.split(' ',1) |
|
|||
1170 | magic_name = args[0] |
|
|||
1171 | magic_name = magic_name.lstrip(self.ESC_MAGIC) |
|
|||
1172 |
|
||||
1173 | try: |
|
|||
1174 | magic_args = args[1] |
|
|||
1175 | except IndexError: |
|
|||
1176 | magic_args = '' |
|
|||
1177 | fn = getattr(self,'magic_'+magic_name,None) |
|
|||
1178 | if fn is None: |
|
|||
1179 | error("Magic function `%s` not found." % magic_name) |
|
|||
1180 | else: |
|
|||
1181 | magic_args = self.var_expand(magic_args,1) |
|
|||
1182 | return fn(magic_args) |
|
|||
1183 |
|
||||
1184 | def ipalias(self,arg_s): |
|
|||
1185 | """Call an alias by name. |
|
|||
1186 |
|
||||
1187 | Input: a string containing the name of the alias to call and any |
|
|||
1188 | additional arguments to be passed to the magic. |
|
|||
1189 |
|
||||
1190 | ipalias('name -opt foo bar') is equivalent to typing at the ipython |
|
|||
1191 | prompt: |
|
|||
1192 |
|
||||
1193 | In[1]: name -opt foo bar |
|
|||
1194 |
|
||||
1195 | To call an alias without arguments, simply use ipalias('name'). |
|
|||
1196 |
|
||||
1197 | This provides a proper Python function to call IPython's aliases in any |
|
|||
1198 | valid Python code you can type at the interpreter, including loops and |
|
|||
1199 | compound statements. It is added by IPython to the Python builtin |
|
|||
1200 | namespace upon initialization.""" |
|
|||
1201 |
|
||||
1202 | args = arg_s.split(' ',1) |
|
|||
1203 | alias_name = args[0] |
|
|||
1204 | try: |
|
|||
1205 | alias_args = args[1] |
|
|||
1206 | except IndexError: |
|
|||
1207 | alias_args = '' |
|
|||
1208 | if alias_name in self.alias_table: |
|
|||
1209 | self.call_alias(alias_name,alias_args) |
|
|||
1210 | else: |
|
|||
1211 | error("Alias `%s` not found." % alias_name) |
|
|||
1212 |
|
||||
1213 | def ipsystem(self,arg_s): |
|
|||
1214 | """Make a system call, using IPython.""" |
|
|||
1215 |
|
||||
1216 | self.system(arg_s) |
|
|||
1217 |
|
||||
1218 | def complete(self,text): |
|
|||
1219 | """Return a sorted list of all possible completions on text. |
|
|||
1220 |
|
||||
1221 | Inputs: |
|
|||
1222 |
|
||||
1223 | - text: a string of text to be completed on. |
|
|||
1224 |
|
||||
1225 | This is a wrapper around the completion mechanism, similar to what |
|
|||
1226 | readline does at the command line when the TAB key is hit. By |
|
|||
1227 | exposing it as a method, it can be used by other non-readline |
|
|||
1228 | environments (such as GUIs) for text completion. |
|
|||
1229 |
|
||||
1230 | Simple usage example: |
|
|||
1231 |
|
||||
1232 | In [7]: x = 'hello' |
|
|||
1233 |
|
||||
1234 | In [8]: x |
|
|||
1235 | Out[8]: 'hello' |
|
|||
1236 |
|
||||
1237 | In [9]: print x |
|
|||
1238 | hello |
|
|||
1239 |
|
||||
1240 | In [10]: _ip.IP.complete('x.l') |
|
|||
1241 | Out[10]: ['x.ljust', 'x.lower', 'x.lstrip'] |
|
|||
1242 | """ |
|
|||
1243 |
|
||||
1244 | complete = self.Completer.complete |
|
|||
1245 | state = 0 |
|
|||
1246 | # use a dict so we get unique keys, since ipyhton's multiple |
|
|||
1247 | # completers can return duplicates. When we make 2.4 a requirement, |
|
|||
1248 | # start using sets instead, which are faster. |
|
|||
1249 | comps = {} |
|
|||
1250 | while True: |
|
|||
1251 | newcomp = complete(text,state,line_buffer=text) |
|
|||
1252 | if newcomp is None: |
|
|||
1253 | break |
|
|||
1254 | comps[newcomp] = 1 |
|
|||
1255 | state += 1 |
|
|||
1256 | outcomps = comps.keys() |
|
|||
1257 | outcomps.sort() |
|
|||
1258 | #print "T:",text,"OC:",outcomps # dbg |
|
|||
1259 | #print "vars:",self.user_ns.keys() |
|
|||
1260 | return outcomps |
|
|||
1261 |
|
||||
1262 | def set_completer_frame(self, frame=None): |
|
|||
1263 | if frame: |
|
|||
1264 | self.Completer.namespace = frame.f_locals |
|
|||
1265 | self.Completer.global_namespace = frame.f_globals |
|
|||
1266 | else: |
|
|||
1267 | self.Completer.namespace = self.user_ns |
|
|||
1268 | self.Completer.global_namespace = self.user_global_ns |
|
|||
1269 |
|
||||
1270 | def init_auto_alias(self): |
|
|||
1271 | """Define some aliases automatically. |
|
|||
1272 |
|
||||
1273 | These are ALL parameter-less aliases""" |
|
|||
1274 |
|
||||
1275 | for alias,cmd in self.auto_alias: |
|
|||
1276 | self.getapi().defalias(alias,cmd) |
|
|||
1277 |
|
||||
1278 |
|
||||
1279 | def alias_table_validate(self,verbose=0): |
|
|||
1280 | """Update information about the alias table. |
|
|||
1281 |
|
||||
1282 | In particular, make sure no Python keywords/builtins are in it.""" |
|
|||
1283 |
|
||||
1284 | no_alias = self.no_alias |
|
|||
1285 | for k in self.alias_table.keys(): |
|
|||
1286 | if k in no_alias: |
|
|||
1287 | del self.alias_table[k] |
|
|||
1288 | if verbose: |
|
|||
1289 | print ("Deleting alias <%s>, it's a Python " |
|
|||
1290 | "keyword or builtin." % k) |
|
|||
1291 |
|
||||
1292 | def set_autoindent(self,value=None): |
|
|||
1293 | """Set the autoindent flag, checking for readline support. |
|
|||
1294 |
|
||||
1295 | If called with no arguments, it acts as a toggle.""" |
|
|||
1296 |
|
||||
1297 | if not self.has_readline: |
|
|||
1298 | if os.name == 'posix': |
|
|||
1299 | warn("The auto-indent feature requires the readline library") |
|
|||
1300 | self.autoindent = 0 |
|
|||
1301 | return |
|
|||
1302 | if value is None: |
|
|||
1303 | self.autoindent = not self.autoindent |
|
|||
1304 | else: |
|
|||
1305 | self.autoindent = value |
|
|||
1306 |
|
||||
1307 | def rc_set_toggle(self,rc_field,value=None): |
|
|||
1308 | """Set or toggle a field in IPython's rc config. structure. |
|
|||
1309 |
|
||||
1310 | If called with no arguments, it acts as a toggle. |
|
|||
1311 |
|
||||
1312 | If called with a non-existent field, the resulting AttributeError |
|
|||
1313 | exception will propagate out.""" |
|
|||
1314 |
|
||||
1315 | rc_val = getattr(self.rc,rc_field) |
|
|||
1316 | if value is None: |
|
|||
1317 | value = not rc_val |
|
|||
1318 | setattr(self.rc,rc_field,value) |
|
|||
1319 |
|
||||
1320 | def user_setup(self,ipythondir,rc_suffix,mode='install'): |
|
|||
1321 | """Install the user configuration directory. |
|
|||
1322 |
|
||||
1323 | Notes |
|
|||
1324 | ----- |
|
|||
1325 | DEPRECATED: use the top-level user_setup() function instead. |
|
|||
1326 | """ |
|
|||
1327 | return user_setup(ipythondir,rc_suffix,mode) |
|
|||
1328 |
|
||||
1329 | def atexit_operations(self): |
|
|||
1330 | """This will be executed at the time of exit. |
|
|||
1331 |
|
||||
1332 | Saving of persistent data should be performed here. """ |
|
|||
1333 |
|
||||
1334 | #print '*** IPython exit cleanup ***' # dbg |
|
|||
1335 | # input history |
|
|||
1336 | self.savehist() |
|
|||
1337 |
|
||||
1338 | # Cleanup all tempfiles left around |
|
|||
1339 | for tfile in self.tempfiles: |
|
|||
1340 | try: |
|
|||
1341 | os.unlink(tfile) |
|
|||
1342 | except OSError: |
|
|||
1343 | pass |
|
|||
1344 |
|
||||
1345 | # Clear all user namespaces to release all references cleanly. |
|
|||
1346 | self.reset() |
|
|||
1347 |
|
||||
1348 | # Run user hooks |
|
|||
1349 | self.hooks.shutdown_hook() |
|
|||
1350 |
|
||||
1351 | def reset(self): |
|
|||
1352 | """Clear all internal namespaces. |
|
|||
1353 |
|
||||
1354 | Note that this is much more aggressive than %reset, since it clears |
|
|||
1355 | fully all namespaces, as well as all input/output lists. |
|
|||
1356 | """ |
|
|||
1357 | for ns in self.ns_refs_table: |
|
|||
1358 | ns.clear() |
|
|||
1359 |
|
||||
1360 | # Clear input and output histories |
|
|||
1361 | self.input_hist[:] = [] |
|
|||
1362 | self.input_hist_raw[:] = [] |
|
|||
1363 | self.output_hist.clear() |
|
|||
1364 | # Restore the user namespaces to minimal usability |
|
|||
1365 | self.init_namespaces() |
|
|||
1366 |
|
||||
1367 | def savehist(self): |
|
|||
1368 | """Save input history to a file (via readline library).""" |
|
|||
1369 |
|
||||
1370 | if not self.has_readline: |
|
|||
1371 | return |
|
|||
1372 |
|
||||
1373 | try: |
|
|||
1374 | self.readline.write_history_file(self.histfile) |
|
|||
1375 | except: |
|
|||
1376 | print 'Unable to save IPython command history to file: ' + \ |
|
|||
1377 | `self.histfile` |
|
|||
1378 |
|
||||
1379 | def reloadhist(self): |
|
|||
1380 | """Reload the input history from disk file.""" |
|
|||
1381 |
|
||||
1382 | if self.has_readline: |
|
|||
1383 | try: |
|
|||
1384 | self.readline.clear_history() |
|
|||
1385 | self.readline.read_history_file(self.shell.histfile) |
|
|||
1386 | except AttributeError: |
|
|||
1387 | pass |
|
|||
1388 |
|
||||
1389 |
|
||||
1390 | def history_saving_wrapper(self, func): |
|
|||
1391 | """ Wrap func for readline history saving |
|
|||
1392 |
|
||||
1393 | Convert func into callable that saves & restores |
|
|||
1394 | history around the call """ |
|
|||
1395 |
|
||||
1396 | if not self.has_readline: |
|
|||
1397 | return func |
|
|||
1398 |
|
||||
1399 | def wrapper(): |
|
|||
1400 | self.savehist() |
|
|||
1401 | try: |
|
|||
1402 | func() |
|
|||
1403 | finally: |
|
|||
1404 | readline.read_history_file(self.histfile) |
|
|||
1405 | return wrapper |
|
|||
1406 |
|
||||
1407 | def pre_readline(self): |
|
|||
1408 | """readline hook to be used at the start of each line. |
|
|||
1409 |
|
||||
1410 | Currently it handles auto-indent only.""" |
|
|||
1411 |
|
||||
1412 | #debugx('self.indent_current_nsp','pre_readline:') |
|
|||
1413 |
|
||||
1414 | if self.rl_do_indent: |
|
|||
1415 | self.readline.insert_text(self.indent_current_str()) |
|
|||
1416 | if self.rl_next_input is not None: |
|
|||
1417 | self.readline.insert_text(self.rl_next_input) |
|
|||
1418 | self.rl_next_input = None |
|
|||
1419 |
|
||||
1420 | def init_readline(self): |
|
|||
1421 | """Command history completion/saving/reloading.""" |
|
|||
1422 |
|
||||
1423 |
|
||||
1424 | import IPython.rlineimpl as readline |
|
|||
1425 |
|
||||
1426 | if not readline.have_readline: |
|
|||
1427 | self.has_readline = 0 |
|
|||
1428 | self.readline = None |
|
|||
1429 | # no point in bugging windows users with this every time: |
|
|||
1430 | warn('Readline services not available on this platform.') |
|
|||
1431 | else: |
|
|||
1432 | sys.modules['readline'] = readline |
|
|||
1433 | import atexit |
|
|||
1434 | from IPython.completer import IPCompleter |
|
|||
1435 | self.Completer = IPCompleter(self, |
|
|||
1436 | self.user_ns, |
|
|||
1437 | self.user_global_ns, |
|
|||
1438 | self.rc.readline_omit__names, |
|
|||
1439 | self.alias_table) |
|
|||
1440 | sdisp = self.strdispatchers.get('complete_command', StrDispatch()) |
|
|||
1441 | self.strdispatchers['complete_command'] = sdisp |
|
|||
1442 | self.Completer.custom_completers = sdisp |
|
|||
1443 | # Platform-specific configuration |
|
|||
1444 | if os.name == 'nt': |
|
|||
1445 | self.readline_startup_hook = readline.set_pre_input_hook |
|
|||
1446 | else: |
|
|||
1447 | self.readline_startup_hook = readline.set_startup_hook |
|
|||
1448 |
|
||||
1449 | # Load user's initrc file (readline config) |
|
|||
1450 | # Or if libedit is used, load editrc. |
|
|||
1451 | inputrc_name = os.environ.get('INPUTRC') |
|
|||
1452 | if inputrc_name is None: |
|
|||
1453 | home_dir = get_home_dir() |
|
|||
1454 | if home_dir is not None: |
|
|||
1455 | inputrc_name = '.inputrc' |
|
|||
1456 | if readline.uses_libedit: |
|
|||
1457 | inputrc_name = '.editrc' |
|
|||
1458 | inputrc_name = os.path.join(home_dir, inputrc_name) |
|
|||
1459 | if os.path.isfile(inputrc_name): |
|
|||
1460 | try: |
|
|||
1461 | readline.read_init_file(inputrc_name) |
|
|||
1462 | except: |
|
|||
1463 | warn('Problems reading readline initialization file <%s>' |
|
|||
1464 | % inputrc_name) |
|
|||
1465 |
|
||||
1466 | self.has_readline = 1 |
|
|||
1467 | self.readline = readline |
|
|||
1468 | # save this in sys so embedded copies can restore it properly |
|
|||
1469 | sys.ipcompleter = self.Completer.complete |
|
|||
1470 | self.set_completer() |
|
|||
1471 |
|
||||
1472 | # Configure readline according to user's prefs |
|
|||
1473 | # This is only done if GNU readline is being used. If libedit |
|
|||
1474 | # is being used (as on Leopard) the readline config is |
|
|||
1475 | # not run as the syntax for libedit is different. |
|
|||
1476 | if not readline.uses_libedit: |
|
|||
1477 | for rlcommand in self.rc.readline_parse_and_bind: |
|
|||
1478 | #print "loading rl:",rlcommand # dbg |
|
|||
1479 | readline.parse_and_bind(rlcommand) |
|
|||
1480 |
|
||||
1481 | # Remove some chars from the delimiters list. If we encounter |
|
|||
1482 | # unicode chars, discard them. |
|
|||
1483 | delims = readline.get_completer_delims().encode("ascii", "ignore") |
|
|||
1484 | delims = delims.translate(string._idmap, |
|
|||
1485 | self.rc.readline_remove_delims) |
|
|||
1486 | readline.set_completer_delims(delims) |
|
|||
1487 | # otherwise we end up with a monster history after a while: |
|
|||
1488 | readline.set_history_length(1000) |
|
|||
1489 | try: |
|
|||
1490 | #print '*** Reading readline history' # dbg |
|
|||
1491 | readline.read_history_file(self.histfile) |
|
|||
1492 | except IOError: |
|
|||
1493 | pass # It doesn't exist yet. |
|
|||
1494 |
|
||||
1495 | atexit.register(self.atexit_operations) |
|
|||
1496 | del atexit |
|
|||
1497 |
|
||||
1498 | # Configure auto-indent for all platforms |
|
|||
1499 | self.set_autoindent(self.rc.autoindent) |
|
|||
1500 |
|
||||
1501 | def ask_yes_no(self,prompt,default=True): |
|
|||
1502 | if self.rc.quiet: |
|
|||
1503 | return True |
|
|||
1504 | return ask_yes_no(prompt,default) |
|
|||
1505 |
|
||||
1506 | def new_main_mod(self,ns=None): |
|
|||
1507 | """Return a new 'main' module object for user code execution. |
|
|||
1508 | """ |
|
|||
1509 | main_mod = self._user_main_module |
|
|||
1510 | init_fakemod_dict(main_mod,ns) |
|
|||
1511 | return main_mod |
|
|||
1512 |
|
||||
1513 | def cache_main_mod(self,ns,fname): |
|
|||
1514 | """Cache a main module's namespace. |
|
|||
1515 |
|
||||
1516 | When scripts are executed via %run, we must keep a reference to the |
|
|||
1517 | namespace of their __main__ module (a FakeModule instance) around so |
|
|||
1518 | that Python doesn't clear it, rendering objects defined therein |
|
|||
1519 | useless. |
|
|||
1520 |
|
||||
1521 | This method keeps said reference in a private dict, keyed by the |
|
|||
1522 | absolute path of the module object (which corresponds to the script |
|
|||
1523 | path). This way, for multiple executions of the same script we only |
|
|||
1524 | keep one copy of the namespace (the last one), thus preventing memory |
|
|||
1525 | leaks from old references while allowing the objects from the last |
|
|||
1526 | execution to be accessible. |
|
|||
1527 |
|
||||
1528 | Note: we can not allow the actual FakeModule instances to be deleted, |
|
|||
1529 | because of how Python tears down modules (it hard-sets all their |
|
|||
1530 | references to None without regard for reference counts). This method |
|
|||
1531 | must therefore make a *copy* of the given namespace, to allow the |
|
|||
1532 | original module's __dict__ to be cleared and reused. |
|
|||
1533 |
|
||||
1534 |
|
||||
1535 | Parameters |
|
|||
1536 | ---------- |
|
|||
1537 | ns : a namespace (a dict, typically) |
|
|||
1538 |
|
||||
1539 | fname : str |
|
|||
1540 | Filename associated with the namespace. |
|
|||
1541 |
|
||||
1542 | Examples |
|
|||
1543 | -------- |
|
|||
1544 |
|
||||
1545 | In [10]: import IPython |
|
|||
1546 |
|
||||
1547 | In [11]: _ip.IP.cache_main_mod(IPython.__dict__,IPython.__file__) |
|
|||
1548 |
|
||||
1549 | In [12]: IPython.__file__ in _ip.IP._main_ns_cache |
|
|||
1550 | Out[12]: True |
|
|||
1551 | """ |
|
|||
1552 | self._main_ns_cache[os.path.abspath(fname)] = ns.copy() |
|
|||
1553 |
|
||||
1554 | def clear_main_mod_cache(self): |
|
|||
1555 | """Clear the cache of main modules. |
|
|||
1556 |
|
||||
1557 | Mainly for use by utilities like %reset. |
|
|||
1558 |
|
||||
1559 | Examples |
|
|||
1560 | -------- |
|
|||
1561 |
|
||||
1562 | In [15]: import IPython |
|
|||
1563 |
|
||||
1564 | In [16]: _ip.IP.cache_main_mod(IPython.__dict__,IPython.__file__) |
|
|||
1565 |
|
||||
1566 | In [17]: len(_ip.IP._main_ns_cache) > 0 |
|
|||
1567 | Out[17]: True |
|
|||
1568 |
|
||||
1569 | In [18]: _ip.IP.clear_main_mod_cache() |
|
|||
1570 |
|
||||
1571 | In [19]: len(_ip.IP._main_ns_cache) == 0 |
|
|||
1572 | Out[19]: True |
|
|||
1573 | """ |
|
|||
1574 | self._main_ns_cache.clear() |
|
|||
1575 |
|
||||
1576 | def _should_recompile(self,e): |
|
|||
1577 | """Utility routine for edit_syntax_error""" |
|
|||
1578 |
|
||||
1579 | if e.filename in ('<ipython console>','<input>','<string>', |
|
|||
1580 | '<console>','<BackgroundJob compilation>', |
|
|||
1581 | None): |
|
|||
1582 |
|
||||
1583 | return False |
|
|||
1584 | try: |
|
|||
1585 | if (self.rc.autoedit_syntax and |
|
|||
1586 | not self.ask_yes_no('Return to editor to correct syntax error? ' |
|
|||
1587 | '[Y/n] ','y')): |
|
|||
1588 | return False |
|
|||
1589 | except EOFError: |
|
|||
1590 | return False |
|
|||
1591 |
|
||||
1592 | def int0(x): |
|
|||
1593 | try: |
|
|||
1594 | return int(x) |
|
|||
1595 | except TypeError: |
|
|||
1596 | return 0 |
|
|||
1597 | # always pass integer line and offset values to editor hook |
|
|||
1598 | try: |
|
|||
1599 | self.hooks.fix_error_editor(e.filename, |
|
|||
1600 | int0(e.lineno),int0(e.offset),e.msg) |
|
|||
1601 | except IPython.ipapi.TryNext: |
|
|||
1602 | warn('Could not open editor') |
|
|||
1603 | return False |
|
|||
1604 | return True |
|
|||
1605 |
|
||||
1606 | def edit_syntax_error(self): |
|
|||
1607 | """The bottom half of the syntax error handler called in the main loop. |
|
|||
1608 |
|
||||
1609 | Loop until syntax error is fixed or user cancels. |
|
|||
1610 | """ |
|
|||
1611 |
|
||||
1612 | while self.SyntaxTB.last_syntax_error: |
|
|||
1613 | # copy and clear last_syntax_error |
|
|||
1614 | err = self.SyntaxTB.clear_err_state() |
|
|||
1615 | if not self._should_recompile(err): |
|
|||
1616 | return |
|
|||
1617 | try: |
|
|||
1618 | # may set last_syntax_error again if a SyntaxError is raised |
|
|||
1619 | self.safe_execfile(err.filename,self.user_ns) |
|
|||
1620 | except: |
|
|||
1621 | self.showtraceback() |
|
|||
1622 | else: |
|
|||
1623 | try: |
|
|||
1624 | f = file(err.filename) |
|
|||
1625 | try: |
|
|||
1626 | sys.displayhook(f.read()) |
|
|||
1627 | finally: |
|
|||
1628 | f.close() |
|
|||
1629 | except: |
|
|||
1630 | self.showtraceback() |
|
|||
1631 |
|
||||
1632 | def showsyntaxerror(self, filename=None): |
|
|||
1633 | """Display the syntax error that just occurred. |
|
|||
1634 |
|
||||
1635 | This doesn't display a stack trace because there isn't one. |
|
|||
1636 |
|
||||
1637 | If a filename is given, it is stuffed in the exception instead |
|
|||
1638 | of what was there before (because Python's parser always uses |
|
|||
1639 | "<string>" when reading from a string). |
|
|||
1640 | """ |
|
|||
1641 | etype, value, last_traceback = sys.exc_info() |
|
|||
1642 |
|
||||
1643 | # See note about these variables in showtraceback() below |
|
|||
1644 | sys.last_type = etype |
|
|||
1645 | sys.last_value = value |
|
|||
1646 | sys.last_traceback = last_traceback |
|
|||
1647 |
|
||||
1648 | if filename and etype is SyntaxError: |
|
|||
1649 | # Work hard to stuff the correct filename in the exception |
|
|||
1650 | try: |
|
|||
1651 | msg, (dummy_filename, lineno, offset, line) = value |
|
|||
1652 | except: |
|
|||
1653 | # Not the format we expect; leave it alone |
|
|||
1654 | pass |
|
|||
1655 | else: |
|
|||
1656 | # Stuff in the right filename |
|
|||
1657 | try: |
|
|||
1658 | # Assume SyntaxError is a class exception |
|
|||
1659 | value = SyntaxError(msg, (filename, lineno, offset, line)) |
|
|||
1660 | except: |
|
|||
1661 | # If that failed, assume SyntaxError is a string |
|
|||
1662 | value = msg, (filename, lineno, offset, line) |
|
|||
1663 | self.SyntaxTB(etype,value,[]) |
|
|||
1664 |
|
||||
1665 | def debugger(self,force=False): |
|
|||
1666 | """Call the pydb/pdb debugger. |
|
|||
1667 |
|
||||
1668 | Keywords: |
|
|||
1669 |
|
||||
1670 | - force(False): by default, this routine checks the instance call_pdb |
|
|||
1671 | flag and does not actually invoke the debugger if the flag is false. |
|
|||
1672 | The 'force' option forces the debugger to activate even if the flag |
|
|||
1673 | is false. |
|
|||
1674 | """ |
|
|||
1675 |
|
||||
1676 | if not (force or self.call_pdb): |
|
|||
1677 | return |
|
|||
1678 |
|
||||
1679 | if not hasattr(sys,'last_traceback'): |
|
|||
1680 | error('No traceback has been produced, nothing to debug.') |
|
|||
1681 | return |
|
|||
1682 |
|
||||
1683 | # use pydb if available |
|
|||
1684 | if Debugger.has_pydb: |
|
|||
1685 | from pydb import pm |
|
|||
1686 | else: |
|
|||
1687 | # fallback to our internal debugger |
|
|||
1688 | pm = lambda : self.InteractiveTB.debugger(force=True) |
|
|||
1689 | self.history_saving_wrapper(pm)() |
|
|||
1690 |
|
||||
1691 | def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None): |
|
|||
1692 | """Display the exception that just occurred. |
|
|||
1693 |
|
||||
1694 | If nothing is known about the exception, this is the method which |
|
|||
1695 | should be used throughout the code for presenting user tracebacks, |
|
|||
1696 | rather than directly invoking the InteractiveTB object. |
|
|||
1697 |
|
||||
1698 | A specific showsyntaxerror() also exists, but this method can take |
|
|||
1699 | care of calling it if needed, so unless you are explicitly catching a |
|
|||
1700 | SyntaxError exception, don't try to analyze the stack manually and |
|
|||
1701 | simply call this method.""" |
|
|||
1702 |
|
||||
1703 |
|
||||
1704 | # Though this won't be called by syntax errors in the input line, |
|
|||
1705 | # there may be SyntaxError cases whith imported code. |
|
|||
1706 |
|
||||
1707 | try: |
|
|||
1708 | if exc_tuple is None: |
|
|||
1709 | etype, value, tb = sys.exc_info() |
|
|||
1710 | else: |
|
|||
1711 | etype, value, tb = exc_tuple |
|
|||
1712 |
|
||||
1713 | if etype is SyntaxError: |
|
|||
1714 | self.showsyntaxerror(filename) |
|
|||
1715 | elif etype is IPython.ipapi.UsageError: |
|
|||
1716 | print "UsageError:", value |
|
|||
1717 | else: |
|
|||
1718 | # WARNING: these variables are somewhat deprecated and not |
|
|||
1719 | # necessarily safe to use in a threaded environment, but tools |
|
|||
1720 | # like pdb depend on their existence, so let's set them. If we |
|
|||
1721 | # find problems in the field, we'll need to revisit their use. |
|
|||
1722 | sys.last_type = etype |
|
|||
1723 | sys.last_value = value |
|
|||
1724 | sys.last_traceback = tb |
|
|||
1725 |
|
||||
1726 | if etype in self.custom_exceptions: |
|
|||
1727 | self.CustomTB(etype,value,tb) |
|
|||
1728 | else: |
|
|||
1729 | self.InteractiveTB(etype,value,tb,tb_offset=tb_offset) |
|
|||
1730 | if self.InteractiveTB.call_pdb and self.has_readline: |
|
|||
1731 | # pdb mucks up readline, fix it back |
|
|||
1732 | self.set_completer() |
|
|||
1733 | except KeyboardInterrupt: |
|
|||
1734 | self.write("\nKeyboardInterrupt\n") |
|
|||
1735 |
|
||||
1736 | def mainloop(self,banner=None): |
|
|||
1737 | """Creates the local namespace and starts the mainloop. |
|
|||
1738 |
|
||||
1739 | If an optional banner argument is given, it will override the |
|
|||
1740 | internally created default banner.""" |
|
|||
1741 |
|
||||
1742 | if self.rc.c: # Emulate Python's -c option |
|
|||
1743 | self.exec_init_cmd() |
|
|||
1744 | if banner is None: |
|
|||
1745 | if not self.rc.banner: |
|
|||
1746 | banner = '' |
|
|||
1747 | # banner is string? Use it directly! |
|
|||
1748 | elif isinstance(self.rc.banner,basestring): |
|
|||
1749 | banner = self.rc.banner |
|
|||
1750 | else: |
|
|||
1751 | banner = self.BANNER+self.banner2 |
|
|||
1752 |
|
||||
1753 | # if you run stuff with -c <cmd>, raw hist is not updated |
|
|||
1754 | # ensure that it's in sync |
|
|||
1755 | if len(self.input_hist) != len (self.input_hist_raw): |
|
|||
1756 | self.input_hist_raw = InputList(self.input_hist) |
|
|||
1757 |
|
||||
1758 | while 1: |
|
|||
1759 | try: |
|
|||
1760 | self.interact(banner) |
|
|||
1761 | #self.interact_with_readline() |
|
|||
1762 |
|
||||
1763 | # XXX for testing of a readline-decoupled repl loop, call |
|
|||
1764 | # interact_with_readline above |
|
|||
1765 |
|
||||
1766 | break |
|
|||
1767 | except KeyboardInterrupt: |
|
|||
1768 | # this should not be necessary, but KeyboardInterrupt |
|
|||
1769 | # handling seems rather unpredictable... |
|
|||
1770 | self.write("\nKeyboardInterrupt in interact()\n") |
|
|||
1771 |
|
||||
1772 | def exec_init_cmd(self): |
|
|||
1773 | """Execute a command given at the command line. |
|
|||
1774 |
|
||||
1775 | This emulates Python's -c option.""" |
|
|||
1776 |
|
||||
1777 | #sys.argv = ['-c'] |
|
|||
1778 | self.push(self.prefilter(self.rc.c, False)) |
|
|||
1779 | if not self.rc.interact: |
|
|||
1780 | self.ask_exit() |
|
|||
1781 |
|
||||
1782 | def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0): |
|
|||
1783 | """Embeds IPython into a running python program. |
|
|||
1784 |
|
||||
1785 | Input: |
|
|||
1786 |
|
||||
1787 | - header: An optional header message can be specified. |
|
|||
1788 |
|
||||
1789 | - local_ns, global_ns: working namespaces. If given as None, the |
|
|||
1790 | IPython-initialized one is updated with __main__.__dict__, so that |
|
|||
1791 | program variables become visible but user-specific configuration |
|
|||
1792 | remains possible. |
|
|||
1793 |
|
||||
1794 | - stack_depth: specifies how many levels in the stack to go to |
|
|||
1795 | looking for namespaces (when local_ns and global_ns are None). This |
|
|||
1796 | allows an intermediate caller to make sure that this function gets |
|
|||
1797 | the namespace from the intended level in the stack. By default (0) |
|
|||
1798 | it will get its locals and globals from the immediate caller. |
|
|||
1799 |
|
||||
1800 | Warning: it's possible to use this in a program which is being run by |
|
|||
1801 | IPython itself (via %run), but some funny things will happen (a few |
|
|||
1802 | globals get overwritten). In the future this will be cleaned up, as |
|
|||
1803 | there is no fundamental reason why it can't work perfectly.""" |
|
|||
1804 |
|
||||
1805 | # Get locals and globals from caller |
|
|||
1806 | if local_ns is None or global_ns is None: |
|
|||
1807 | call_frame = sys._getframe(stack_depth).f_back |
|
|||
1808 |
|
||||
1809 | if local_ns is None: |
|
|||
1810 | local_ns = call_frame.f_locals |
|
|||
1811 | if global_ns is None: |
|
|||
1812 | global_ns = call_frame.f_globals |
|
|||
1813 |
|
||||
1814 | # Update namespaces and fire up interpreter |
|
|||
1815 |
|
||||
1816 | # The global one is easy, we can just throw it in |
|
|||
1817 | self.user_global_ns = global_ns |
|
|||
1818 |
|
||||
1819 | # but the user/local one is tricky: ipython needs it to store internal |
|
|||
1820 | # data, but we also need the locals. We'll copy locals in the user |
|
|||
1821 | # one, but will track what got copied so we can delete them at exit. |
|
|||
1822 | # This is so that a later embedded call doesn't see locals from a |
|
|||
1823 | # previous call (which most likely existed in a separate scope). |
|
|||
1824 | local_varnames = local_ns.keys() |
|
|||
1825 | self.user_ns.update(local_ns) |
|
|||
1826 | #self.user_ns['local_ns'] = local_ns # dbg |
|
|||
1827 |
|
||||
1828 | # Patch for global embedding to make sure that things don't overwrite |
|
|||
1829 | # user globals accidentally. Thanks to Richard <rxe@renre-europe.com> |
|
|||
1830 | # FIXME. Test this a bit more carefully (the if.. is new) |
|
|||
1831 | if local_ns is None and global_ns is None: |
|
|||
1832 | self.user_global_ns.update(__main__.__dict__) |
|
|||
1833 |
|
||||
1834 | # make sure the tab-completer has the correct frame information, so it |
|
|||
1835 | # actually completes using the frame's locals/globals |
|
|||
1836 | self.set_completer_frame() |
|
|||
1837 |
|
||||
1838 | # before activating the interactive mode, we need to make sure that |
|
|||
1839 | # all names in the builtin namespace needed by ipython point to |
|
|||
1840 | # ourselves, and not to other instances. |
|
|||
1841 | self.add_builtins() |
|
|||
1842 |
|
||||
1843 | self.interact(header) |
|
|||
1844 |
|
||||
1845 | # now, purge out the user namespace from anything we might have added |
|
|||
1846 | # from the caller's local namespace |
|
|||
1847 | delvar = self.user_ns.pop |
|
|||
1848 | for var in local_varnames: |
|
|||
1849 | delvar(var,None) |
|
|||
1850 | # and clean builtins we may have overridden |
|
|||
1851 | self.clean_builtins() |
|
|||
1852 |
|
||||
1853 | def interact_prompt(self): |
|
|||
1854 | """ Print the prompt (in read-eval-print loop) |
|
|||
1855 |
|
||||
1856 | Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not |
|
|||
1857 | used in standard IPython flow. |
|
|||
1858 | """ |
|
|||
1859 | if self.more: |
|
|||
1860 | try: |
|
|||
1861 | prompt = self.hooks.generate_prompt(True) |
|
|||
1862 | except: |
|
|||
1863 | self.showtraceback() |
|
|||
1864 | if self.autoindent: |
|
|||
1865 | self.rl_do_indent = True |
|
|||
1866 |
|
||||
1867 | else: |
|
|||
1868 | try: |
|
|||
1869 | prompt = self.hooks.generate_prompt(False) |
|
|||
1870 | except: |
|
|||
1871 | self.showtraceback() |
|
|||
1872 | self.write(prompt) |
|
|||
1873 |
|
||||
1874 | def interact_handle_input(self,line): |
|
|||
1875 | """ Handle the input line (in read-eval-print loop) |
|
|||
1876 |
|
||||
1877 | Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not |
|
|||
1878 | used in standard IPython flow. |
|
|||
1879 | """ |
|
|||
1880 | if line.lstrip() == line: |
|
|||
1881 | self.shadowhist.add(line.strip()) |
|
|||
1882 | lineout = self.prefilter(line,self.more) |
|
|||
1883 |
|
||||
1884 | if line.strip(): |
|
|||
1885 | if self.more: |
|
|||
1886 | self.input_hist_raw[-1] += '%s\n' % line |
|
|||
1887 | else: |
|
|||
1888 | self.input_hist_raw.append('%s\n' % line) |
|
|||
1889 |
|
||||
1890 |
|
||||
1891 | self.more = self.push(lineout) |
|
|||
1892 | if (self.SyntaxTB.last_syntax_error and |
|
|||
1893 | self.rc.autoedit_syntax): |
|
|||
1894 | self.edit_syntax_error() |
|
|||
1895 |
|
||||
1896 | def interact_with_readline(self): |
|
|||
1897 | """ Demo of using interact_handle_input, interact_prompt |
|
|||
1898 |
|
||||
1899 | This is the main read-eval-print loop. If you need to implement your own (e.g. for GUI), |
|
|||
1900 | it should work like this. |
|
|||
1901 | """ |
|
|||
1902 | self.readline_startup_hook(self.pre_readline) |
|
|||
1903 | while not self.exit_now: |
|
|||
1904 | self.interact_prompt() |
|
|||
1905 | if self.more: |
|
|||
1906 | self.rl_do_indent = True |
|
|||
1907 | else: |
|
|||
1908 | self.rl_do_indent = False |
|
|||
1909 | line = raw_input_original().decode(self.stdin_encoding) |
|
|||
1910 | self.interact_handle_input(line) |
|
|||
1911 |
|
||||
1912 |
|
||||
1913 | def interact(self, banner=None): |
|
|||
1914 | """Closely emulate the interactive Python console. |
|
|||
1915 |
|
||||
1916 | The optional banner argument specify the banner to print |
|
|||
1917 | before the first interaction; by default it prints a banner |
|
|||
1918 | similar to the one printed by the real Python interpreter, |
|
|||
1919 | followed by the current class name in parentheses (so as not |
|
|||
1920 | to confuse this with the real interpreter -- since it's so |
|
|||
1921 | close!). |
|
|||
1922 |
|
||||
1923 | """ |
|
|||
1924 |
|
||||
1925 | if self.exit_now: |
|
|||
1926 | # batch run -> do not interact |
|
|||
1927 | return |
|
|||
1928 | cprt = 'Type "copyright", "credits" or "license" for more information.' |
|
|||
1929 | if banner is None: |
|
|||
1930 | self.write("Python %s on %s\n%s\n(%s)\n" % |
|
|||
1931 | (sys.version, sys.platform, cprt, |
|
|||
1932 | self.__class__.__name__)) |
|
|||
1933 | else: |
|
|||
1934 | self.write(banner) |
|
|||
1935 |
|
||||
1936 | more = 0 |
|
|||
1937 |
|
||||
1938 | # Mark activity in the builtins |
|
|||
1939 | __builtin__.__dict__['__IPYTHON__active'] += 1 |
|
|||
1940 |
|
||||
1941 | if self.has_readline: |
|
|||
1942 | self.readline_startup_hook(self.pre_readline) |
|
|||
1943 | # exit_now is set by a call to %Exit or %Quit, through the |
|
|||
1944 | # ask_exit callback. |
|
|||
1945 |
|
||||
1946 | while not self.exit_now: |
|
|||
1947 | self.hooks.pre_prompt_hook() |
|
|||
1948 | if more: |
|
|||
1949 | try: |
|
|||
1950 | prompt = self.hooks.generate_prompt(True) |
|
|||
1951 | except: |
|
|||
1952 | self.showtraceback() |
|
|||
1953 | if self.autoindent: |
|
|||
1954 | self.rl_do_indent = True |
|
|||
1955 |
|
||||
1956 | else: |
|
|||
1957 | try: |
|
|||
1958 | prompt = self.hooks.generate_prompt(False) |
|
|||
1959 | except: |
|
|||
1960 | self.showtraceback() |
|
|||
1961 | try: |
|
|||
1962 | line = self.raw_input(prompt,more) |
|
|||
1963 | if self.exit_now: |
|
|||
1964 | # quick exit on sys.std[in|out] close |
|
|||
1965 | break |
|
|||
1966 | if self.autoindent: |
|
|||
1967 | self.rl_do_indent = False |
|
|||
1968 |
|
||||
1969 | except KeyboardInterrupt: |
|
|||
1970 | #double-guard against keyboardinterrupts during kbdint handling |
|
|||
1971 | try: |
|
|||
1972 | self.write('\nKeyboardInterrupt\n') |
|
|||
1973 | self.resetbuffer() |
|
|||
1974 | # keep cache in sync with the prompt counter: |
|
|||
1975 | self.outputcache.prompt_count -= 1 |
|
|||
1976 |
|
||||
1977 | if self.autoindent: |
|
|||
1978 | self.indent_current_nsp = 0 |
|
|||
1979 | more = 0 |
|
|||
1980 | except KeyboardInterrupt: |
|
|||
1981 | pass |
|
|||
1982 | except EOFError: |
|
|||
1983 | if self.autoindent: |
|
|||
1984 | self.rl_do_indent = False |
|
|||
1985 | self.readline_startup_hook(None) |
|
|||
1986 | self.write('\n') |
|
|||
1987 | self.exit() |
|
|||
1988 | except bdb.BdbQuit: |
|
|||
1989 | warn('The Python debugger has exited with a BdbQuit exception.\n' |
|
|||
1990 | 'Because of how pdb handles the stack, it is impossible\n' |
|
|||
1991 | 'for IPython to properly format this particular exception.\n' |
|
|||
1992 | 'IPython will resume normal operation.') |
|
|||
1993 | except: |
|
|||
1994 | # exceptions here are VERY RARE, but they can be triggered |
|
|||
1995 | # asynchronously by signal handlers, for example. |
|
|||
1996 | self.showtraceback() |
|
|||
1997 | else: |
|
|||
1998 | more = self.push(line) |
|
|||
1999 | if (self.SyntaxTB.last_syntax_error and |
|
|||
2000 | self.rc.autoedit_syntax): |
|
|||
2001 | self.edit_syntax_error() |
|
|||
2002 |
|
||||
2003 | # We are off again... |
|
|||
2004 | __builtin__.__dict__['__IPYTHON__active'] -= 1 |
|
|||
2005 |
|
||||
2006 | def excepthook(self, etype, value, tb): |
|
|||
2007 | """One more defense for GUI apps that call sys.excepthook. |
|
|||
2008 |
|
||||
2009 | GUI frameworks like wxPython trap exceptions and call |
|
|||
2010 | sys.excepthook themselves. I guess this is a feature that |
|
|||
2011 | enables them to keep running after exceptions that would |
|
|||
2012 | otherwise kill their mainloop. This is a bother for IPython |
|
|||
2013 | which excepts to catch all of the program exceptions with a try: |
|
|||
2014 | except: statement. |
|
|||
2015 |
|
||||
2016 | Normally, IPython sets sys.excepthook to a CrashHandler instance, so if |
|
|||
2017 | any app directly invokes sys.excepthook, it will look to the user like |
|
|||
2018 | IPython crashed. In order to work around this, we can disable the |
|
|||
2019 | CrashHandler and replace it with this excepthook instead, which prints a |
|
|||
2020 | regular traceback using our InteractiveTB. In this fashion, apps which |
|
|||
2021 | call sys.excepthook will generate a regular-looking exception from |
|
|||
2022 | IPython, and the CrashHandler will only be triggered by real IPython |
|
|||
2023 | crashes. |
|
|||
2024 |
|
||||
2025 | This hook should be used sparingly, only in places which are not likely |
|
|||
2026 | to be true IPython errors. |
|
|||
2027 | """ |
|
|||
2028 | self.showtraceback((etype,value,tb),tb_offset=0) |
|
|||
2029 |
|
||||
2030 | def expand_aliases(self,fn,rest): |
|
|||
2031 | """ Expand multiple levels of aliases: |
|
|||
2032 |
|
||||
2033 | if: |
|
|||
2034 |
|
||||
2035 | alias foo bar /tmp |
|
|||
2036 | alias baz foo |
|
|||
2037 |
|
||||
2038 | then: |
|
|||
2039 |
|
||||
2040 | baz huhhahhei -> bar /tmp huhhahhei |
|
|||
2041 |
|
||||
2042 | """ |
|
|||
2043 | line = fn + " " + rest |
|
|||
2044 |
|
||||
2045 | done = set() |
|
|||
2046 | while 1: |
|
|||
2047 | pre,fn,rest = prefilter.splitUserInput(line, |
|
|||
2048 | prefilter.shell_line_split) |
|
|||
2049 | if fn in self.alias_table: |
|
|||
2050 | if fn in done: |
|
|||
2051 | warn("Cyclic alias definition, repeated '%s'" % fn) |
|
|||
2052 | return "" |
|
|||
2053 | done.add(fn) |
|
|||
2054 |
|
||||
2055 | l2 = self.transform_alias(fn,rest) |
|
|||
2056 | # dir -> dir |
|
|||
2057 | # print "alias",line, "->",l2 #dbg |
|
|||
2058 | if l2 == line: |
|
|||
2059 | break |
|
|||
2060 | # ls -> ls -F should not recurse forever |
|
|||
2061 | if l2.split(None,1)[0] == line.split(None,1)[0]: |
|
|||
2062 | line = l2 |
|
|||
2063 | break |
|
|||
2064 |
|
||||
2065 | line=l2 |
|
|||
2066 |
|
||||
2067 |
|
||||
2068 | # print "al expand to",line #dbg |
|
|||
2069 | else: |
|
|||
2070 | break |
|
|||
2071 |
|
||||
2072 | return line |
|
|||
2073 |
|
||||
2074 | def transform_alias(self, alias,rest=''): |
|
|||
2075 | """ Transform alias to system command string. |
|
|||
2076 | """ |
|
|||
2077 | trg = self.alias_table[alias] |
|
|||
2078 |
|
||||
2079 | nargs,cmd = trg |
|
|||
2080 | # print trg #dbg |
|
|||
2081 | if ' ' in cmd and os.path.isfile(cmd): |
|
|||
2082 | cmd = '"%s"' % cmd |
|
|||
2083 |
|
||||
2084 | # Expand the %l special to be the user's input line |
|
|||
2085 | if cmd.find('%l') >= 0: |
|
|||
2086 | cmd = cmd.replace('%l',rest) |
|
|||
2087 | rest = '' |
|
|||
2088 | if nargs==0: |
|
|||
2089 | # Simple, argument-less aliases |
|
|||
2090 | cmd = '%s %s' % (cmd,rest) |
|
|||
2091 | else: |
|
|||
2092 | # Handle aliases with positional arguments |
|
|||
2093 | args = rest.split(None,nargs) |
|
|||
2094 | if len(args)< nargs: |
|
|||
2095 | error('Alias <%s> requires %s arguments, %s given.' % |
|
|||
2096 | (alias,nargs,len(args))) |
|
|||
2097 | return None |
|
|||
2098 | cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:])) |
|
|||
2099 | # Now call the macro, evaluating in the user's namespace |
|
|||
2100 | #print 'new command: <%r>' % cmd # dbg |
|
|||
2101 | return cmd |
|
|||
2102 |
|
||||
2103 | def call_alias(self,alias,rest=''): |
|
|||
2104 | """Call an alias given its name and the rest of the line. |
|
|||
2105 |
|
||||
2106 | This is only used to provide backwards compatibility for users of |
|
|||
2107 | ipalias(), use of which is not recommended for anymore.""" |
|
|||
2108 |
|
||||
2109 | # Now call the macro, evaluating in the user's namespace |
|
|||
2110 | cmd = self.transform_alias(alias, rest) |
|
|||
2111 | try: |
|
|||
2112 | self.system(cmd) |
|
|||
2113 | except: |
|
|||
2114 | self.showtraceback() |
|
|||
2115 |
|
||||
2116 | def indent_current_str(self): |
|
|||
2117 | """return the current level of indentation as a string""" |
|
|||
2118 | return self.indent_current_nsp * ' ' |
|
|||
2119 |
|
||||
2120 | def autoindent_update(self,line): |
|
|||
2121 | """Keep track of the indent level.""" |
|
|||
2122 |
|
||||
2123 | #debugx('line') |
|
|||
2124 | #debugx('self.indent_current_nsp') |
|
|||
2125 | if self.autoindent: |
|
|||
2126 | if line: |
|
|||
2127 | inisp = num_ini_spaces(line) |
|
|||
2128 | if inisp < self.indent_current_nsp: |
|
|||
2129 | self.indent_current_nsp = inisp |
|
|||
2130 |
|
||||
2131 | if line[-1] == ':': |
|
|||
2132 | self.indent_current_nsp += 4 |
|
|||
2133 | elif dedent_re.match(line): |
|
|||
2134 | self.indent_current_nsp -= 4 |
|
|||
2135 | else: |
|
|||
2136 | self.indent_current_nsp = 0 |
|
|||
2137 |
|
||||
2138 | def runlines(self,lines): |
|
|||
2139 | """Run a string of one or more lines of source. |
|
|||
2140 |
|
||||
2141 | This method is capable of running a string containing multiple source |
|
|||
2142 | lines, as if they had been entered at the IPython prompt. Since it |
|
|||
2143 | exposes IPython's processing machinery, the given strings can contain |
|
|||
2144 | magic calls (%magic), special shell access (!cmd), etc.""" |
|
|||
2145 |
|
||||
2146 | # We must start with a clean buffer, in case this is run from an |
|
|||
2147 | # interactive IPython session (via a magic, for example). |
|
|||
2148 | self.resetbuffer() |
|
|||
2149 | lines = lines.split('\n') |
|
|||
2150 | more = 0 |
|
|||
2151 |
|
||||
2152 | for line in lines: |
|
|||
2153 | # skip blank lines so we don't mess up the prompt counter, but do |
|
|||
2154 | # NOT skip even a blank line if we are in a code block (more is |
|
|||
2155 | # true) |
|
|||
2156 |
|
||||
2157 | if line or more: |
|
|||
2158 | # push to raw history, so hist line numbers stay in sync |
|
|||
2159 | self.input_hist_raw.append("# " + line + "\n") |
|
|||
2160 | more = self.push(self.prefilter(line,more)) |
|
|||
2161 | # IPython's runsource returns None if there was an error |
|
|||
2162 | # compiling the code. This allows us to stop processing right |
|
|||
2163 | # away, so the user gets the error message at the right place. |
|
|||
2164 | if more is None: |
|
|||
2165 | break |
|
|||
2166 | else: |
|
|||
2167 | self.input_hist_raw.append("\n") |
|
|||
2168 | # final newline in case the input didn't have it, so that the code |
|
|||
2169 | # actually does get executed |
|
|||
2170 | if more: |
|
|||
2171 | self.push('\n') |
|
|||
2172 |
|
||||
2173 | def runsource(self, source, filename='<input>', symbol='single'): |
|
|||
2174 | """Compile and run some source in the interpreter. |
|
|||
2175 |
|
||||
2176 | Arguments are as for compile_command(). |
|
|||
2177 |
|
||||
2178 | One several things can happen: |
|
|||
2179 |
|
||||
2180 | 1) The input is incorrect; compile_command() raised an |
|
|||
2181 | exception (SyntaxError or OverflowError). A syntax traceback |
|
|||
2182 | will be printed by calling the showsyntaxerror() method. |
|
|||
2183 |
|
||||
2184 | 2) The input is incomplete, and more input is required; |
|
|||
2185 | compile_command() returned None. Nothing happens. |
|
|||
2186 |
|
||||
2187 | 3) The input is complete; compile_command() returned a code |
|
|||
2188 | object. The code is executed by calling self.runcode() (which |
|
|||
2189 | also handles run-time exceptions, except for SystemExit). |
|
|||
2190 |
|
||||
2191 | The return value is: |
|
|||
2192 |
|
||||
2193 | - True in case 2 |
|
|||
2194 |
|
||||
2195 | - False in the other cases, unless an exception is raised, where |
|
|||
2196 | None is returned instead. This can be used by external callers to |
|
|||
2197 | know whether to continue feeding input or not. |
|
|||
2198 |
|
||||
2199 | The return value can be used to decide whether to use sys.ps1 or |
|
|||
2200 | sys.ps2 to prompt the next line.""" |
|
|||
2201 |
|
||||
2202 | # if the source code has leading blanks, add 'if 1:\n' to it |
|
|||
2203 | # this allows execution of indented pasted code. It is tempting |
|
|||
2204 | # to add '\n' at the end of source to run commands like ' a=1' |
|
|||
2205 | # directly, but this fails for more complicated scenarios |
|
|||
2206 | source=source.encode(self.stdin_encoding) |
|
|||
2207 | if source[:1] in [' ', '\t']: |
|
|||
2208 | source = 'if 1:\n%s' % source |
|
|||
2209 |
|
||||
2210 | try: |
|
|||
2211 | code = self.compile(source,filename,symbol) |
|
|||
2212 | except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError): |
|
|||
2213 | # Case 1 |
|
|||
2214 | self.showsyntaxerror(filename) |
|
|||
2215 | return None |
|
|||
2216 |
|
||||
2217 | if code is None: |
|
|||
2218 | # Case 2 |
|
|||
2219 | return True |
|
|||
2220 |
|
||||
2221 | # Case 3 |
|
|||
2222 | # We store the code object so that threaded shells and |
|
|||
2223 | # custom exception handlers can access all this info if needed. |
|
|||
2224 | # The source corresponding to this can be obtained from the |
|
|||
2225 | # buffer attribute as '\n'.join(self.buffer). |
|
|||
2226 | self.code_to_run = code |
|
|||
2227 | # now actually execute the code object |
|
|||
2228 | if self.runcode(code) == 0: |
|
|||
2229 | return False |
|
|||
2230 | else: |
|
|||
2231 | return None |
|
|||
2232 |
|
||||
2233 | def runcode(self,code_obj): |
|
|||
2234 | """Execute a code object. |
|
|||
2235 |
|
||||
2236 | When an exception occurs, self.showtraceback() is called to display a |
|
|||
2237 | traceback. |
|
|||
2238 |
|
||||
2239 | Return value: a flag indicating whether the code to be run completed |
|
|||
2240 | successfully: |
|
|||
2241 |
|
||||
2242 | - 0: successful execution. |
|
|||
2243 | - 1: an error occurred. |
|
|||
2244 | """ |
|
|||
2245 |
|
||||
2246 | # Set our own excepthook in case the user code tries to call it |
|
|||
2247 | # directly, so that the IPython crash handler doesn't get triggered |
|
|||
2248 | old_excepthook,sys.excepthook = sys.excepthook, self.excepthook |
|
|||
2249 |
|
||||
2250 | # we save the original sys.excepthook in the instance, in case config |
|
|||
2251 | # code (such as magics) needs access to it. |
|
|||
2252 | self.sys_excepthook = old_excepthook |
|
|||
2253 | outflag = 1 # happens in more places, so it's easier as default |
|
|||
2254 | try: |
|
|||
2255 | try: |
|
|||
2256 | self.hooks.pre_runcode_hook() |
|
|||
2257 | exec code_obj in self.user_global_ns, self.user_ns |
|
|||
2258 | finally: |
|
|||
2259 | # Reset our crash handler in place |
|
|||
2260 | sys.excepthook = old_excepthook |
|
|||
2261 | except SystemExit: |
|
|||
2262 | self.resetbuffer() |
|
|||
2263 | self.showtraceback() |
|
|||
2264 | warn("Type %exit or %quit to exit IPython " |
|
|||
2265 | "(%Exit or %Quit do so unconditionally).",level=1) |
|
|||
2266 | except self.custom_exceptions: |
|
|||
2267 | etype,value,tb = sys.exc_info() |
|
|||
2268 | self.CustomTB(etype,value,tb) |
|
|||
2269 | except: |
|
|||
2270 | self.showtraceback() |
|
|||
2271 | else: |
|
|||
2272 | outflag = 0 |
|
|||
2273 | if softspace(sys.stdout, 0): |
|
|||
2274 |
|
||||
2275 | # Flush out code object which has been run (and source) |
|
|||
2276 | self.code_to_run = None |
|
|||
2277 | return outflag |
|
|||
2278 |
|
||||
2279 | def push(self, line): |
|
|||
2280 | """Push a line to the interpreter. |
|
|||
2281 |
|
||||
2282 | The line should not have a trailing newline; it may have |
|
|||
2283 | internal newlines. The line is appended to a buffer and the |
|
|||
2284 | interpreter's runsource() method is called with the |
|
|||
2285 | concatenated contents of the buffer as source. If this |
|
|||
2286 | indicates that the command was executed or invalid, the buffer |
|
|||
2287 | is reset; otherwise, the command is incomplete, and the buffer |
|
|||
2288 | is left as it was after the line was appended. The return |
|
|||
2289 | value is 1 if more input is required, 0 if the line was dealt |
|
|||
2290 | with in some way (this is the same as runsource()). |
|
|||
2291 | """ |
|
|||
2292 |
|
||||
2293 | # autoindent management should be done here, and not in the |
|
|||
2294 | # interactive loop, since that one is only seen by keyboard input. We |
|
|||
2295 | # need this done correctly even for code run via runlines (which uses |
|
|||
2296 | # push). |
|
|||
2297 |
|
||||
2298 | #print 'push line: <%s>' % line # dbg |
|
|||
2299 | for subline in line.splitlines(): |
|
|||
2300 | self.autoindent_update(subline) |
|
|||
2301 | self.buffer.append(line) |
|
|||
2302 | more = self.runsource('\n'.join(self.buffer), self.filename) |
|
|||
2303 | if not more: |
|
|||
2304 | self.resetbuffer() |
|
|||
2305 | return more |
|
|||
2306 |
|
||||
2307 | def split_user_input(self, line): |
|
|||
2308 | # This is really a hold-over to support ipapi and some extensions |
|
|||
2309 | return prefilter.splitUserInput(line) |
|
|||
2310 |
|
||||
2311 | def resetbuffer(self): |
|
|||
2312 | """Reset the input buffer.""" |
|
|||
2313 | self.buffer[:] = [] |
|
|||
2314 |
|
||||
2315 | def raw_input(self,prompt='',continue_prompt=False): |
|
|||
2316 | """Write a prompt and read a line. |
|
|||
2317 |
|
||||
2318 | The returned line does not include the trailing newline. |
|
|||
2319 | When the user enters the EOF key sequence, EOFError is raised. |
|
|||
2320 |
|
||||
2321 | Optional inputs: |
|
|||
2322 |
|
||||
2323 | - prompt(''): a string to be printed to prompt the user. |
|
|||
2324 |
|
||||
2325 | - continue_prompt(False): whether this line is the first one or a |
|
|||
2326 | continuation in a sequence of inputs. |
|
|||
2327 | """ |
|
|||
2328 |
|
||||
2329 | # Code run by the user may have modified the readline completer state. |
|
|||
2330 | # We must ensure that our completer is back in place. |
|
|||
2331 | if self.has_readline: |
|
|||
2332 | self.set_completer() |
|
|||
2333 |
|
||||
2334 | try: |
|
|||
2335 | line = raw_input_original(prompt).decode(self.stdin_encoding) |
|
|||
2336 | except ValueError: |
|
|||
2337 | warn("\n********\nYou or a %run:ed script called sys.stdin.close()" |
|
|||
2338 | " or sys.stdout.close()!\nExiting IPython!") |
|
|||
2339 | self.ask_exit() |
|
|||
2340 | return "" |
|
|||
2341 |
|
||||
2342 | # Try to be reasonably smart about not re-indenting pasted input more |
|
|||
2343 | # than necessary. We do this by trimming out the auto-indent initial |
|
|||
2344 | # spaces, if the user's actual input started itself with whitespace. |
|
|||
2345 | #debugx('self.buffer[-1]') |
|
|||
2346 |
|
||||
2347 | if self.autoindent: |
|
|||
2348 | if num_ini_spaces(line) > self.indent_current_nsp: |
|
|||
2349 | line = line[self.indent_current_nsp:] |
|
|||
2350 | self.indent_current_nsp = 0 |
|
|||
2351 |
|
||||
2352 | # store the unfiltered input before the user has any chance to modify |
|
|||
2353 | # it. |
|
|||
2354 | if line.strip(): |
|
|||
2355 | if continue_prompt: |
|
|||
2356 | self.input_hist_raw[-1] += '%s\n' % line |
|
|||
2357 | if self.has_readline: # and some config option is set? |
|
|||
2358 | try: |
|
|||
2359 | histlen = self.readline.get_current_history_length() |
|
|||
2360 | if histlen > 1: |
|
|||
2361 | newhist = self.input_hist_raw[-1].rstrip() |
|
|||
2362 | self.readline.remove_history_item(histlen-1) |
|
|||
2363 | self.readline.replace_history_item(histlen-2, |
|
|||
2364 | newhist.encode(self.stdin_encoding)) |
|
|||
2365 | except AttributeError: |
|
|||
2366 | pass # re{move,place}_history_item are new in 2.4. |
|
|||
2367 | else: |
|
|||
2368 | self.input_hist_raw.append('%s\n' % line) |
|
|||
2369 | # only entries starting at first column go to shadow history |
|
|||
2370 | if line.lstrip() == line: |
|
|||
2371 | self.shadowhist.add(line.strip()) |
|
|||
2372 | elif not continue_prompt: |
|
|||
2373 | self.input_hist_raw.append('\n') |
|
|||
2374 | try: |
|
|||
2375 | lineout = self.prefilter(line,continue_prompt) |
|
|||
2376 | except: |
|
|||
2377 | # blanket except, in case a user-defined prefilter crashes, so it |
|
|||
2378 | # can't take all of ipython with it. |
|
|||
2379 | self.showtraceback() |
|
|||
2380 | return '' |
|
|||
2381 | else: |
|
|||
2382 | return lineout |
|
|||
2383 |
|
||||
2384 | def _prefilter(self, line, continue_prompt): |
|
|||
2385 | """Calls different preprocessors, depending on the form of line.""" |
|
|||
2386 |
|
||||
2387 | # All handlers *must* return a value, even if it's blank (''). |
|
|||
2388 |
|
||||
2389 | # Lines are NOT logged here. Handlers should process the line as |
|
|||
2390 | # needed, update the cache AND log it (so that the input cache array |
|
|||
2391 | # stays synced). |
|
|||
2392 |
|
||||
2393 | #..................................................................... |
|
|||
2394 | # Code begins |
|
|||
2395 |
|
||||
2396 | #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg |
|
|||
2397 |
|
||||
2398 | # save the line away in case we crash, so the post-mortem handler can |
|
|||
2399 | # record it |
|
|||
2400 | self._last_input_line = line |
|
|||
2401 |
|
||||
2402 | #print '***line: <%s>' % line # dbg |
|
|||
2403 |
|
||||
2404 | if not line: |
|
|||
2405 | # Return immediately on purely empty lines, so that if the user |
|
|||
2406 | # previously typed some whitespace that started a continuation |
|
|||
2407 | # prompt, he can break out of that loop with just an empty line. |
|
|||
2408 | # This is how the default python prompt works. |
|
|||
2409 |
|
||||
2410 | # Only return if the accumulated input buffer was just whitespace! |
|
|||
2411 | if ''.join(self.buffer).isspace(): |
|
|||
2412 | self.buffer[:] = [] |
|
|||
2413 | return '' |
|
|||
2414 |
|
||||
2415 | line_info = prefilter.LineInfo(line, continue_prompt) |
|
|||
2416 |
|
||||
2417 | # the input history needs to track even empty lines |
|
|||
2418 | stripped = line.strip() |
|
|||
2419 |
|
||||
2420 | if not stripped: |
|
|||
2421 | if not continue_prompt: |
|
|||
2422 | self.outputcache.prompt_count -= 1 |
|
|||
2423 | return self.handle_normal(line_info) |
|
|||
2424 |
|
||||
2425 | # print '***cont',continue_prompt # dbg |
|
|||
2426 | # special handlers are only allowed for single line statements |
|
|||
2427 | if continue_prompt and not self.rc.multi_line_specials: |
|
|||
2428 | return self.handle_normal(line_info) |
|
|||
2429 |
|
||||
2430 |
|
||||
2431 | # See whether any pre-existing handler can take care of it |
|
|||
2432 | rewritten = self.hooks.input_prefilter(stripped) |
|
|||
2433 | if rewritten != stripped: # ok, some prefilter did something |
|
|||
2434 | rewritten = line_info.pre + rewritten # add indentation |
|
|||
2435 | return self.handle_normal(prefilter.LineInfo(rewritten, |
|
|||
2436 | continue_prompt)) |
|
|||
2437 |
|
||||
2438 | #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg |
|
|||
2439 |
|
||||
2440 | return prefilter.prefilter(line_info, self) |
|
|||
2441 |
|
||||
2442 |
|
||||
2443 | def _prefilter_dumb(self, line, continue_prompt): |
|
|||
2444 | """simple prefilter function, for debugging""" |
|
|||
2445 | return self.handle_normal(line,continue_prompt) |
|
|||
2446 |
|
||||
2447 |
|
||||
2448 | def multiline_prefilter(self, line, continue_prompt): |
|
|||
2449 | """ Run _prefilter for each line of input |
|
|||
2450 |
|
||||
2451 | Covers cases where there are multiple lines in the user entry, |
|
|||
2452 | which is the case when the user goes back to a multiline history |
|
|||
2453 | entry and presses enter. |
|
|||
2454 |
|
||||
2455 | """ |
|
|||
2456 | out = [] |
|
|||
2457 | for l in line.rstrip('\n').split('\n'): |
|
|||
2458 | out.append(self._prefilter(l, continue_prompt)) |
|
|||
2459 | return '\n'.join(out) |
|
|||
2460 |
|
||||
2461 | # Set the default prefilter() function (this can be user-overridden) |
|
|||
2462 | prefilter = multiline_prefilter |
|
|||
2463 |
|
||||
2464 | def handle_normal(self,line_info): |
|
|||
2465 | """Handle normal input lines. Use as a template for handlers.""" |
|
|||
2466 |
|
||||
2467 | # With autoindent on, we need some way to exit the input loop, and I |
|
|||
2468 | # don't want to force the user to have to backspace all the way to |
|
|||
2469 | # clear the line. The rule will be in this case, that either two |
|
|||
2470 | # lines of pure whitespace in a row, or a line of pure whitespace but |
|
|||
2471 | # of a size different to the indent level, will exit the input loop. |
|
|||
2472 | line = line_info.line |
|
|||
2473 | continue_prompt = line_info.continue_prompt |
|
|||
2474 |
|
||||
2475 | if (continue_prompt and self.autoindent and line.isspace() and |
|
|||
2476 | (0 < abs(len(line) - self.indent_current_nsp) <= 2 or |
|
|||
2477 | (self.buffer[-1]).isspace() )): |
|
|||
2478 | line = '' |
|
|||
2479 |
|
||||
2480 | self.log(line,line,continue_prompt) |
|
|||
2481 | return line |
|
|||
2482 |
|
||||
2483 | def handle_alias(self,line_info): |
|
|||
2484 | """Handle alias input lines. """ |
|
|||
2485 | tgt = self.alias_table[line_info.iFun] |
|
|||
2486 | # print "=>",tgt #dbg |
|
|||
2487 | if callable(tgt): |
|
|||
2488 | if '$' in line_info.line: |
|
|||
2489 | call_meth = '(_ip, _ip.itpl(%s))' |
|
|||
2490 | else: |
|
|||
2491 | call_meth = '(_ip,%s)' |
|
|||
2492 | line_out = ("%s_sh.%s" + call_meth) % (line_info.preWhitespace, |
|
|||
2493 | line_info.iFun, |
|
|||
2494 | make_quoted_expr(line_info.line)) |
|
|||
2495 | else: |
|
|||
2496 | transformed = self.expand_aliases(line_info.iFun,line_info.theRest) |
|
|||
2497 |
|
||||
2498 | # pre is needed, because it carries the leading whitespace. Otherwise |
|
|||
2499 | # aliases won't work in indented sections. |
|
|||
2500 | line_out = '%s_ip.system(%s)' % (line_info.preWhitespace, |
|
|||
2501 | make_quoted_expr( transformed )) |
|
|||
2502 |
|
||||
2503 | self.log(line_info.line,line_out,line_info.continue_prompt) |
|
|||
2504 | #print 'line out:',line_out # dbg |
|
|||
2505 | return line_out |
|
|||
2506 |
|
||||
2507 | def handle_shell_escape(self, line_info): |
|
|||
2508 | """Execute the line in a shell, empty return value""" |
|
|||
2509 | #print 'line in :', `line` # dbg |
|
|||
2510 | line = line_info.line |
|
|||
2511 | if line.lstrip().startswith('!!'): |
|
|||
2512 | # rewrite LineInfo's line, iFun and theRest to properly hold the |
|
|||
2513 | # call to %sx and the actual command to be executed, so |
|
|||
2514 | # handle_magic can work correctly. Note that this works even if |
|
|||
2515 | # the line is indented, so it handles multi_line_specials |
|
|||
2516 | # properly. |
|
|||
2517 | new_rest = line.lstrip()[2:] |
|
|||
2518 | line_info.line = '%ssx %s' % (self.ESC_MAGIC,new_rest) |
|
|||
2519 | line_info.iFun = 'sx' |
|
|||
2520 | line_info.theRest = new_rest |
|
|||
2521 | return self.handle_magic(line_info) |
|
|||
2522 | else: |
|
|||
2523 | cmd = line.lstrip().lstrip('!') |
|
|||
2524 | line_out = '%s_ip.system(%s)' % (line_info.preWhitespace, |
|
|||
2525 | make_quoted_expr(cmd)) |
|
|||
2526 | # update cache/log and return |
|
|||
2527 | self.log(line,line_out,line_info.continue_prompt) |
|
|||
2528 | return line_out |
|
|||
2529 |
|
||||
2530 | def handle_magic(self, line_info): |
|
|||
2531 | """Execute magic functions.""" |
|
|||
2532 | iFun = line_info.iFun |
|
|||
2533 | theRest = line_info.theRest |
|
|||
2534 | cmd = '%s_ip.magic(%s)' % (line_info.preWhitespace, |
|
|||
2535 | make_quoted_expr(iFun + " " + theRest)) |
|
|||
2536 | self.log(line_info.line,cmd,line_info.continue_prompt) |
|
|||
2537 | #print 'in handle_magic, cmd=<%s>' % cmd # dbg |
|
|||
2538 | return cmd |
|
|||
2539 |
|
||||
2540 | def handle_auto(self, line_info): |
|
|||
2541 | """Hande lines which can be auto-executed, quoting if requested.""" |
|
|||
2542 |
|
||||
2543 | line = line_info.line |
|
|||
2544 | iFun = line_info.iFun |
|
|||
2545 | theRest = line_info.theRest |
|
|||
2546 | pre = line_info.pre |
|
|||
2547 | continue_prompt = line_info.continue_prompt |
|
|||
2548 | obj = line_info.ofind(self)['obj'] |
|
|||
2549 |
|
||||
2550 | #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg |
|
|||
2551 |
|
||||
2552 | # This should only be active for single-line input! |
|
|||
2553 | if continue_prompt: |
|
|||
2554 | self.log(line,line,continue_prompt) |
|
|||
2555 | return line |
|
|||
2556 |
|
||||
2557 | force_auto = isinstance(obj, IPython.ipapi.IPyAutocall) |
|
|||
2558 | auto_rewrite = True |
|
|||
2559 |
|
||||
2560 | if pre == self.ESC_QUOTE: |
|
|||
2561 | # Auto-quote splitting on whitespace |
|
|||
2562 | newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) ) |
|
|||
2563 | elif pre == self.ESC_QUOTE2: |
|
|||
2564 | # Auto-quote whole string |
|
|||
2565 | newcmd = '%s("%s")' % (iFun,theRest) |
|
|||
2566 | elif pre == self.ESC_PAREN: |
|
|||
2567 | newcmd = '%s(%s)' % (iFun,",".join(theRest.split())) |
|
|||
2568 | else: |
|
|||
2569 | # Auto-paren. |
|
|||
2570 | # We only apply it to argument-less calls if the autocall |
|
|||
2571 | # parameter is set to 2. We only need to check that autocall is < |
|
|||
2572 | # 2, since this function isn't called unless it's at least 1. |
|
|||
2573 | if not theRest and (self.rc.autocall < 2) and not force_auto: |
|
|||
2574 | newcmd = '%s %s' % (iFun,theRest) |
|
|||
2575 | auto_rewrite = False |
|
|||
2576 | else: |
|
|||
2577 | if not force_auto and theRest.startswith('['): |
|
|||
2578 | if hasattr(obj,'__getitem__'): |
|
|||
2579 | # Don't autocall in this case: item access for an object |
|
|||
2580 | # which is BOTH callable and implements __getitem__. |
|
|||
2581 | newcmd = '%s %s' % (iFun,theRest) |
|
|||
2582 | auto_rewrite = False |
|
|||
2583 | else: |
|
|||
2584 | # if the object doesn't support [] access, go ahead and |
|
|||
2585 | # autocall |
|
|||
2586 | newcmd = '%s(%s)' % (iFun.rstrip(),theRest) |
|
|||
2587 | elif theRest.endswith(';'): |
|
|||
2588 | newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1]) |
|
|||
2589 | else: |
|
|||
2590 | newcmd = '%s(%s)' % (iFun.rstrip(), theRest) |
|
|||
2591 |
|
||||
2592 | if auto_rewrite: |
|
|||
2593 | rw = self.outputcache.prompt1.auto_rewrite() + newcmd |
|
|||
2594 |
|
||||
2595 | try: |
|
|||
2596 | # plain ascii works better w/ pyreadline, on some machines, so |
|
|||
2597 | # we use it and only print uncolored rewrite if we have unicode |
|
|||
2598 | rw = str(rw) |
|
|||
2599 | print >>Term.cout, rw |
|
|||
2600 | except UnicodeEncodeError: |
|
|||
2601 | print "-------------->" + newcmd |
|
|||
2602 |
|
||||
2603 | # log what is now valid Python, not the actual user input (without the |
|
|||
2604 | # final newline) |
|
|||
2605 | self.log(line,newcmd,continue_prompt) |
|
|||
2606 | return newcmd |
|
|||
2607 |
|
||||
2608 | def handle_help(self, line_info): |
|
|||
2609 | """Try to get some help for the object. |
|
|||
2610 |
|
||||
2611 | obj? or ?obj -> basic information. |
|
|||
2612 | obj?? or ??obj -> more details. |
|
|||
2613 | """ |
|
|||
2614 |
|
||||
2615 | line = line_info.line |
|
|||
2616 | # We need to make sure that we don't process lines which would be |
|
|||
2617 | # otherwise valid python, such as "x=1 # what?" |
|
|||
2618 | try: |
|
|||
2619 | codeop.compile_command(line) |
|
|||
2620 | except SyntaxError: |
|
|||
2621 | # We should only handle as help stuff which is NOT valid syntax |
|
|||
2622 | if line[0]==self.ESC_HELP: |
|
|||
2623 | line = line[1:] |
|
|||
2624 | elif line[-1]==self.ESC_HELP: |
|
|||
2625 | line = line[:-1] |
|
|||
2626 | self.log(line,'#?'+line,line_info.continue_prompt) |
|
|||
2627 | if line: |
|
|||
2628 | #print 'line:<%r>' % line # dbg |
|
|||
2629 | self.magic_pinfo(line) |
|
|||
2630 | else: |
|
|||
2631 | page(self.usage,screen_lines=self.rc.screen_length) |
|
|||
2632 | return '' # Empty string is needed here! |
|
|||
2633 | except: |
|
|||
2634 | # Pass any other exceptions through to the normal handler |
|
|||
2635 | return self.handle_normal(line_info) |
|
|||
2636 | else: |
|
|||
2637 | # If the code compiles ok, we should handle it normally |
|
|||
2638 | return self.handle_normal(line_info) |
|
|||
2639 |
|
||||
2640 | def getapi(self): |
|
|||
2641 | """ Get an IPApi object for this shell instance |
|
|||
2642 |
|
||||
2643 | Getting an IPApi object is always preferable to accessing the shell |
|
|||
2644 | directly, but this holds true especially for extensions. |
|
|||
2645 |
|
||||
2646 | It should always be possible to implement an extension with IPApi |
|
|||
2647 | alone. If not, contact maintainer to request an addition. |
|
|||
2648 |
|
||||
2649 | """ |
|
|||
2650 | return self.api |
|
|||
2651 |
|
||||
2652 | def handle_emacs(self, line_info): |
|
|||
2653 | """Handle input lines marked by python-mode.""" |
|
|||
2654 |
|
||||
2655 | # Currently, nothing is done. Later more functionality can be added |
|
|||
2656 | # here if needed. |
|
|||
2657 |
|
||||
2658 | # The input cache shouldn't be updated |
|
|||
2659 | return line_info.line |
|
|||
2660 |
|
||||
2661 |
|
||||
2662 | def mktempfile(self,data=None): |
|
|||
2663 | """Make a new tempfile and return its filename. |
|
|||
2664 |
|
||||
2665 | This makes a call to tempfile.mktemp, but it registers the created |
|
|||
2666 | filename internally so ipython cleans it up at exit time. |
|
|||
2667 |
|
||||
2668 | Optional inputs: |
|
|||
2669 |
|
||||
2670 | - data(None): if data is given, it gets written out to the temp file |
|
|||
2671 | immediately, and the file is closed again.""" |
|
|||
2672 |
|
||||
2673 | filename = tempfile.mktemp('.py','ipython_edit_') |
|
|||
2674 | self.tempfiles.append(filename) |
|
|||
2675 |
|
||||
2676 | if data: |
|
|||
2677 | tmp_file = open(filename,'w') |
|
|||
2678 | tmp_file.write(data) |
|
|||
2679 | tmp_file.close() |
|
|||
2680 | return filename |
|
|||
2681 |
|
||||
2682 | def write(self,data): |
|
|||
2683 | """Write a string to the default output""" |
|
|||
2684 | Term.cout.write(data) |
|
|||
2685 |
|
||||
2686 | def write_err(self,data): |
|
|||
2687 | """Write a string to the default error output""" |
|
|||
2688 | Term.cerr.write(data) |
|
|||
2689 |
|
||||
2690 | def ask_exit(self): |
|
|||
2691 | """ Call for exiting. Can be overiden and used as a callback. """ |
|
|||
2692 | self.exit_now = True |
|
|||
2693 |
|
||||
2694 | def exit(self): |
|
|||
2695 | """Handle interactive exit. |
|
|||
2696 |
|
||||
2697 | This method calls the ask_exit callback.""" |
|
|||
2698 |
|
||||
2699 | if self.rc.confirm_exit: |
|
|||
2700 | if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'): |
|
|||
2701 | self.ask_exit() |
|
|||
2702 | else: |
|
|||
2703 | self.ask_exit() |
|
|||
2704 |
|
||||
2705 | def safe_execfile(self,fname,*where,**kw): |
|
|||
2706 | """A safe version of the builtin execfile(). |
|
|||
2707 |
|
||||
2708 | This version will never throw an exception, and knows how to handle |
|
|||
2709 | ipython logs as well. |
|
|||
2710 |
|
||||
2711 | :Parameters: |
|
|||
2712 | fname : string |
|
|||
2713 | Name of the file to be executed. |
|
|||
2714 |
|
||||
2715 | where : tuple |
|
|||
2716 | One or two namespaces, passed to execfile() as (globals,locals). |
|
|||
2717 | If only one is given, it is passed as both. |
|
|||
2718 |
|
||||
2719 | :Keywords: |
|
|||
2720 | islog : boolean (False) |
|
|||
2721 |
|
||||
2722 | quiet : boolean (True) |
|
|||
2723 |
|
||||
2724 | exit_ignore : boolean (False) |
|
|||
2725 | """ |
|
|||
2726 |
|
||||
2727 | def syspath_cleanup(): |
|
|||
2728 | """Internal cleanup routine for sys.path.""" |
|
|||
2729 | if add_dname: |
|
|||
2730 | try: |
|
|||
2731 | sys.path.remove(dname) |
|
|||
2732 | except ValueError: |
|
|||
2733 | # For some reason the user has already removed it, ignore. |
|
|||
2734 | pass |
|
|||
2735 |
|
||||
2736 | fname = os.path.expanduser(fname) |
|
|||
2737 |
|
||||
2738 | # Find things also in current directory. This is needed to mimic the |
|
|||
2739 | # behavior of running a script from the system command line, where |
|
|||
2740 | # Python inserts the script's directory into sys.path |
|
|||
2741 | dname = os.path.dirname(os.path.abspath(fname)) |
|
|||
2742 | add_dname = False |
|
|||
2743 | if dname not in sys.path: |
|
|||
2744 | sys.path.insert(0,dname) |
|
|||
2745 | add_dname = True |
|
|||
2746 |
|
||||
2747 | try: |
|
|||
2748 | xfile = open(fname) |
|
|||
2749 | except: |
|
|||
2750 | print >> Term.cerr, \ |
|
|||
2751 | 'Could not open file <%s> for safe execution.' % fname |
|
|||
2752 | syspath_cleanup() |
|
|||
2753 | return None |
|
|||
2754 |
|
||||
2755 | kw.setdefault('islog',0) |
|
|||
2756 | kw.setdefault('quiet',1) |
|
|||
2757 | kw.setdefault('exit_ignore',0) |
|
|||
2758 |
|
||||
2759 | first = xfile.readline() |
|
|||
2760 | loghead = str(self.loghead_tpl).split('\n',1)[0].strip() |
|
|||
2761 | xfile.close() |
|
|||
2762 | # line by line execution |
|
|||
2763 | if first.startswith(loghead) or kw['islog']: |
|
|||
2764 | print 'Loading log file <%s> one line at a time...' % fname |
|
|||
2765 | if kw['quiet']: |
|
|||
2766 | stdout_save = sys.stdout |
|
|||
2767 | sys.stdout = StringIO.StringIO() |
|
|||
2768 | try: |
|
|||
2769 | globs,locs = where[0:2] |
|
|||
2770 | except: |
|
|||
2771 | try: |
|
|||
2772 | globs = locs = where[0] |
|
|||
2773 | except: |
|
|||
2774 | globs = locs = globals() |
|
|||
2775 | badblocks = [] |
|
|||
2776 |
|
18 | |||
2777 | # we also need to identify indented blocks of code when replaying |
|
19 | from warnings import warn | |
2778 | # logs and put them together before passing them to an exec |
|
|||
2779 | # statement. This takes a bit of regexp and look-ahead work in the |
|
|||
2780 | # file. It's easiest if we swallow the whole thing in memory |
|
|||
2781 | # first, and manually walk through the lines list moving the |
|
|||
2782 | # counter ourselves. |
|
|||
2783 | indent_re = re.compile('\s+\S') |
|
|||
2784 | xfile = open(fname) |
|
|||
2785 | filelines = xfile.readlines() |
|
|||
2786 | xfile.close() |
|
|||
2787 | nlines = len(filelines) |
|
|||
2788 | lnum = 0 |
|
|||
2789 | while lnum < nlines: |
|
|||
2790 | line = filelines[lnum] |
|
|||
2791 | lnum += 1 |
|
|||
2792 | # don't re-insert logger status info into cache |
|
|||
2793 | if line.startswith('#log#'): |
|
|||
2794 | continue |
|
|||
2795 | else: |
|
|||
2796 | # build a block of code (maybe a single line) for execution |
|
|||
2797 | block = line |
|
|||
2798 | try: |
|
|||
2799 | next = filelines[lnum] # lnum has already incremented |
|
|||
2800 | except: |
|
|||
2801 | next = None |
|
|||
2802 | while next and indent_re.match(next): |
|
|||
2803 | block += next |
|
|||
2804 | lnum += 1 |
|
|||
2805 | try: |
|
|||
2806 | next = filelines[lnum] |
|
|||
2807 | except: |
|
|||
2808 | next = None |
|
|||
2809 | # now execute the block of one or more lines |
|
|||
2810 | try: |
|
|||
2811 | exec block in globs,locs |
|
|||
2812 | except SystemExit: |
|
|||
2813 | pass |
|
|||
2814 | except: |
|
|||
2815 | badblocks.append(block.rstrip()) |
|
|||
2816 | if kw['quiet']: # restore stdout |
|
|||
2817 | sys.stdout.close() |
|
|||
2818 | sys.stdout = stdout_save |
|
|||
2819 | print 'Finished replaying log file <%s>' % fname |
|
|||
2820 | if badblocks: |
|
|||
2821 | print >> sys.stderr, ('\nThe following lines/blocks in file ' |
|
|||
2822 | '<%s> reported errors:' % fname) |
|
|||
2823 |
|
||||
2824 | for badline in badblocks: |
|
|||
2825 | print >> sys.stderr, badline |
|
|||
2826 | else: # regular file execution |
|
|||
2827 | try: |
|
|||
2828 | if sys.platform == 'win32' and sys.version_info < (2,5,1): |
|
|||
2829 | # Work around a bug in Python for Windows. The bug was |
|
|||
2830 | # fixed in in Python 2.5 r54159 and 54158, but that's still |
|
|||
2831 | # SVN Python as of March/07. For details, see: |
|
|||
2832 | # http://projects.scipy.org/ipython/ipython/ticket/123 |
|
|||
2833 | try: |
|
|||
2834 | globs,locs = where[0:2] |
|
|||
2835 | except: |
|
|||
2836 | try: |
|
|||
2837 | globs = locs = where[0] |
|
|||
2838 | except: |
|
|||
2839 | globs = locs = globals() |
|
|||
2840 | exec file(fname) in globs,locs |
|
|||
2841 | else: |
|
|||
2842 | execfile(fname,*where) |
|
|||
2843 | except SyntaxError: |
|
|||
2844 | self.showsyntaxerror() |
|
|||
2845 | warn('Failure executing file: <%s>' % fname) |
|
|||
2846 | except SystemExit,status: |
|
|||
2847 | # Code that correctly sets the exit status flag to success (0) |
|
|||
2848 | # shouldn't be bothered with a traceback. Note that a plain |
|
|||
2849 | # sys.exit() does NOT set the message to 0 (it's empty) so that |
|
|||
2850 | # will still get a traceback. Note that the structure of the |
|
|||
2851 | # SystemExit exception changed between Python 2.4 and 2.5, so |
|
|||
2852 | # the checks must be done in a version-dependent way. |
|
|||
2853 | show = False |
|
|||
2854 |
|
20 | |||
2855 | if sys.version_info[:2] > (2,5): |
|
21 | msg = """ | |
2856 | if status.message!=0 and not kw['exit_ignore']: |
|
22 | This module (IPython.iplib) has been moved to a new location | |
2857 | show = True |
|
23 | (IPython.core.iplib) and is being refactored. Please update your code | |
2858 | else: |
|
24 | to use the new IPython.core.iplib module""" | |
2859 | if status.code and not kw['exit_ignore']: |
|
|||
2860 | show = True |
|
|||
2861 | if show: |
|
|||
2862 | self.showtraceback() |
|
|||
2863 | warn('Failure executing file: <%s>' % fname) |
|
|||
2864 | except: |
|
|||
2865 | self.showtraceback() |
|
|||
2866 | warn('Failure executing file: <%s>' % fname) |
|
|||
2867 |
|
25 | |||
2868 | syspath_cleanup() |
|
26 | warn(msg, category=DeprecationWarning, stacklevel=1) | |
2869 |
|
27 | |||
2870 | #************************* end of file <iplib.py> ***************************** |
|
28 | from IPython.core.iplib import * |
@@ -30,7 +30,7 b' __docformat__ = "restructuredtext en"' | |||||
30 |
|
30 | |||
31 | import sys |
|
31 | import sys | |
32 |
|
32 | |||
33 |
# from IPython. |
|
33 | # from IPython.utils import growl | |
34 | # growl.start("IPython1 Client") |
|
34 | # growl.start("IPython1 Client") | |
35 |
|
35 | |||
36 |
|
36 |
@@ -20,7 +20,7 b' from os.path import join as pjoin' | |||||
20 |
|
20 | |||
21 | from IPython.external.configobj import ConfigObj |
|
21 | from IPython.external.configobj import ConfigObj | |
22 | from IPython.config.api import ConfigObjManager |
|
22 | from IPython.config.api import ConfigObjManager | |
23 | from IPython.genutils import get_ipython_dir, get_security_dir |
|
23 | from IPython.utils.genutils import get_ipython_dir, get_security_dir | |
24 |
|
24 | |||
25 | default_kernel_config = ConfigObj() |
|
25 | default_kernel_config = ConfigObj() | |
26 |
|
26 |
@@ -26,8 +26,8 b' import sys' | |||||
26 |
|
26 | |||
27 | from twisted.internet.error import ConnectionRefusedError |
|
27 | from twisted.internet.error import ConnectionRefusedError | |
28 |
|
28 | |||
29 |
from IPython. |
|
29 | from IPython.core.ultratb import _fixed_getinnerframes, findsource | |
30 | from IPython import ipapi |
|
30 | from IPython.core import ipapi | |
31 |
|
31 | |||
32 | from IPython.kernel import error |
|
32 | from IPython.kernel import error | |
33 |
|
33 | |||
@@ -108,7 +108,7 b' class RemoteContextBase(object):' | |||||
108 | return strip_whitespace(wsource) |
|
108 | return strip_whitespace(wsource) | |
109 |
|
109 | |||
110 | def _findsource_ipython(self,f): |
|
110 | def _findsource_ipython(self,f): | |
111 | from IPython import ipapi |
|
111 | from IPython.core import ipapi | |
112 | self.ip = ipapi.get() |
|
112 | self.ip = ipapi.get() | |
113 | buf = self.ip.IP.input_hist_raw[-1].splitlines()[1:] |
|
113 | buf = self.ip.IP.input_hist_raw[-1].splitlines()[1:] | |
114 | wsource = [l+'\n' for l in buf ] |
|
114 | wsource = [l+'\n' for l in buf ] |
@@ -50,7 +50,7 b' from IPython.kernel.engineservice import \\' | |||||
50 | IEngineSerialized, \ |
|
50 | IEngineSerialized, \ | |
51 | IEngineQueued |
|
51 | IEngineQueued | |
52 |
|
52 | |||
53 | from IPython.genutils import get_ipython_dir |
|
53 | from IPython.utils.genutils import get_ipython_dir | |
54 | from IPython.kernel import codeutil |
|
54 | from IPython.kernel import codeutil | |
55 |
|
55 | |||
56 | #------------------------------------------------------------------------------- |
|
56 | #------------------------------------------------------------------------------- |
@@ -29,7 +29,7 b' import sys' | |||||
29 | import traceback |
|
29 | import traceback | |
30 |
|
30 | |||
31 | # Local imports. |
|
31 | # Local imports. | |
32 |
from IPython import ultra |
|
32 | from IPython.core import ultratb | |
33 | from IPython.kernel.core.display_trap import DisplayTrap |
|
33 | from IPython.kernel.core.display_trap import DisplayTrap | |
34 | from IPython.kernel.core.macro import Macro |
|
34 | from IPython.kernel.core.macro import Macro | |
35 | from IPython.kernel.core.prompts import CachedOutput |
|
35 | from IPython.kernel.core.prompts import CachedOutput | |
@@ -167,9 +167,9 b' class Interpreter(object):' | |||||
167 | formatters=self.traceback_formatters) |
|
167 | formatters=self.traceback_formatters) | |
168 |
|
168 | |||
169 | # This is used temporarily for reformating exceptions in certain |
|
169 | # This is used temporarily for reformating exceptions in certain | |
170 |
# cases. It will go away once the ultra |
|
170 | # cases. It will go away once the ultratb stuff is ported | |
171 | # to ipython1 |
|
171 | # to ipython1 | |
172 |
self.tbHandler = ultra |
|
172 | self.tbHandler = ultratb.FormattedTB(color_scheme='NoColor', | |
173 | mode='Context', |
|
173 | mode='Context', | |
174 | tb_offset=2) |
|
174 | tb_offset=2) | |
175 |
|
175 |
@@ -21,30 +21,27 b' __docformat__ = "restructuredtext en"' | |||||
21 |
|
21 | |||
22 | # Required modules |
|
22 | # Required modules | |
23 | import __builtin__ |
|
23 | import __builtin__ | |
24 | import os |
|
|||
25 | import socket |
|
24 | import socket | |
26 | import sys |
|
25 | import sys | |
27 | import time |
|
|||
28 |
|
26 | |||
29 | # IPython's own |
|
27 | # IPython's own | |
30 | from IPython.external.Itpl import ItplNS |
|
28 | from IPython.external.Itpl import ItplNS | |
31 | from macro import Macro |
|
|||
32 |
|
29 | |||
33 |
from IPython import |
|
30 | from IPython.utils import coloransi | |
34 |
from IPython import |
|
31 | from IPython.core import release | |
35 | from IPython.ipapi import TryNext |
|
32 | from IPython.core.ipapi import TryNext | |
36 |
from IPython. |
|
33 | from IPython.utils.genutils import * | |
37 | from IPython.genutils import * |
|
34 | import IPython.utils.generics | |
38 |
|
35 | |||
39 | #**************************************************************************** |
|
36 | #**************************************************************************** | |
40 | #Color schemes for Prompts. |
|
37 | #Color schemes for Prompts. | |
41 |
|
38 | |||
42 |
PromptColors = |
|
39 | PromptColors = coloransi.ColorSchemeTable() | |
43 |
InputColors = |
|
40 | InputColors = coloransi.InputTermColors # just a shorthand | |
44 |
Colors = |
|
41 | Colors = coloransi.TermColors # just a shorthand | |
45 |
|
42 | |||
46 |
|
43 | |||
47 |
__PColNoColor = |
|
44 | __PColNoColor = coloransi.ColorScheme( | |
48 | 'NoColor', |
|
45 | 'NoColor', | |
49 | in_prompt = InputColors.NoColor, # Input prompt |
|
46 | in_prompt = InputColors.NoColor, # Input prompt | |
50 | in_number = InputColors.NoColor, # Input prompt number |
|
47 | in_number = InputColors.NoColor, # Input prompt number | |
@@ -156,7 +153,7 b' prompt_specials_color = {' | |||||
156 | # Carriage return |
|
153 | # Carriage return | |
157 | r'\r': '\r', |
|
154 | r'\r': '\r', | |
158 | # Release version |
|
155 | # Release version | |
159 |
r'\v': |
|
156 | r'\v': release.version, | |
160 | # Root symbol ($ or #) |
|
157 | # Root symbol ($ or #) | |
161 | r'\$': ROOT_SYMBOL, |
|
158 | r'\$': ROOT_SYMBOL, | |
162 | } |
|
159 | } | |
@@ -172,7 +169,7 b" prompt_specials_nocolor[r'\\#'] = '${self.cache.prompt_count}'" | |||||
172 | # with a color name which may begin with a letter used by any other of the |
|
169 | # with a color name which may begin with a letter used by any other of the | |
173 | # allowed specials. This of course means that \\C will never be allowed for |
|
170 | # allowed specials. This of course means that \\C will never be allowed for | |
174 | # anything else. |
|
171 | # anything else. | |
175 |
input_colors = |
|
172 | input_colors = coloransi.InputTermColors | |
176 | for _color in dir(input_colors): |
|
173 | for _color in dir(input_colors): | |
177 | if _color[0] != '_': |
|
174 | if _color[0] != '_': | |
178 | c_name = r'\C_'+_color |
|
175 | c_name = r'\C_'+_color | |
@@ -535,7 +532,7 b' class CachedOutput:' | |||||
535 | display, e.g. when your own objects need special formatting. |
|
532 | display, e.g. when your own objects need special formatting. | |
536 | """ |
|
533 | """ | |
537 | try: |
|
534 | try: | |
538 | return IPython.generics.result_display(arg) |
|
535 | return IPython.utils.generics.result_display(arg) | |
539 | except TryNext: |
|
536 | except TryNext: | |
540 | return self.shell.hooks.result_display(arg) |
|
537 | return self.shell.hooks.result_display(arg) | |
541 |
|
538 |
@@ -18,7 +18,7 b' __docformat__ = "restructuredtext en"' | |||||
18 | # Imports |
|
18 | # Imports | |
19 | #------------------------------------------------------------------------------- |
|
19 | #------------------------------------------------------------------------------- | |
20 | from traceback_trap import TracebackTrap |
|
20 | from traceback_trap import TracebackTrap | |
21 |
from IPython. |
|
21 | from IPython.core.ultratb import ColorTB | |
22 |
|
22 | |||
23 | class SyncTracebackTrap(TracebackTrap): |
|
23 | class SyncTracebackTrap(TracebackTrap): | |
24 | """ TracebackTrap that displays immediatly the traceback in addition |
|
24 | """ TracebackTrap that displays immediatly the traceback in addition |
@@ -23,7 +23,8 b' method that automatically added methods to engines.' | |||||
23 |
|
23 | |||
24 | __docformat__ = "restructuredtext en" |
|
24 | __docformat__ = "restructuredtext en" | |
25 |
|
25 | |||
26 | # Tell nose to skip this module |
|
26 | # Tell nose to skip this module. I don't think we need this as nose | |
|
27 | # shouldn't ever be run on this! | |||
27 | __test__ = {} |
|
28 | __test__ = {} | |
28 |
|
29 | |||
29 | #------------------------------------------------------------------------------- |
|
30 | #------------------------------------------------------------------------------- |
@@ -17,8 +17,8 b' __docformat__ = "restructuredtext en"' | |||||
17 |
|
17 | |||
18 | import new |
|
18 | import new | |
19 |
|
19 | |||
20 | from IPython.iplib import InteractiveShell |
|
20 | from IPython.core.iplib import InteractiveShell | |
21 |
from IPython. |
|
21 | from IPython.core.shell import MTInteractiveShell | |
22 |
|
22 | |||
23 | from twisted.internet.defer import Deferred |
|
23 | from twisted.internet.defer import Deferred | |
24 |
|
24 |
@@ -21,7 +21,7 b' __docformat__ = "restructuredtext en"' | |||||
21 |
|
21 | |||
22 | import types |
|
22 | import types | |
23 |
|
23 | |||
24 | from IPython.genutils import flatten as genutil_flatten |
|
24 | from IPython.utils.genutils import flatten as genutil_flatten | |
25 |
|
25 | |||
26 | #------------------------------------------------------------------------------- |
|
26 | #------------------------------------------------------------------------------- | |
27 | # Figure out which array packages are present and their array types |
|
27 | # Figure out which array packages are present and their array types |
@@ -35,7 +35,7 b' from twisted.internet import defer, reactor' | |||||
35 | from twisted.python import log, components, failure |
|
35 | from twisted.python import log, components, failure | |
36 | from zope.interface import Interface, implements, Attribute |
|
36 | from zope.interface import Interface, implements, Attribute | |
37 |
|
37 | |||
38 |
from IPython. |
|
38 | from IPython.utils import growl | |
39 | from IPython.kernel.util import printer |
|
39 | from IPython.kernel.util import printer | |
40 | from IPython.kernel.twistedutil import gatherBoth |
|
40 | from IPython.kernel.twistedutil import gatherBoth | |
41 | from IPython.kernel import map as Map |
|
41 | from IPython.kernel import map as Map |
@@ -17,17 +17,14 b' __docformat__ = "restructuredtext en"' | |||||
17 | #------------------------------------------------------------------------------- |
|
17 | #------------------------------------------------------------------------------- | |
18 |
|
18 | |||
19 | import sys |
|
19 | import sys | |
20 | import cPickle as pickle |
|
|||
21 | from types import FunctionType |
|
|||
22 | import linecache |
|
20 | import linecache | |
23 | import warnings |
|
21 | import warnings | |
24 |
|
22 | |||
25 |
from twisted. |
|
23 | from twisted.python import components | |
26 | from twisted.python import components, log |
|
|||
27 | from twisted.python.failure import Failure |
|
24 | from twisted.python.failure import Failure | |
28 | from zope.interface import Interface, implements, Attribute |
|
25 | from zope.interface import Interface, implements, Attribute | |
29 |
|
26 | |||
30 |
from IPython. |
|
27 | from IPython.utils.coloransi import TermColors | |
31 |
|
28 | |||
32 | from IPython.kernel.twistedutil import blockingCallFromThread |
|
29 | from IPython.kernel.twistedutil import blockingCallFromThread | |
33 | from IPython.kernel import error |
|
30 | from IPython.kernel import error | |
@@ -37,10 +34,8 b' from IPython.kernel.mapper import (' | |||||
37 | IMultiEngineMapperFactory, |
|
34 | IMultiEngineMapperFactory, | |
38 | IMapper |
|
35 | IMapper | |
39 | ) |
|
36 | ) | |
40 | from IPython.kernel import map as Map |
|
37 | ||
41 |
from IPython.kernel import |
|
38 | from IPython.kernel.multiengine import IFullSynchronousMultiEngine | |
42 | from IPython.kernel.multiengine import (IFullMultiEngine, |
|
|||
43 | IFullSynchronousMultiEngine) |
|
|||
44 |
|
39 | |||
45 |
|
40 | |||
46 | #------------------------------------------------------------------------------- |
|
41 | #------------------------------------------------------------------------------- | |
@@ -310,13 +305,13 b' class InteractiveMultiEngineClient(object):' | |||||
310 |
|
305 | |||
311 | def findsource_file(self,f): |
|
306 | def findsource_file(self,f): | |
312 | linecache.checkcache() |
|
307 | linecache.checkcache() | |
313 | s = findsource(f.f_code) |
|
308 | s = findsource(f.f_code) # findsource is not defined! | |
314 | lnum = f.f_lineno |
|
309 | lnum = f.f_lineno | |
315 | wsource = s[0][f.f_lineno:] |
|
310 | wsource = s[0][f.f_lineno:] | |
316 | return strip_whitespace(wsource) |
|
311 | return strip_whitespace(wsource) | |
317 |
|
312 | |||
318 | def findsource_ipython(self,f): |
|
313 | def findsource_ipython(self,f): | |
319 | from IPython import ipapi |
|
314 | from IPython.core import ipapi | |
320 | self.ip = ipapi.get() |
|
315 | self.ip = ipapi.get() | |
321 | wsource = [l+'\n' for l in |
|
316 | wsource = [l+'\n' for l in | |
322 | self.ip.IP.input_hist_raw[-1].splitlines()[1:]] |
|
317 | self.ip.IP.input_hist_raw[-1].splitlines()[1:]] |
@@ -30,7 +30,7 b' from zope.interface import Interface, implements, Attribute' | |||||
30 | from IPython.kernel.twistedutil import gatherBoth |
|
30 | from IPython.kernel.twistedutil import gatherBoth | |
31 | from IPython.kernel import error |
|
31 | from IPython.kernel import error | |
32 | from IPython.external import guid |
|
32 | from IPython.external import guid | |
33 |
from IPython. |
|
33 | from IPython.utils import growl | |
34 |
|
34 | |||
35 | class PendingDeferredManager(object): |
|
35 | class PendingDeferredManager(object): | |
36 | """A class to track pending deferreds. |
|
36 | """A class to track pending deferreds. |
@@ -29,7 +29,7 b' from twisted.python import failure, log' | |||||
29 |
|
29 | |||
30 | from IPython.external import argparse |
|
30 | from IPython.external import argparse | |
31 | from IPython.external import Itpl |
|
31 | from IPython.external import Itpl | |
32 | from IPython.genutils import ( |
|
32 | from IPython.utils.genutils import ( | |
33 | get_ipython_dir, |
|
33 | get_ipython_dir, | |
34 | get_log_dir, |
|
34 | get_log_dir, | |
35 | get_security_dir, |
|
35 | get_security_dir, | |
@@ -39,7 +39,7 b' from IPython.kernel.fcutil import have_crypto' | |||||
39 |
|
39 | |||
40 | # Create various ipython directories if they don't exist. |
|
40 | # Create various ipython directories if they don't exist. | |
41 | # This must be done before IPython.kernel.config is imported. |
|
41 | # This must be done before IPython.kernel.config is imported. | |
42 | from IPython.iplib import user_setup |
|
42 | from IPython.core.iplib import user_setup | |
43 | if os.name == 'posix': |
|
43 | if os.name == 'posix': | |
44 | rc_suffix = '' |
|
44 | rc_suffix = '' | |
45 | else: |
|
45 | else: |
@@ -32,7 +32,7 b' from twisted.python import log' | |||||
32 |
|
32 | |||
33 | from IPython.kernel.fcutil import Tub, UnauthenticatedTub, have_crypto |
|
33 | from IPython.kernel.fcutil import Tub, UnauthenticatedTub, have_crypto | |
34 |
|
34 | |||
35 |
# from IPython. |
|
35 | # from IPython.utils import growl | |
36 | # growl.start("IPython1 Controller") |
|
36 | # growl.start("IPython1 Controller") | |
37 |
|
37 | |||
38 | from IPython.kernel.error import SecurityError |
|
38 | from IPython.kernel.error import SecurityError | |
@@ -41,8 +41,8 b' from IPython.kernel.fcutil import check_furl_file_security' | |||||
41 |
|
41 | |||
42 | # Create various ipython directories if they don't exist. |
|
42 | # Create various ipython directories if they don't exist. | |
43 | # This must be done before IPython.kernel.config is imported. |
|
43 | # This must be done before IPython.kernel.config is imported. | |
44 | from IPython.iplib import user_setup |
|
44 | from IPython.core.iplib import user_setup | |
45 | from IPython.genutils import get_ipython_dir, get_log_dir, get_security_dir |
|
45 | from IPython.utils.genutils import get_ipython_dir, get_log_dir, get_security_dir | |
46 | if os.name == 'posix': |
|
46 | if os.name == 'posix': | |
47 | rc_suffix = '' |
|
47 | rc_suffix = '' | |
48 | else: |
|
48 | else: |
@@ -36,8 +36,8 b' from IPython.kernel.engineservice import EngineService' | |||||
36 |
|
36 | |||
37 | # Create various ipython directories if they don't exist. |
|
37 | # Create various ipython directories if they don't exist. | |
38 | # This must be done before IPython.kernel.config is imported. |
|
38 | # This must be done before IPython.kernel.config is imported. | |
39 | from IPython.iplib import user_setup |
|
39 | from IPython.core.iplib import user_setup | |
40 | from IPython.genutils import get_ipython_dir, get_log_dir, get_security_dir |
|
40 | from IPython.utils.genutils import get_ipython_dir, get_log_dir, get_security_dir | |
41 | if os.name == 'posix': |
|
41 | if os.name == 'posix': | |
42 | rc_suffix = '' |
|
42 | rc_suffix = '' | |
43 | else: |
|
43 | else: |
@@ -30,8 +30,8 b' separate implementation).' | |||||
30 | import sys |
|
30 | import sys | |
31 | import threading |
|
31 | import threading | |
32 |
|
32 | |||
33 |
from IPython. |
|
33 | from IPython.core.ultratb import AutoFormattedTB | |
34 | from IPython.genutils import warn,error |
|
34 | from IPython.utils.genutils import warn,error | |
35 |
|
35 | |||
36 | class BackgroundJobManager: |
|
36 | class BackgroundJobManager: | |
37 | """Class to manage a pool of backgrounded threaded jobs. |
|
37 | """Class to manage a pool of backgrounded threaded jobs. |
@@ -4,7 +4,7 b'' | |||||
4 | import subprocess |
|
4 | import subprocess | |
5 | import sys |
|
5 | import sys | |
6 |
|
6 | |||
7 | from IPython.ipapi import TryNext |
|
7 | from IPython.core.ipapi import TryNext | |
8 |
|
8 | |||
9 |
|
9 | |||
10 | def win32_clipboard_get(): |
|
10 | def win32_clipboard_get(): |
@@ -2,14 +2,14 b'' | |||||
2 | """ |
|
2 | """ | |
3 | A module to change reload() so that it acts recursively. |
|
3 | A module to change reload() so that it acts recursively. | |
4 | To enable it type: |
|
4 | To enable it type: | |
5 |
>>> import __builtin__, deep |
|
5 | >>> import __builtin__, deepreload | |
6 |
>>> __builtin__.reload = deep |
|
6 | >>> __builtin__.reload = deepreload.reload | |
7 |
|
7 | |||
8 | You can then disable it with: |
|
8 | You can then disable it with: | |
9 |
>>> __builtin__.reload = deep |
|
9 | >>> __builtin__.reload = deepreload.original_reload | |
10 |
|
10 | |||
11 | Alternatively, you can add a dreload builtin alongside normal reload with: |
|
11 | Alternatively, you can add a dreload builtin alongside normal reload with: | |
12 |
>>> __builtin__.dreload = deep |
|
12 | >>> __builtin__.dreload = deepreload.reload | |
13 |
|
13 | |||
14 | This code is almost entirely based on knee.py from the standard library. |
|
14 | This code is almost entirely based on knee.py from the standard library. | |
15 | """ |
|
15 | """ |
@@ -175,8 +175,8 b' import re' | |||||
175 | import shlex |
|
175 | import shlex | |
176 | import sys |
|
176 | import sys | |
177 |
|
177 | |||
178 | from IPython.PyColorize import Parser |
|
178 | from IPython.utils.PyColorize import Parser | |
179 | from IPython.genutils import marquee, file_read, file_readlines, Term |
|
179 | from IPython.utils.genutils import marquee, file_read, file_readlines, Term | |
180 |
|
180 | |||
181 | __all__ = ['Demo','IPythonDemo','LineDemo','IPythonLineDemo','DemoError'] |
|
181 | __all__ = ['Demo','IPythonDemo','LineDemo','IPythonLineDemo','DemoError'] | |
182 |
|
182 | |||
@@ -543,8 +543,8 b' class ClearMixin(object):' | |||||
543 | """Method called before executing each block. |
|
543 | """Method called before executing each block. | |
544 |
|
544 | |||
545 | This one simply clears the screen.""" |
|
545 | This one simply clears the screen.""" | |
546 |
|
|
546 | from IPython.utils.platutils import term_clear | |
547 |
|
|
547 | term_clear() | |
548 |
|
548 | |||
549 | class ClearDemo(ClearMixin,Demo): |
|
549 | class ClearDemo(ClearMixin,Demo): | |
550 | pass |
|
550 | pass |
1 | NO CONTENT: file renamed from IPython/irunner.py to IPython/lib/irunner.py |
|
NO CONTENT: file renamed from IPython/irunner.py to IPython/lib/irunner.py |
1 | NO CONTENT: file renamed from scripts/iptest to IPython/scripts/iptest |
|
NO CONTENT: file renamed from scripts/iptest to IPython/scripts/iptest |
@@ -23,6 +23,6 b' this mode, there is no way to pass IPython any command-line options, as those' | |||||
23 | are trapped first by Python itself. |
|
23 | are trapped first by Python itself. | |
24 | """ |
|
24 | """ | |
25 |
|
25 | |||
26 |
import IPython. |
|
26 | import IPython.core.shell | |
27 |
|
27 | |||
28 |
IPython. |
|
28 | IPython.core.shell.start().mainloop() |
1 | NO CONTENT: file renamed from scripts/ipython-wx to IPython/scripts/ipython-wx |
|
NO CONTENT: file renamed from scripts/ipython-wx to IPython/scripts/ipython-wx |
1 | NO CONTENT: file renamed from scripts/ipythonx to IPython/scripts/ipythonx |
|
NO CONTENT: file renamed from scripts/ipythonx to IPython/scripts/ipythonx |
@@ -4,6 +4,6 b'' | |||||
4 |
|
4 | |||
5 | Run with --help for details, or see the irunner source.""" |
|
5 | Run with --help for details, or see the irunner source.""" | |
6 |
|
6 | |||
7 | from IPython import irunner |
|
7 | from IPython.lib import irunner | |
8 |
|
8 | |||
9 | irunner.main() |
|
9 | irunner.main() |
@@ -2,5 +2,5 b'' | |||||
2 | # -*- coding: utf-8 -*- |
|
2 | # -*- coding: utf-8 -*- | |
3 | """Simple wrapper around PyColorize, which colorizes python sources.""" |
|
3 | """Simple wrapper around PyColorize, which colorizes python sources.""" | |
4 |
|
4 | |||
5 | import IPython.PyColorize |
|
5 | import IPython.utils.PyColorize | |
6 | IPython.PyColorize.main() |
|
6 | IPython.utils.PyColorize.main() |
@@ -31,7 +31,7 b' import warnings' | |||||
31 | import nose.plugins.builtin |
|
31 | import nose.plugins.builtin | |
32 | from nose.core import TestProgram |
|
32 | from nose.core import TestProgram | |
33 |
|
33 | |||
34 | from IPython.platutils import find_cmd |
|
34 | from IPython.utils.platutils import find_cmd | |
35 | from IPython.testing.plugin.ipdoctest import IPythonDoctest |
|
35 | from IPython.testing.plugin.ipdoctest import IPythonDoctest | |
36 |
|
36 | |||
37 | pjoin = path.join |
|
37 | pjoin = path.join | |
@@ -58,75 +58,85 b" have_foolscap = test_for('foolscap')" | |||||
58 | have_objc = test_for('objc') |
|
58 | have_objc = test_for('objc') | |
59 | have_pexpect = test_for('pexpect') |
|
59 | have_pexpect = test_for('pexpect') | |
60 |
|
60 | |||
61 | # For the IPythonDoctest plugin, we need to exclude certain patterns that cause |
|
61 | ||
62 | # testing problems. We should strive to minimize the number of skipped |
|
62 | def make_exclude(): | |
63 | # modules, since this means untested code. As the testing machinery |
|
63 | ||
64 | # solidifies, this list should eventually become empty. |
|
64 | # For the IPythonDoctest plugin, we need to exclude certain patterns that cause | |
65 | EXCLUDE = [pjoin('IPython', 'external'), |
|
65 | # testing problems. We should strive to minimize the number of skipped | |
66 | pjoin('IPython', 'frontend', 'process', 'winprocess.py'), |
|
66 | # modules, since this means untested code. As the testing machinery | |
67 | pjoin('IPython_doctest_plugin'), |
|
67 | # solidifies, this list should eventually become empty. | |
68 |
|
|
68 | EXCLUDE = [pjoin('IPython', 'external'), | |
69 |
pjoin('IPython', ' |
|
69 | pjoin('IPython', 'frontend', 'process', 'winprocess.py'), | |
70 | pjoin('IPython', 'Extensions', 'PhysicalQInput'), |
|
70 | pjoin('IPython_doctest_plugin'), | |
71 |
pjoin('IPython', ' |
|
71 | pjoin('IPython', 'extensions', 'ipy_'), | |
72 |
pjoin('IPython', ' |
|
72 | pjoin('IPython', 'extensions', 'PhysicalQInput'), | |
73 |
pjoin('IPython', ' |
|
73 | pjoin('IPython', 'extensions', 'PhysicalQInteractive'), | |
74 |
pjoin('IPython', ' |
|
74 | pjoin('IPython', 'extensions', 'InterpreterPasteInput'), | |
75 |
pjoin('IPython', ' |
|
75 | pjoin('IPython', 'extensions', 'scitedirector'), | |
76 |
pjoin('IPython', ' |
|
76 | pjoin('IPython', 'extensions', 'numeric_formats'), | |
77 |
pjoin('IPython', 'testing', ' |
|
77 | pjoin('IPython', 'testing', 'attic'), | |
78 |
pjoin('IPython', 'testing', ' |
|
78 | pjoin('IPython', 'testing', 'tools'), | |
79 | ] |
|
79 | pjoin('IPython', 'testing', 'mkdoctests') | |
80 |
|
80 | ] | ||
81 | if not have_wx: |
|
81 | ||
82 | EXCLUDE.append(pjoin('IPython', 'Extensions', 'igrid')) |
|
82 | if not have_wx: | |
83 |
EXCLUDE.append(pjoin('IPython', ' |
|
83 | EXCLUDE.append(pjoin('IPython', 'extensions', 'igrid')) | |
84 |
EXCLUDE.append(pjoin('IPython', ' |
|
84 | EXCLUDE.append(pjoin('IPython', 'gui')) | |
85 |
|
85 | EXCLUDE.append(pjoin('IPython', 'frontend', 'wx')) | ||
86 | if not have_wx_aui: |
|
86 | ||
87 | EXCLUDE.append(pjoin('IPython', 'gui', 'wx', 'wxIPython')) |
|
87 | if not have_wx_aui: | |
88 |
|
88 | EXCLUDE.append(pjoin('IPython', 'gui', 'wx', 'wxIPython')) | ||
89 | if not have_objc: |
|
89 | ||
90 | EXCLUDE.append(pjoin('IPython', 'frontend', 'cocoa')) |
|
90 | if not have_objc: | |
91 |
|
91 | EXCLUDE.append(pjoin('IPython', 'frontend', 'cocoa')) | ||
92 | if not have_curses: |
|
92 | ||
93 | EXCLUDE.append(pjoin('IPython', 'Extensions', 'ibrowse')) |
|
93 | if not have_curses: | |
94 |
|
94 | EXCLUDE.append(pjoin('IPython', 'extensions', 'ibrowse')) | ||
95 | if not sys.platform == 'win32': |
|
95 | ||
96 | EXCLUDE.append(pjoin('IPython', 'platutils_win32')) |
|
96 | if not sys.platform == 'win32': | |
97 |
|
97 | EXCLUDE.append(pjoin('IPython', 'utils', 'platutils_win32')) | ||
98 | # These have to be skipped on win32 because the use echo, rm, cd, etc. |
|
98 | ||
99 | # See ticket https://bugs.launchpad.net/bugs/366982 |
|
99 | # These have to be skipped on win32 because the use echo, rm, cd, etc. | |
100 | if sys.platform == 'win32': |
|
100 | # See ticket https://bugs.launchpad.net/bugs/366982 | |
101 | EXCLUDE.append(pjoin('IPython', 'testing', 'plugin', 'test_exampleip')) |
|
101 | if sys.platform == 'win32': | |
102 |
EXCLUDE.append(pjoin('IPython', 'testing', 'plugin', ' |
|
102 | EXCLUDE.append(pjoin('IPython', 'testing', 'plugin', 'test_exampleip')) | |
103 |
|
103 | EXCLUDE.append(pjoin('IPython', 'testing', 'plugin', 'dtexample')) | ||
104 | if not os.name == 'posix': |
|
104 | ||
105 | EXCLUDE.append(pjoin('IPython', 'platutils_posix')) |
|
105 | if not os.name == 'posix': | |
106 |
|
106 | EXCLUDE.append(pjoin('IPython', 'utils', 'platutils_posix')) | ||
107 | if not have_pexpect: |
|
107 | ||
108 | EXCLUDE.append(pjoin('IPython', 'irunner')) |
|
108 | if not have_pexpect: | |
109 |
|
109 | EXCLUDE.append(pjoin('IPython', 'scripts', 'irunner')) | ||
110 | if not have_twisted: |
|
110 | ||
111 | EXCLUDE.append(pjoin('IPython', 'frontend', 'asyncfrontendbase')) |
|
111 | # This is scary. We still have things in frontend and testing that | |
112 | EXCLUDE.append(pjoin('IPython', 'frontend', 'prefilterfrontend')) |
|
112 | # are being tested by nose that use twisted. We need to rethink | |
113 | EXCLUDE.append(pjoin('IPython', 'frontend', 'frontendbase')) |
|
113 | # how we are isolating dependencies in testing. | |
114 | EXCLUDE.append(pjoin('IPython', 'frontend', 'linefrontendbase')) |
|
114 | if not (have_twisted and have_zi and have_foolscap): | |
115 |
EXCLUDE.append(pjoin('IPython', 'frontend', ' |
|
115 | EXCLUDE.append(pjoin('IPython', 'frontend', 'asyncfrontendbase')) | |
116 |
EXCLUDE.append(pjoin('IPython', 'frontend', ' |
|
116 | EXCLUDE.append(pjoin('IPython', 'frontend', 'prefilterfrontend')) | |
117 |
EXCLUDE.append(pjoin('IPython', 'frontend', ' |
|
117 | EXCLUDE.append(pjoin('IPython', 'frontend', 'frontendbase')) | |
118 | 'test_prefilterfrontend')) |
|
118 | EXCLUDE.append(pjoin('IPython', 'frontend', 'linefrontendbase')) | |
119 | EXCLUDE.append(pjoin('IPython', 'frontend', 'tests', |
|
119 | EXCLUDE.append(pjoin('IPython', 'frontend', 'tests', | |
120 |
'test_ |
|
120 | 'test_linefrontend')) | |
121 |
EXCLUDE.append(pjoin('IPython', ' |
|
121 | EXCLUDE.append(pjoin('IPython', 'frontend', 'tests', | |
122 | EXCLUDE.append(pjoin('IPython', 'testing', 'parametric')) |
|
122 | 'test_frontendbase')) | |
123 |
EXCLUDE.append(pjoin('IPython', ' |
|
123 | EXCLUDE.append(pjoin('IPython', 'frontend', 'tests', | |
124 | EXCLUDE.append(pjoin('IPython', 'testing', 'tests', 'test_decorators_trial')) |
|
124 | 'test_prefilterfrontend')) | |
125 |
|
125 | EXCLUDE.append(pjoin('IPython', 'frontend', 'tests', | ||
126 |
|
126 | 'test_asyncfrontendbase')), | ||
127 | # This is needed for the reg-exp to match on win32 in the ipdoctest plugin. |
|
127 | EXCLUDE.append(pjoin('IPython', 'testing', 'parametric')) | |
128 | if sys.platform == 'win32': |
|
128 | EXCLUDE.append(pjoin('IPython', 'testing', 'util')) | |
129 | EXCLUDE = [s.replace('\\','\\\\') for s in EXCLUDE] |
|
129 | EXCLUDE.append(pjoin('IPython', 'testing', 'tests', | |
|
130 | 'test_decorators_trial')) | |||
|
131 | ||||
|
132 | # Skip shell always because of a bug in FakeModule. | |||
|
133 | EXCLUDE.append(pjoin('IPython', 'core', 'shell')) | |||
|
134 | ||||
|
135 | # This is needed for the reg-exp to match on win32 in the ipdoctest plugin. | |||
|
136 | if sys.platform == 'win32': | |||
|
137 | EXCLUDE = [s.replace('\\','\\\\') for s in EXCLUDE] | |||
|
138 | ||||
|
139 | return EXCLUDE | |||
130 |
|
140 | |||
131 |
|
141 | |||
132 | #----------------------------------------------------------------------------- |
|
142 | #----------------------------------------------------------------------------- | |
@@ -178,13 +188,12 b' def run_iptest():' | |||||
178 |
|
188 | |||
179 | # Construct list of plugins, omitting the existing doctest plugin, which |
|
189 | # Construct list of plugins, omitting the existing doctest plugin, which | |
180 | # ours replaces (and extends). |
|
190 | # ours replaces (and extends). | |
|
191 | EXCLUDE = make_exclude() | |||
181 | plugins = [IPythonDoctest(EXCLUDE)] |
|
192 | plugins = [IPythonDoctest(EXCLUDE)] | |
182 | for p in nose.plugins.builtin.plugins: |
|
193 | for p in nose.plugins.builtin.plugins: | |
183 | plug = p() |
|
194 | plug = p() | |
184 | if plug.name == 'doctest': |
|
195 | if plug.name == 'doctest': | |
185 | continue |
|
196 | continue | |
186 |
|
||||
187 | #print '*** adding plugin:',plug.name # dbg |
|
|||
188 | plugins.append(plug) |
|
197 | plugins.append(plug) | |
189 |
|
198 | |||
190 | TestProgram(argv=argv,plugins=plugins) |
|
199 | TestProgram(argv=argv,plugins=plugins) | |
@@ -234,58 +243,28 b' class IPTester(object):' | |||||
234 |
|
243 | |||
235 |
|
244 | |||
236 | def make_runners(): |
|
245 | def make_runners(): | |
237 |
"""Define the |
|
246 | """Define the top-level packages that need to be tested. | |
238 | """ |
|
247 | """ | |
239 |
|
||||
240 | # This omits additional top-level modules that should not be doctested. |
|
|||
241 | # XXX: Shell.py is also ommited because of a bug in the skip_doctest |
|
|||
242 | # decorator. See ticket https://bugs.launchpad.net/bugs/366209 |
|
|||
243 | top_mod = \ |
|
|||
244 | ['background_jobs.py', 'ColorANSI.py', 'completer.py', 'ConfigLoader.py', |
|
|||
245 | 'CrashHandler.py', 'Debugger.py', 'deep_reload.py', 'demo.py', |
|
|||
246 | 'DPyGetOpt.py', 'dtutils.py', 'excolors.py', 'FakeModule.py', |
|
|||
247 | 'generics.py', 'genutils.py', 'history.py', 'hooks.py', 'ipapi.py', |
|
|||
248 | 'iplib.py', 'ipmaker.py', 'ipstruct.py', 'Itpl.py', |
|
|||
249 | 'Logger.py', 'macro.py', 'Magic.py', 'OInspect.py', |
|
|||
250 | 'OutputTrap.py', 'platutils.py', 'prefilter.py', 'Prompts.py', |
|
|||
251 | 'PyColorize.py', 'Release.py', 'rlineimpl.py', 'shadowns.py', |
|
|||
252 | 'shellglobals.py', 'strdispatch.py', |
|
|||
253 | 'ultraTB.py', 'upgrade_dir.py', 'usage.py', 'wildcard.py', |
|
|||
254 | # See note above for why this is skipped |
|
|||
255 | # 'Shell.py', |
|
|||
256 | 'winconsole.py'] |
|
|||
257 |
|
||||
258 | if have_twisted: |
|
|||
259 | top_mod.append('twshell.py') |
|
|||
260 |
|
||||
261 | if have_pexpect: |
|
|||
262 | top_mod.append('irunner.py') |
|
|||
263 |
|
248 | |||
264 | if sys.platform == 'win32': |
|
249 | nose_packages = ['config', 'core', 'extensions', | |
265 | top_mod.append('platutils_win32.py') |
|
250 | 'frontend', 'lib', 'quarantine', | |
266 | elif os.name == 'posix': |
|
251 | 'scripts', 'testing', 'utils'] | |
267 | top_mod.append('platutils_posix.py') |
|
252 | trial_packages = ['kernel'] | |
268 | else: |
|
|||
269 | top_mod.append('platutils_dummy.py') |
|
|||
270 |
|
||||
271 | # These are tested by nose, so skip IPython.kernel |
|
|||
272 | top_pack = ['config','Extensions','frontend', |
|
|||
273 | 'testing','tests','tools','UserConfig'] |
|
|||
274 |
|
253 | |||
275 | if have_wx: |
|
254 | if have_wx: | |
276 |
|
|
255 | nose_packages.append('gui') | |
277 |
|
256 | |||
278 |
|
|
257 | nose_packages = ['IPython.%s' % m for m in nose_packages ] | |
279 |
packages = ['IPython.%s' % m for m in t |
|
258 | trial_packages = ['IPython.%s' % m for m in trial_packages ] | |
280 |
|
259 | |||
281 | # Make runners |
|
260 | # Make runners | |
282 | runners = dict(zip(top_pack, [IPTester(params=v) for v in packages])) |
|
261 | runners = dict() | |
283 |
|
262 | |||
284 | # Test IPython.kernel using trial if twisted is installed |
|
263 | nose_runners = dict(zip(nose_packages, [IPTester(params=v) for v in nose_packages])) | |
285 | if have_zi and have_twisted and have_foolscap: |
|
264 | if have_zi and have_twisted and have_foolscap: | |
286 | runners['trial'] = IPTester('trial',['IPython']) |
|
265 | trial_runners = dict(zip(trial_packages, [IPTester('trial',params=v) for v in trial_packages])) | |
287 |
|
266 | runners.update(nose_runners) | ||
288 | runners['modules'] = IPTester(params=modules) |
|
267 | runners.update(trial_runners) | |
289 |
|
268 | |||
290 | return runners |
|
269 | return runners | |
291 |
|
270 | |||
@@ -298,7 +277,9 b' def run_iptestall():' | |||||
298 | and packages of IPython to be tested each in their own subprocess using |
|
277 | and packages of IPython to be tested each in their own subprocess using | |
299 | nose or twisted.trial appropriately. |
|
278 | nose or twisted.trial appropriately. | |
300 | """ |
|
279 | """ | |
|
280 | ||||
301 | runners = make_runners() |
|
281 | runners = make_runners() | |
|
282 | ||||
302 | # Run all test runners, tracking execution time |
|
283 | # Run all test runners, tracking execution time | |
303 | failed = {} |
|
284 | failed = {} | |
304 | t_start = time.time() |
|
285 | t_start = time.time() |
@@ -37,8 +37,8 b' import sys' | |||||
37 | import tempfile |
|
37 | import tempfile | |
38 |
|
38 | |||
39 | # IPython-specific libraries |
|
39 | # IPython-specific libraries | |
40 | from IPython import irunner |
|
40 | from IPython.lib import irunner | |
41 | from IPython.genutils import fatal |
|
41 | from IPython.utils.genutils import fatal | |
42 |
|
42 | |||
43 | class IndentOut(object): |
|
43 | class IndentOut(object): | |
44 | """A simple output stream that indents all output by a fixed amount. |
|
44 | """A simple output stream that indents all output by a fixed amount. |
@@ -34,16 +34,16 b' deco:' | |||||
34 | $(NOSE0) IPython.testing.decorators |
|
34 | $(NOSE0) IPython.testing.decorators | |
35 |
|
35 | |||
36 | magic: plugin |
|
36 | magic: plugin | |
37 |
$(NOSE) IPython. |
|
37 | $(NOSE) IPython.core.magic | |
38 |
|
38 | |||
39 | excolors: plugin |
|
39 | excolors: plugin | |
40 | $(NOSE) IPython.excolors |
|
40 | $(NOSE) IPython.core.excolors | |
41 |
|
41 | |||
42 | iplib: plugin |
|
42 | iplib: plugin | |
43 | $(NOSE) IPython.iplib |
|
43 | $(NOSE) IPython.core.iplib | |
44 |
|
44 | |||
45 | strd: plugin |
|
45 | strd: plugin | |
46 | $(NOSE) IPython.strdispatch |
|
46 | $(NOSE) IPython.core.strdispatch | |
47 |
|
47 | |||
48 | engine: plugin |
|
48 | engine: plugin | |
49 | $(NOSE) IPython.kernel |
|
49 | $(NOSE) IPython.kernel |
@@ -64,8 +64,8 b' def default_argv():' | |||||
64 |
|
64 | |||
65 | # Get the install directory for the user configuration and tell ipython to |
|
65 | # Get the install directory for the user configuration and tell ipython to | |
66 | # use the default profile from there. |
|
66 | # use the default profile from there. | |
67 |
from IPython import |
|
67 | from IPython.config import userconfig | |
68 |
ipcdir = os.path.dirname( |
|
68 | ipcdir = os.path.dirname(userconfig.__file__) | |
69 | #ipconf = os.path.join(ipcdir,'ipy_user_conf.py') |
|
69 | #ipconf = os.path.join(ipcdir,'ipy_user_conf.py') | |
70 | ipconf = os.path.join(ipcdir,'ipythonrc') |
|
70 | ipconf = os.path.join(ipcdir,'ipythonrc') | |
71 | #print 'conf:',ipconf # dbg |
|
71 | #print 'conf:',ipconf # dbg | |
@@ -82,7 +82,7 b' class py_file_finder(object):' | |||||
82 | self.test_filename = test_filename |
|
82 | self.test_filename = test_filename | |
83 |
|
83 | |||
84 | def __call__(self,name): |
|
84 | def __call__(self,name): | |
85 | from IPython.genutils import get_py_filename |
|
85 | from IPython.utils.genutils import get_py_filename | |
86 | try: |
|
86 | try: | |
87 | return get_py_filename(name) |
|
87 | return get_py_filename(name) | |
88 | except IOError: |
|
88 | except IOError: | |
@@ -164,7 +164,8 b' def start_ipython():' | |||||
164 | import new |
|
164 | import new | |
165 |
|
165 | |||
166 | import IPython |
|
166 | import IPython | |
167 |
|
167 | from IPython.core import ipapi | ||
|
168 | ||||
168 | def xsys(cmd): |
|
169 | def xsys(cmd): | |
169 | """Execute a command and print its output. |
|
170 | """Execute a command and print its output. | |
170 |
|
171 | |||
@@ -183,8 +184,8 b' def start_ipython():' | |||||
183 | argv = default_argv() |
|
184 | argv = default_argv() | |
184 |
|
185 | |||
185 | # Start IPython instance. We customize it to start with minimal frills. |
|
186 | # Start IPython instance. We customize it to start with minimal frills. | |
186 |
user_ns,global_ns = |
|
187 | user_ns,global_ns = ipapi.make_user_namespaces(ipnsdict(),dict()) | |
187 |
IPython. |
|
188 | IPython.shell.IPShell(argv,user_ns,global_ns) | |
188 |
|
189 | |||
189 | # Deactivate the various python system hooks added by ipython for |
|
190 | # Deactivate the various python system hooks added by ipython for | |
190 | # interactive convenience so we don't confuse the doctest system |
|
191 | # interactive convenience so we don't confuse the doctest system | |
@@ -194,7 +195,7 b' def start_ipython():' | |||||
194 |
|
195 | |||
195 | # So that ipython magics and aliases can be doctested (they work by making |
|
196 | # So that ipython magics and aliases can be doctested (they work by making | |
196 | # a call into a global _ip object) |
|
197 | # a call into a global _ip object) | |
197 |
_ip = |
|
198 | _ip = ipapi.get() | |
198 | __builtin__._ip = _ip |
|
199 | __builtin__._ip = _ip | |
199 |
|
200 | |||
200 | # Modify the IPython system call with one that uses getoutput, so that we |
|
201 | # Modify the IPython system call with one that uses getoutput, so that we | |
@@ -210,7 +211,7 b' def start_ipython():' | |||||
210 | # XXX - For some very bizarre reason, the loading of %history by default is |
|
211 | # XXX - For some very bizarre reason, the loading of %history by default is | |
211 | # failing. This needs to be fixed later, but for now at least this ensures |
|
212 | # failing. This needs to be fixed later, but for now at least this ensures | |
212 | # that tests that use %hist run to completion. |
|
213 | # that tests that use %hist run to completion. | |
213 | from IPython import history |
|
214 | from IPython.core import history | |
214 | history.init_ipython(_ip) |
|
215 | history.init_ipython(_ip) | |
215 | if not hasattr(_ip.IP,'magic_history'): |
|
216 | if not hasattr(_ip.IP,'magic_history'): | |
216 | raise RuntimeError("Can't load magics, aborting") |
|
217 | raise RuntimeError("Can't load magics, aborting") |
@@ -31,7 +31,7 b' import sys' | |||||
31 |
|
31 | |||
32 | import nose.tools as nt |
|
32 | import nose.tools as nt | |
33 |
|
33 | |||
34 |
from IPython. |
|
34 | from IPython.utils import genutils | |
35 | from IPython.testing import decorators as dec |
|
35 | from IPython.testing import decorators as dec | |
36 |
|
36 | |||
37 | #----------------------------------------------------------------------------- |
|
37 | #----------------------------------------------------------------------------- | |
@@ -84,6 +84,6 b' def full_path(startPath,files):' | |||||
84 | ['/a.txt'] |
|
84 | ['/a.txt'] | |
85 | """ |
|
85 | """ | |
86 |
|
86 | |||
87 | files = utils.list_strings(files) |
|
87 | files = genutils.list_strings(files) | |
88 | base = os.path.split(startPath)[0] |
|
88 | base = os.path.split(startPath)[0] | |
89 | return [ os.path.join(base,f) for f in files ] |
|
89 | return [ os.path.join(base,f) for f in files ] |
1 | NO CONTENT: file renamed from IPython/DPyGetOpt.py to IPython/utils/DPyGetOpt.py |
|
NO CONTENT: file renamed from IPython/DPyGetOpt.py to IPython/utils/DPyGetOpt.py |
@@ -38,12 +38,11 b' import cStringIO' | |||||
38 | import keyword |
|
38 | import keyword | |
39 | import os |
|
39 | import os | |
40 | import optparse |
|
40 | import optparse | |
41 | import string |
|
|||
42 | import sys |
|
41 | import sys | |
43 | import token |
|
42 | import token | |
44 | import tokenize |
|
43 | import tokenize | |
45 |
|
44 | |||
46 |
from IPython. |
|
45 | from IPython.utils.coloransi import * | |
47 |
|
46 | |||
48 | ############################################################################# |
|
47 | ############################################################################# | |
49 | ### Python Source Parser (does Hilighting) |
|
48 | ### Python Source Parser (does Hilighting) |
@@ -13,7 +13,7 b" __all__ = ['TermColors','InputTermColors','ColorScheme','ColorSchemeTable']" | |||||
13 |
|
13 | |||
14 | import os |
|
14 | import os | |
15 |
|
15 | |||
16 | from IPython.ipstruct import Struct |
|
16 | from IPython.utils.ipstruct import Struct | |
17 |
|
17 | |||
18 | def make_color_table(in_class): |
|
18 | def make_color_table(in_class): | |
19 | """Build a set of color attributes in a class. |
|
19 | """Build a set of color attributes in a class. |
@@ -15,7 +15,7 b' Here is an example from genutils.py:' | |||||
15 | can use the niftier decorator syntax introduced in Python 2.4). |
|
15 | can use the niftier decorator syntax introduced in Python 2.4). | |
16 | ''' |
|
16 | ''' | |
17 |
|
17 | |||
18 | from IPython.ipapi import TryNext |
|
18 | from IPython.core.ipapi import TryNext | |
19 | from IPython.external.simplegeneric import generic |
|
19 | from IPython.external.simplegeneric import generic | |
20 |
|
20 | |||
21 | def result_display(result): |
|
21 | def result_display(result): |
1 | NO CONTENT: file renamed from IPython/genutils.py to IPython/utils/genutils.py |
|
NO CONTENT: file renamed from IPython/genutils.py to IPython/utils/genutils.py | ||
The requested commit or file is too big and content was truncated. Show full diff |
1 | NO CONTENT: file renamed from IPython/tools/growl.py to IPython/utils/growl.py |
|
NO CONTENT: file renamed from IPython/tools/growl.py to IPython/utils/growl.py |
1 | NO CONTENT: file renamed from IPython/ipstruct.py to IPython/utils/ipstruct.py |
|
NO CONTENT: file renamed from IPython/ipstruct.py to IPython/utils/ipstruct.py | ||
The requested commit or file is too big and content was truncated. Show full diff |
1 | NO CONTENT: file renamed from IPython/platutils.py to IPython/utils/platutils.py |
|
NO CONTENT: file renamed from IPython/platutils.py to IPython/utils/platutils.py |
1 | NO CONTENT: file renamed from IPython/platutils_dummy.py to IPython/utils/platutils_dummy.py |
|
NO CONTENT: file renamed from IPython/platutils_dummy.py to IPython/utils/platutils_dummy.py |
1 | NO CONTENT: file renamed from IPython/platutils_posix.py to IPython/utils/platutils_posix.py |
|
NO CONTENT: file renamed from IPython/platutils_posix.py to IPython/utils/platutils_posix.py |
1 | NO CONTENT: file renamed from IPython/platutils_win32.py to IPython/utils/platutils_win32.py |
|
NO CONTENT: file renamed from IPython/platutils_win32.py to IPython/utils/platutils_win32.py |
1 | NO CONTENT: file renamed from IPython/rlineimpl.py to IPython/utils/rlineimpl.py |
|
NO CONTENT: file renamed from IPython/rlineimpl.py to IPython/utils/rlineimpl.py | ||
The requested commit or file is too big and content was truncated. Show full diff |
1 | NO CONTENT: file renamed from IPython/strdispatch.py to IPython/utils/strdispatch.py |
|
NO CONTENT: file renamed from IPython/strdispatch.py to IPython/utils/strdispatch.py | ||
The requested commit or file is too big and content was truncated. Show full diff |
1 | NO CONTENT: file renamed from IPython/tests/test_genutils.py to IPython/utils/tests/test_genutils.py |
|
NO CONTENT: file renamed from IPython/tests/test_genutils.py to IPython/utils/tests/test_genutils.py | ||
The requested commit or file is too big and content was truncated. Show full diff |
1 | NO CONTENT: file renamed from IPython/tests/test_platutils.py to IPython/utils/tests/test_platutils.py |
|
NO CONTENT: file renamed from IPython/tests/test_platutils.py to IPython/utils/tests/test_platutils.py | ||
The requested commit or file is too big and content was truncated. Show full diff |
1 | NO CONTENT: file renamed from IPython/upgrade_dir.py to IPython/utils/upgradedir.py |
|
NO CONTENT: file renamed from IPython/upgrade_dir.py to IPython/utils/upgradedir.py |
1 | NO CONTENT: file renamed from IPython/wildcard.py to IPython/utils/wildcard.py |
|
NO CONTENT: file renamed from IPython/wildcard.py to IPython/utils/wildcard.py | ||
The requested commit or file is too big and content was truncated. Show full diff |
1 | NO CONTENT: file renamed from IPython/winconsole.py to IPython/utils/winconsole.py |
|
NO CONTENT: file renamed from IPython/winconsole.py to IPython/utils/winconsole.py |
1 | NO CONTENT: modified file |
|
NO CONTENT: modified file | ||
The requested commit or file is too big and content was truncated. Show full diff |
1 | NO CONTENT: modified file |
|
NO CONTENT: modified file | ||
The requested commit or file is too big and content was truncated. Show full diff |
1 | NO CONTENT: modified file |
|
NO CONTENT: modified file | ||
The requested commit or file is too big and content was truncated. Show full diff |
1 | NO CONTENT: modified file |
|
NO CONTENT: modified file | ||
The requested commit or file is too big and content was truncated. Show full diff |
1 | NO CONTENT: modified file |
|
NO CONTENT: modified file | ||
The requested commit or file is too big and content was truncated. Show full diff |
1 | NO CONTENT: modified file |
|
NO CONTENT: modified file | ||
The requested commit or file is too big and content was truncated. Show full diff |
1 | NO CONTENT: modified file |
|
NO CONTENT: modified file | ||
The requested commit or file is too big and content was truncated. Show full diff |
1 | NO CONTENT: modified file |
|
NO CONTENT: modified file | ||
The requested commit or file is too big and content was truncated. Show full diff |
1 | NO CONTENT: modified file |
|
NO CONTENT: modified file | ||
The requested commit or file is too big and content was truncated. Show full diff |
1 | NO CONTENT: modified file |
|
NO CONTENT: modified file | ||
The requested commit or file is too big and content was truncated. Show full diff |
1 | NO CONTENT: modified file |
|
NO CONTENT: modified file | ||
The requested commit or file is too big and content was truncated. Show full diff |
1 | NO CONTENT: modified file |
|
NO CONTENT: modified file | ||
The requested commit or file is too big and content was truncated. Show full diff |
1 | NO CONTENT: modified file |
|
NO CONTENT: modified file | ||
The requested commit or file is too big and content was truncated. Show full diff |
1 | NO CONTENT: modified file |
|
NO CONTENT: modified file | ||
The requested commit or file is too big and content was truncated. Show full diff |
1 | NO CONTENT: modified file |
|
NO CONTENT: modified file | ||
The requested commit or file is too big and content was truncated. Show full diff |
1 | NO CONTENT: modified file |
|
NO CONTENT: modified file | ||
The requested commit or file is too big and content was truncated. Show full diff |
1 | NO CONTENT: file was removed |
|
NO CONTENT: file was removed |
1 | NO CONTENT: file was removed |
|
NO CONTENT: file was removed |
1 | NO CONTENT: file was removed |
|
NO CONTENT: file was removed |
1 | NO CONTENT: file was removed |
|
NO CONTENT: file was removed |
General Comments 0
You need to be logged in to leave comments.
Login now