Show More
@@ -1,327 +1,330 b'' | |||
|
1 | 1 | # -*- coding: utf-8 -*- |
|
2 | 2 | """Displayhook for IPython. |
|
3 | 3 | |
|
4 | 4 | This defines a callable class that IPython uses for `sys.displayhook`. |
|
5 | 5 | |
|
6 | 6 | Authors: |
|
7 | 7 | |
|
8 | 8 | * Fernando Perez |
|
9 | 9 | * Brian Granger |
|
10 | 10 | * Robert Kern |
|
11 | 11 | """ |
|
12 | 12 | |
|
13 | 13 | #----------------------------------------------------------------------------- |
|
14 | 14 | # Copyright (C) 2008-2010 The IPython Development Team |
|
15 | 15 | # Copyright (C) 2001-2007 Fernando Perez <fperez@colorado.edu> |
|
16 | 16 | # |
|
17 | 17 | # Distributed under the terms of the BSD License. The full license is in |
|
18 | 18 | # the file COPYING, distributed as part of this software. |
|
19 | 19 | #----------------------------------------------------------------------------- |
|
20 | 20 | |
|
21 | 21 | #----------------------------------------------------------------------------- |
|
22 | 22 | # Imports |
|
23 | 23 | #----------------------------------------------------------------------------- |
|
24 | 24 | |
|
25 | 25 | import __builtin__ |
|
26 | 26 | |
|
27 | 27 | from IPython.config.configurable import Configurable |
|
28 | 28 | from IPython.core import prompts |
|
29 | 29 | import IPython.utils.generics |
|
30 | 30 | import IPython.utils.io |
|
31 | 31 | from IPython.utils.traitlets import Instance, List |
|
32 | 32 | from IPython.utils.warn import warn |
|
33 | 33 | |
|
34 | 34 | #----------------------------------------------------------------------------- |
|
35 | 35 | # Main displayhook class |
|
36 | 36 | #----------------------------------------------------------------------------- |
|
37 | 37 | |
|
38 | 38 | # TODO: The DisplayHook class should be split into two classes, one that |
|
39 | 39 | # manages the prompts and their synchronization and another that just does the |
|
40 | 40 | # displayhook logic and calls into the prompt manager. |
|
41 | 41 | |
|
42 | 42 | # TODO: Move the various attributes (cache_size, colors, input_sep, |
|
43 | 43 | # output_sep, output_sep2, ps1, ps2, ps_out, pad_left). Some of these are also |
|
44 | 44 | # attributes of InteractiveShell. They should be on ONE object only and the |
|
45 | 45 | # other objects should ask that one object for their values. |
|
46 | 46 | |
|
47 | 47 | class DisplayHook(Configurable): |
|
48 | 48 | """The custom IPython displayhook to replace sys.displayhook. |
|
49 | 49 | |
|
50 | 50 | This class does many things, but the basic idea is that it is a callable |
|
51 | 51 | that gets called anytime user code returns a value. |
|
52 | 52 | |
|
53 | 53 | Currently this class does more than just the displayhook logic and that |
|
54 | 54 | extra logic should eventually be moved out of here. |
|
55 | 55 | """ |
|
56 | 56 | |
|
57 | 57 | shell = Instance('IPython.core.interactiveshell.InteractiveShellABC') |
|
58 | 58 | |
|
59 | 59 | def __init__(self, shell=None, cache_size=1000, |
|
60 | 60 | colors='NoColor', input_sep='\n', |
|
61 | 61 | output_sep='\n', output_sep2='', |
|
62 | 62 | ps1 = None, ps2 = None, ps_out = None, pad_left=True, |
|
63 | 63 | config=None): |
|
64 | 64 | super(DisplayHook, self).__init__(shell=shell, config=config) |
|
65 | 65 | |
|
66 | 66 | cache_size_min = 3 |
|
67 | 67 | if cache_size <= 0: |
|
68 | 68 | self.do_full_cache = 0 |
|
69 | 69 | cache_size = 0 |
|
70 | 70 | elif cache_size < cache_size_min: |
|
71 | 71 | self.do_full_cache = 0 |
|
72 | 72 | cache_size = 0 |
|
73 | 73 | warn('caching was disabled (min value for cache size is %s).' % |
|
74 | 74 | cache_size_min,level=3) |
|
75 | 75 | else: |
|
76 | 76 | self.do_full_cache = 1 |
|
77 | 77 | |
|
78 | 78 | self.cache_size = cache_size |
|
79 | 79 | self.input_sep = input_sep |
|
80 | 80 | |
|
81 | 81 | # we need a reference to the user-level namespace |
|
82 | 82 | self.shell = shell |
|
83 | 83 | |
|
84 | 84 | # Set input prompt strings and colors |
|
85 | 85 | if cache_size == 0: |
|
86 | 86 | if ps1.find('%n') > -1 or ps1.find(r'\#') > -1 \ |
|
87 | 87 | or ps1.find(r'\N') > -1: |
|
88 | 88 | ps1 = '>>> ' |
|
89 | 89 | if ps2.find('%n') > -1 or ps2.find(r'\#') > -1 \ |
|
90 | 90 | or ps2.find(r'\N') > -1: |
|
91 | 91 | ps2 = '... ' |
|
92 | 92 | self.ps1_str = self._set_prompt_str(ps1,'In [\\#]: ','>>> ') |
|
93 | 93 | self.ps2_str = self._set_prompt_str(ps2,' .\\D.: ','... ') |
|
94 | 94 | self.ps_out_str = self._set_prompt_str(ps_out,'Out[\\#]: ','') |
|
95 | 95 | |
|
96 | 96 | self.color_table = prompts.PromptColors |
|
97 | 97 | self.prompt1 = prompts.Prompt1(self,sep=input_sep,prompt=self.ps1_str, |
|
98 | 98 | pad_left=pad_left) |
|
99 | 99 | self.prompt2 = prompts.Prompt2(self,prompt=self.ps2_str,pad_left=pad_left) |
|
100 | 100 | self.prompt_out = prompts.PromptOut(self,sep='',prompt=self.ps_out_str, |
|
101 | 101 | pad_left=pad_left) |
|
102 | 102 | self.set_colors(colors) |
|
103 | 103 | |
|
104 | 104 | # Store the last prompt string each time, we need it for aligning |
|
105 | 105 | # continuation and auto-rewrite prompts |
|
106 | 106 | self.last_prompt = '' |
|
107 | 107 | self.output_sep = output_sep |
|
108 | 108 | self.output_sep2 = output_sep2 |
|
109 | 109 | self._,self.__,self.___ = '','','' |
|
110 | 110 | |
|
111 | 111 | # these are deliberately global: |
|
112 | 112 | to_user_ns = {'_':self._,'__':self.__,'___':self.___} |
|
113 | 113 | self.shell.user_ns.update(to_user_ns) |
|
114 | 114 | |
|
115 | 115 | @property |
|
116 | 116 | def prompt_count(self): |
|
117 | 117 | return self.shell.execution_count |
|
118 | 118 | |
|
119 | 119 | def _set_prompt_str(self,p_str,cache_def,no_cache_def): |
|
120 | 120 | if p_str is None: |
|
121 | 121 | if self.do_full_cache: |
|
122 | 122 | return cache_def |
|
123 | 123 | else: |
|
124 | 124 | return no_cache_def |
|
125 | 125 | else: |
|
126 | 126 | return p_str |
|
127 | 127 | |
|
128 | 128 | def set_colors(self, colors): |
|
129 | 129 | """Set the active color scheme and configure colors for the three |
|
130 | 130 | prompt subsystems.""" |
|
131 | 131 | |
|
132 | 132 | # FIXME: This modifying of the global prompts.prompt_specials needs |
|
133 | 133 | # to be fixed. We need to refactor all of the prompts stuff to use |
|
134 | 134 | # proper configuration and traits notifications. |
|
135 | 135 | if colors.lower()=='nocolor': |
|
136 | 136 | prompts.prompt_specials = prompts.prompt_specials_nocolor |
|
137 | 137 | else: |
|
138 | 138 | prompts.prompt_specials = prompts.prompt_specials_color |
|
139 | 139 | |
|
140 | 140 | self.color_table.set_active_scheme(colors) |
|
141 | 141 | self.prompt1.set_colors() |
|
142 | 142 | self.prompt2.set_colors() |
|
143 | 143 | self.prompt_out.set_colors() |
|
144 | 144 | |
|
145 | 145 | #------------------------------------------------------------------------- |
|
146 | 146 | # Methods used in __call__. Override these methods to modify the behavior |
|
147 | 147 | # of the displayhook. |
|
148 | 148 | #------------------------------------------------------------------------- |
|
149 | 149 | |
|
150 | 150 | def check_for_underscore(self): |
|
151 | 151 | """Check if the user has set the '_' variable by hand.""" |
|
152 | 152 | # If something injected a '_' variable in __builtin__, delete |
|
153 | 153 | # ipython's automatic one so we don't clobber that. gettext() in |
|
154 | 154 | # particular uses _, so we need to stay away from it. |
|
155 | 155 | if '_' in __builtin__.__dict__: |
|
156 | 156 | try: |
|
157 | 157 | del self.shell.user_ns['_'] |
|
158 | 158 | except KeyError: |
|
159 | 159 | pass |
|
160 | 160 | |
|
161 | 161 | def quiet(self): |
|
162 | 162 | """Should we silence the display hook because of ';'?""" |
|
163 | 163 | # do not print output if input ends in ';' |
|
164 | 164 | try: |
|
165 | 165 | if self.shell.history_manager.input_hist_parsed[self.prompt_count].endswith(';\n'): |
|
166 | 166 | return True |
|
167 | 167 | except IndexError: |
|
168 | 168 | # some uses of ipshellembed may fail here |
|
169 | 169 | pass |
|
170 | 170 | return False |
|
171 | 171 | |
|
172 | 172 | def start_displayhook(self): |
|
173 | 173 | """Start the displayhook, initializing resources.""" |
|
174 | 174 | pass |
|
175 | 175 | |
|
176 | 176 | def write_output_prompt(self): |
|
177 | 177 | """Write the output prompt. |
|
178 | 178 | |
|
179 | 179 | The default implementation simply writes the prompt to |
|
180 | 180 | ``io.Term.cout``. |
|
181 | 181 | """ |
|
182 | 182 | # Use write, not print which adds an extra space. |
|
183 | 183 | IPython.utils.io.Term.cout.write(self.output_sep) |
|
184 | 184 | outprompt = str(self.prompt_out) |
|
185 | 185 | if self.do_full_cache: |
|
186 | 186 | IPython.utils.io.Term.cout.write(outprompt) |
|
187 | 187 | |
|
188 | 188 | def compute_format_data(self, result): |
|
189 | 189 | """Compute format data of the object to be displayed. |
|
190 | 190 | |
|
191 | 191 | The format data is a generalization of the :func:`repr` of an object. |
|
192 | 192 | In the default implementation the format data is a :class:`dict` of |
|
193 | 193 | key value pair where the keys are valid MIME types and the values |
|
194 | 194 | are JSON'able data structure containing the raw data for that MIME |
|
195 | 195 | type. It is up to frontends to determine pick a MIME to to use and |
|
196 | 196 | display that data in an appropriate manner. |
|
197 | 197 | |
|
198 | 198 | This method only computes the format data for the object and should |
|
199 | 199 | NOT actually print or write that to a stream. |
|
200 | 200 | |
|
201 | 201 | Parameters |
|
202 | 202 | ---------- |
|
203 | 203 | result : object |
|
204 | 204 | The Python object passed to the display hook, whose format will be |
|
205 | 205 | computed. |
|
206 | 206 | |
|
207 | 207 | Returns |
|
208 | 208 | ------- |
|
209 | 209 | format_data : dict |
|
210 | 210 | A :class:`dict` whose keys are valid MIME types and values are |
|
211 | 211 | JSON'able raw data for that MIME type. It is recommended that |
|
212 | 212 | all return values of this should always include the "text/plain" |
|
213 | 213 | MIME type representation of the object. |
|
214 | 214 | """ |
|
215 | 215 | return self.shell.display_formatter.format(result) |
|
216 | 216 | |
|
217 | 217 | def write_format_data(self, format_dict): |
|
218 | 218 | """Write the format data dict to the frontend. |
|
219 | 219 | |
|
220 | 220 | This default version of this method simply writes the plain text |
|
221 | 221 | representation of the object to ``io.Term.cout``. Subclasses should |
|
222 | 222 | override this method to send the entire `format_dict` to the |
|
223 | 223 | frontends. |
|
224 | 224 | |
|
225 | 225 | Parameters |
|
226 | 226 | ---------- |
|
227 | 227 | format_dict : dict |
|
228 | 228 | The format dict for the object passed to `sys.displayhook`. |
|
229 | 229 | """ |
|
230 | 230 | # We want to print because we want to always make sure we have a |
|
231 | 231 | # newline, even if all the prompt separators are ''. This is the |
|
232 | 232 | # standard IPython behavior. |
|
233 | 233 | result_repr = format_dict['text/plain'] |
|
234 | 234 | if '\n' in result_repr: |
|
235 | 235 | # So that multi-line strings line up with the left column of |
|
236 | 236 | # the screen, instead of having the output prompt mess up |
|
237 | 237 | # their first line. |
|
238 | 238 | # We use the ps_out_str template instead of the expanded prompt |
|
239 | 239 | # because the expansion may add ANSI escapes that will interfere |
|
240 | 240 | # with our ability to determine whether or not we should add |
|
241 | 241 | # a newline. |
|
242 | 242 | if self.ps_out_str and not self.ps_out_str.endswith('\n'): |
|
243 | 243 | # But avoid extraneous empty lines. |
|
244 | 244 | result_repr = '\n' + result_repr |
|
245 | 245 | |
|
246 | 246 | print >>IPython.utils.io.Term.cout, result_repr |
|
247 | 247 | |
|
248 | 248 | def update_user_ns(self, result): |
|
249 | 249 | """Update user_ns with various things like _, __, _1, etc.""" |
|
250 | 250 | |
|
251 | 251 | # Avoid recursive reference when displaying _oh/Out |
|
252 | 252 | if result is not self.shell.user_ns['_oh']: |
|
253 | 253 | if len(self.shell.user_ns['_oh']) >= self.cache_size and self.do_full_cache: |
|
254 | 254 | warn('Output cache limit (currently '+ |
|
255 | 255 | `self.cache_size`+' entries) hit.\n' |
|
256 | 256 | 'Flushing cache and resetting history counter...\n' |
|
257 | 257 | 'The only history variables available will be _,__,___ and _1\n' |
|
258 | 258 | 'with the current result.') |
|
259 | 259 | |
|
260 | 260 | self.flush() |
|
261 | 261 | # Don't overwrite '_' and friends if '_' is in __builtin__ (otherwise |
|
262 | 262 | # we cause buggy behavior for things like gettext). |
|
263 | 263 | |
|
264 | 264 | if '_' not in __builtin__.__dict__: |
|
265 | 265 | self.___ = self.__ |
|
266 | 266 | self.__ = self._ |
|
267 | 267 | self._ = result |
|
268 | 268 | self.shell.user_ns.update({'_':self._, |
|
269 | 269 | '__':self.__, |
|
270 | 270 | '___':self.___}) |
|
271 | 271 | |
|
272 | 272 | # hackish access to top-level namespace to create _1,_2... dynamically |
|
273 | 273 | to_main = {} |
|
274 | 274 | if self.do_full_cache: |
|
275 | 275 | new_result = '_'+`self.prompt_count` |
|
276 | 276 | to_main[new_result] = result |
|
277 | 277 | self.shell.user_ns.update(to_main) |
|
278 | 278 | self.shell.user_ns['_oh'][self.prompt_count] = result |
|
279 | 279 | |
|
280 | 280 | def log_output(self, format_dict): |
|
281 | 281 | """Log the output.""" |
|
282 | 282 | if self.shell.logger.log_output: |
|
283 | 283 | self.shell.logger.log_write(format_dict['text/plain'], 'output') |
|
284 | 284 | # This is a defaultdict of lists, so we can always append |
|
285 | 285 | self.shell.history_manager.output_hist_reprs[self.prompt_count]\ |
|
286 | 286 | .append(format_dict['text/plain']) |
|
287 | 287 | |
|
288 | 288 | def finish_displayhook(self): |
|
289 | 289 | """Finish up all displayhook activities.""" |
|
290 | 290 | IPython.utils.io.Term.cout.write(self.output_sep2) |
|
291 | 291 | IPython.utils.io.Term.cout.flush() |
|
292 | 292 | |
|
293 | 293 | def __call__(self, result=None): |
|
294 | 294 | """Printing with history cache management. |
|
295 | 295 | |
|
296 | 296 | This is invoked everytime the interpreter needs to print, and is |
|
297 | 297 | activated by setting the variable sys.displayhook to it. |
|
298 | 298 | """ |
|
299 | 299 | self.check_for_underscore() |
|
300 | 300 | if result is not None and not self.quiet(): |
|
301 | 301 | self.start_displayhook() |
|
302 | 302 | self.write_output_prompt() |
|
303 | 303 | format_dict = self.compute_format_data(result) |
|
304 | 304 | self.write_format_data(format_dict) |
|
305 | 305 | self.update_user_ns(result) |
|
306 | 306 | self.log_output(format_dict) |
|
307 | 307 | self.finish_displayhook() |
|
308 | 308 | |
|
309 | 309 | def flush(self): |
|
310 | 310 | if not self.do_full_cache: |
|
311 | 311 | raise ValueError,"You shouldn't have reached the cache flush "\ |
|
312 | 312 | "if full caching is not enabled!" |
|
313 | 313 | # delete auto-generated vars from global namespace |
|
314 | 314 | |
|
315 | 315 | for n in range(1,self.prompt_count + 1): |
|
316 | 316 | key = '_'+`n` |
|
317 | 317 | try: |
|
318 | 318 | del self.shell.user_ns[key] |
|
319 | 319 | except: pass |
|
320 | 320 | self.shell.user_ns['_oh'].clear() |
|
321 | 321 | |
|
322 | # Release our own references to objects: | |
|
323 | self._, self.__, self.___ = '', '', '' | |
|
324 | ||
|
322 | 325 | if '_' not in __builtin__.__dict__: |
|
323 | 326 | self.shell.user_ns.update({'_':None,'__':None, '___':None}) |
|
324 | 327 | import gc |
|
325 | 328 | # TODO: Is this really needed? |
|
326 | 329 | gc.collect() |
|
327 | 330 |
@@ -1,2595 +1,2602 b'' | |||
|
1 | 1 | # -*- coding: utf-8 -*- |
|
2 | 2 | """Main IPython class.""" |
|
3 | 3 | |
|
4 | 4 | #----------------------------------------------------------------------------- |
|
5 | 5 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> |
|
6 | 6 | # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu> |
|
7 | 7 | # Copyright (C) 2008-2011 The IPython Development Team |
|
8 | 8 | # |
|
9 | 9 | # Distributed under the terms of the BSD License. The full license is in |
|
10 | 10 | # the file COPYING, distributed as part of this software. |
|
11 | 11 | #----------------------------------------------------------------------------- |
|
12 | 12 | |
|
13 | 13 | #----------------------------------------------------------------------------- |
|
14 | 14 | # Imports |
|
15 | 15 | #----------------------------------------------------------------------------- |
|
16 | 16 | |
|
17 | 17 | from __future__ import with_statement |
|
18 | 18 | from __future__ import absolute_import |
|
19 | 19 | |
|
20 | 20 | import __builtin__ |
|
21 | 21 | import __future__ |
|
22 | 22 | import abc |
|
23 | 23 | import ast |
|
24 | 24 | import atexit |
|
25 | 25 | import codeop |
|
26 | 26 | import inspect |
|
27 | 27 | import os |
|
28 | 28 | import re |
|
29 | 29 | import sys |
|
30 | 30 | import tempfile |
|
31 | 31 | import types |
|
32 | 32 | from contextlib import nested |
|
33 | 33 | |
|
34 | 34 | from IPython.config.configurable import Configurable |
|
35 | 35 | from IPython.core import debugger, oinspect |
|
36 | 36 | from IPython.core import history as ipcorehist |
|
37 | 37 | from IPython.core import page |
|
38 | 38 | from IPython.core import prefilter |
|
39 | 39 | from IPython.core import shadowns |
|
40 | 40 | from IPython.core import ultratb |
|
41 | 41 | from IPython.core.alias import AliasManager |
|
42 | 42 | from IPython.core.builtin_trap import BuiltinTrap |
|
43 | 43 | from IPython.core.compilerop import CachingCompiler |
|
44 | 44 | from IPython.core.display_trap import DisplayTrap |
|
45 | 45 | from IPython.core.displayhook import DisplayHook |
|
46 | 46 | from IPython.core.displaypub import DisplayPublisher |
|
47 | 47 | from IPython.core.error import TryNext, UsageError |
|
48 | 48 | from IPython.core.extensions import ExtensionManager |
|
49 | 49 | from IPython.core.fakemodule import FakeModule, init_fakemod_dict |
|
50 | 50 | from IPython.core.formatters import DisplayFormatter |
|
51 | 51 | from IPython.core.history import HistoryManager |
|
52 | 52 | from IPython.core.inputsplitter import IPythonInputSplitter |
|
53 | 53 | from IPython.core.logger import Logger |
|
54 | 54 | from IPython.core.macro import Macro |
|
55 | 55 | from IPython.core.magic import Magic |
|
56 | 56 | from IPython.core.payload import PayloadManager |
|
57 | 57 | from IPython.core.plugin import PluginManager |
|
58 | 58 | from IPython.core.prefilter import PrefilterManager, ESC_MAGIC |
|
59 | 59 | from IPython.external.Itpl import ItplNS |
|
60 | 60 | from IPython.utils import PyColorize |
|
61 | 61 | from IPython.utils import io |
|
62 | 62 | from IPython.utils.doctestreload import doctest_reload |
|
63 | 63 | from IPython.utils.io import ask_yes_no, rprint |
|
64 | 64 | from IPython.utils.ipstruct import Struct |
|
65 | 65 | from IPython.utils.path import get_home_dir, get_ipython_dir, HomeDirError |
|
66 | 66 | from IPython.utils.pickleshare import PickleShareDB |
|
67 | 67 | from IPython.utils.process import system, getoutput |
|
68 | 68 | from IPython.utils.strdispatch import StrDispatch |
|
69 | 69 | from IPython.utils.syspathcontext import prepended_to_syspath |
|
70 | 70 | from IPython.utils.text import num_ini_spaces, format_screen, LSString, SList |
|
71 | 71 | from IPython.utils.traitlets import (Int, Str, CBool, CaselessStrEnum, Enum, |
|
72 | 72 | List, Unicode, Instance, Type) |
|
73 | 73 | from IPython.utils.warn import warn, error, fatal |
|
74 | 74 | import IPython.core.hooks |
|
75 | 75 | |
|
76 | 76 | #----------------------------------------------------------------------------- |
|
77 | 77 | # Globals |
|
78 | 78 | #----------------------------------------------------------------------------- |
|
79 | 79 | |
|
80 | 80 | # compiled regexps for autoindent management |
|
81 | 81 | dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass') |
|
82 | 82 | |
|
83 | 83 | #----------------------------------------------------------------------------- |
|
84 | 84 | # Utilities |
|
85 | 85 | #----------------------------------------------------------------------------- |
|
86 | 86 | |
|
87 | 87 | # store the builtin raw_input globally, and use this always, in case user code |
|
88 | 88 | # overwrites it (like wx.py.PyShell does) |
|
89 | 89 | raw_input_original = raw_input |
|
90 | 90 | |
|
91 | 91 | def softspace(file, newvalue): |
|
92 | 92 | """Copied from code.py, to remove the dependency""" |
|
93 | 93 | |
|
94 | 94 | oldvalue = 0 |
|
95 | 95 | try: |
|
96 | 96 | oldvalue = file.softspace |
|
97 | 97 | except AttributeError: |
|
98 | 98 | pass |
|
99 | 99 | try: |
|
100 | 100 | file.softspace = newvalue |
|
101 | 101 | except (AttributeError, TypeError): |
|
102 | 102 | # "attribute-less object" or "read-only attributes" |
|
103 | 103 | pass |
|
104 | 104 | return oldvalue |
|
105 | 105 | |
|
106 | 106 | |
|
107 | 107 | def no_op(*a, **kw): pass |
|
108 | 108 | |
|
109 | 109 | class SpaceInInput(Exception): pass |
|
110 | 110 | |
|
111 | 111 | class Bunch: pass |
|
112 | 112 | |
|
113 | 113 | |
|
114 | 114 | def get_default_colors(): |
|
115 | 115 | if sys.platform=='darwin': |
|
116 | 116 | return "LightBG" |
|
117 | 117 | elif os.name=='nt': |
|
118 | 118 | return 'Linux' |
|
119 | 119 | else: |
|
120 | 120 | return 'Linux' |
|
121 | 121 | |
|
122 | 122 | |
|
123 | 123 | class SeparateStr(Str): |
|
124 | 124 | """A Str subclass to validate separate_in, separate_out, etc. |
|
125 | 125 | |
|
126 | 126 | This is a Str based trait that converts '0'->'' and '\\n'->'\n'. |
|
127 | 127 | """ |
|
128 | 128 | |
|
129 | 129 | def validate(self, obj, value): |
|
130 | 130 | if value == '0': value = '' |
|
131 | 131 | value = value.replace('\\n','\n') |
|
132 | 132 | return super(SeparateStr, self).validate(obj, value) |
|
133 | 133 | |
|
134 | 134 | class MultipleInstanceError(Exception): |
|
135 | 135 | pass |
|
136 | 136 | |
|
137 | 137 | class ReadlineNoRecord(object): |
|
138 | 138 | """Context manager to execute some code, then reload readline history |
|
139 | 139 | so that interactive input to the code doesn't appear when pressing up.""" |
|
140 | 140 | def __init__(self, shell): |
|
141 | 141 | self.shell = shell |
|
142 | 142 | self._nested_level = 0 |
|
143 | 143 | |
|
144 | 144 | def __enter__(self): |
|
145 | 145 | if self._nested_level == 0: |
|
146 | 146 | self.orig_length = self.current_length() |
|
147 | 147 | self.readline_tail = self.get_readline_tail() |
|
148 | 148 | self._nested_level += 1 |
|
149 | 149 | |
|
150 | 150 | def __exit__(self, type, value, traceback): |
|
151 | 151 | self._nested_level -= 1 |
|
152 | 152 | if self._nested_level == 0: |
|
153 | 153 | # Try clipping the end if it's got longer |
|
154 | 154 | e = self.current_length() - self.orig_length |
|
155 | 155 | if e > 0: |
|
156 | 156 | for _ in range(e): |
|
157 | 157 | self.shell.readline.remove_history_item(self.orig_length) |
|
158 | 158 | |
|
159 | 159 | # If it still doesn't match, just reload readline history. |
|
160 | 160 | if self.current_length() != self.orig_length \ |
|
161 | 161 | or self.get_readline_tail() != self.readline_tail: |
|
162 | 162 | self.shell.refill_readline_hist() |
|
163 | 163 | # Returning False will cause exceptions to propagate |
|
164 | 164 | return False |
|
165 | 165 | |
|
166 | 166 | def current_length(self): |
|
167 | 167 | return self.shell.readline.get_current_history_length() |
|
168 | 168 | |
|
169 | 169 | def get_readline_tail(self, n=10): |
|
170 | 170 | """Get the last n items in readline history.""" |
|
171 | 171 | end = self.shell.readline.get_current_history_length() + 1 |
|
172 | 172 | start = max(end-n, 1) |
|
173 | 173 | ghi = self.shell.readline.get_history_item |
|
174 | 174 | return [ghi(x) for x in range(start, end)] |
|
175 | 175 | |
|
176 | 176 | |
|
177 | 177 | #----------------------------------------------------------------------------- |
|
178 | 178 | # Main IPython class |
|
179 | 179 | #----------------------------------------------------------------------------- |
|
180 | 180 | |
|
181 | 181 | class InteractiveShell(Configurable, Magic): |
|
182 | 182 | """An enhanced, interactive shell for Python.""" |
|
183 | 183 | |
|
184 | 184 | _instance = None |
|
185 | 185 | autocall = Enum((0,1,2), default_value=1, config=True) |
|
186 | 186 | # TODO: remove all autoindent logic and put into frontends. |
|
187 | 187 | # We can't do this yet because even runlines uses the autoindent. |
|
188 | 188 | autoindent = CBool(True, config=True) |
|
189 | 189 | automagic = CBool(True, config=True) |
|
190 | 190 | cache_size = Int(1000, config=True) |
|
191 | 191 | color_info = CBool(True, config=True) |
|
192 | 192 | colors = CaselessStrEnum(('NoColor','LightBG','Linux'), |
|
193 | 193 | default_value=get_default_colors(), config=True) |
|
194 | 194 | debug = CBool(False, config=True) |
|
195 | 195 | deep_reload = CBool(False, config=True) |
|
196 | 196 | display_formatter = Instance(DisplayFormatter) |
|
197 | 197 | displayhook_class = Type(DisplayHook) |
|
198 | 198 | display_pub_class = Type(DisplayPublisher) |
|
199 | 199 | |
|
200 | 200 | exit_now = CBool(False) |
|
201 | 201 | # Monotonically increasing execution counter |
|
202 | 202 | execution_count = Int(1) |
|
203 | 203 | filename = Unicode("<ipython console>") |
|
204 | 204 | ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__ |
|
205 | 205 | |
|
206 | 206 | # Input splitter, to split entire cells of input into either individual |
|
207 | 207 | # interactive statements or whole blocks. |
|
208 | 208 | input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter', |
|
209 | 209 | (), {}) |
|
210 | 210 | logstart = CBool(False, config=True) |
|
211 | 211 | logfile = Unicode('', config=True) |
|
212 | 212 | logappend = Unicode('', config=True) |
|
213 | 213 | object_info_string_level = Enum((0,1,2), default_value=0, |
|
214 | 214 | config=True) |
|
215 | 215 | pdb = CBool(False, config=True) |
|
216 | 216 | |
|
217 | 217 | profile = Unicode('', config=True) |
|
218 | 218 | prompt_in1 = Str('In [\\#]: ', config=True) |
|
219 | 219 | prompt_in2 = Str(' .\\D.: ', config=True) |
|
220 | 220 | prompt_out = Str('Out[\\#]: ', config=True) |
|
221 | 221 | prompts_pad_left = CBool(True, config=True) |
|
222 | 222 | quiet = CBool(False, config=True) |
|
223 | 223 | |
|
224 | 224 | history_length = Int(10000, config=True) |
|
225 | 225 | |
|
226 | 226 | # The readline stuff will eventually be moved to the terminal subclass |
|
227 | 227 | # but for now, we can't do that as readline is welded in everywhere. |
|
228 | 228 | readline_use = CBool(True, config=True) |
|
229 | 229 | readline_merge_completions = CBool(True, config=True) |
|
230 | 230 | readline_omit__names = Enum((0,1,2), default_value=2, config=True) |
|
231 | 231 | readline_remove_delims = Str('-/~', config=True) |
|
232 | 232 | readline_parse_and_bind = List([ |
|
233 | 233 | 'tab: complete', |
|
234 | 234 | '"\C-l": clear-screen', |
|
235 | 235 | 'set show-all-if-ambiguous on', |
|
236 | 236 | '"\C-o": tab-insert', |
|
237 | 237 | # See bug gh-58 - with \M-i enabled, chars 0x9000-0x9fff |
|
238 | 238 | # crash IPython. |
|
239 | 239 | '"\M-o": "\d\d\d\d"', |
|
240 | 240 | '"\M-I": "\d\d\d\d"', |
|
241 | 241 | '"\C-r": reverse-search-history', |
|
242 | 242 | '"\C-s": forward-search-history', |
|
243 | 243 | '"\C-p": history-search-backward', |
|
244 | 244 | '"\C-n": history-search-forward', |
|
245 | 245 | '"\e[A": history-search-backward', |
|
246 | 246 | '"\e[B": history-search-forward', |
|
247 | 247 | '"\C-k": kill-line', |
|
248 | 248 | '"\C-u": unix-line-discard', |
|
249 | 249 | ], allow_none=False, config=True) |
|
250 | 250 | |
|
251 | 251 | # TODO: this part of prompt management should be moved to the frontends. |
|
252 | 252 | # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n' |
|
253 | 253 | separate_in = SeparateStr('\n', config=True) |
|
254 | 254 | separate_out = SeparateStr('', config=True) |
|
255 | 255 | separate_out2 = SeparateStr('', config=True) |
|
256 | 256 | wildcards_case_sensitive = CBool(True, config=True) |
|
257 | 257 | xmode = CaselessStrEnum(('Context','Plain', 'Verbose'), |
|
258 | 258 | default_value='Context', config=True) |
|
259 | 259 | |
|
260 | 260 | # Subcomponents of InteractiveShell |
|
261 | 261 | alias_manager = Instance('IPython.core.alias.AliasManager') |
|
262 | 262 | prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager') |
|
263 | 263 | builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap') |
|
264 | 264 | display_trap = Instance('IPython.core.display_trap.DisplayTrap') |
|
265 | 265 | extension_manager = Instance('IPython.core.extensions.ExtensionManager') |
|
266 | 266 | plugin_manager = Instance('IPython.core.plugin.PluginManager') |
|
267 | 267 | payload_manager = Instance('IPython.core.payload.PayloadManager') |
|
268 | 268 | history_manager = Instance('IPython.core.history.HistoryManager') |
|
269 | 269 | |
|
270 | 270 | # Private interface |
|
271 | 271 | _post_execute = set() |
|
272 | 272 | |
|
273 | 273 | def __init__(self, config=None, ipython_dir=None, |
|
274 | 274 | user_ns=None, user_global_ns=None, |
|
275 | 275 | custom_exceptions=((), None)): |
|
276 | 276 | |
|
277 | 277 | # This is where traits with a config_key argument are updated |
|
278 | 278 | # from the values on config. |
|
279 | 279 | super(InteractiveShell, self).__init__(config=config) |
|
280 | 280 | |
|
281 | 281 | # These are relatively independent and stateless |
|
282 | 282 | self.init_ipython_dir(ipython_dir) |
|
283 | 283 | self.init_instance_attrs() |
|
284 | 284 | self.init_environment() |
|
285 | 285 | |
|
286 | 286 | # Create namespaces (user_ns, user_global_ns, etc.) |
|
287 | 287 | self.init_create_namespaces(user_ns, user_global_ns) |
|
288 | 288 | # This has to be done after init_create_namespaces because it uses |
|
289 | 289 | # something in self.user_ns, but before init_sys_modules, which |
|
290 | 290 | # is the first thing to modify sys. |
|
291 | 291 | # TODO: When we override sys.stdout and sys.stderr before this class |
|
292 | 292 | # is created, we are saving the overridden ones here. Not sure if this |
|
293 | 293 | # is what we want to do. |
|
294 | 294 | self.save_sys_module_state() |
|
295 | 295 | self.init_sys_modules() |
|
296 | 296 | |
|
297 | 297 | # While we're trying to have each part of the code directly access what |
|
298 | 298 | # it needs without keeping redundant references to objects, we have too |
|
299 | 299 | # much legacy code that expects ip.db to exist. |
|
300 | 300 | self.db = PickleShareDB(os.path.join(self.ipython_dir, 'db')) |
|
301 | 301 | |
|
302 | 302 | self.init_history() |
|
303 | 303 | self.init_encoding() |
|
304 | 304 | self.init_prefilter() |
|
305 | 305 | |
|
306 | 306 | Magic.__init__(self, self) |
|
307 | 307 | |
|
308 | 308 | self.init_syntax_highlighting() |
|
309 | 309 | self.init_hooks() |
|
310 | 310 | self.init_pushd_popd_magic() |
|
311 | 311 | # self.init_traceback_handlers use to be here, but we moved it below |
|
312 | 312 | # because it and init_io have to come after init_readline. |
|
313 | 313 | self.init_user_ns() |
|
314 | 314 | self.init_logger() |
|
315 | 315 | self.init_alias() |
|
316 | 316 | self.init_builtins() |
|
317 | 317 | |
|
318 | 318 | # pre_config_initialization |
|
319 | 319 | |
|
320 | 320 | # The next section should contain everything that was in ipmaker. |
|
321 | 321 | self.init_logstart() |
|
322 | 322 | |
|
323 | 323 | # The following was in post_config_initialization |
|
324 | 324 | self.init_inspector() |
|
325 | 325 | # init_readline() must come before init_io(), because init_io uses |
|
326 | 326 | # readline related things. |
|
327 | 327 | self.init_readline() |
|
328 | 328 | # init_completer must come after init_readline, because it needs to |
|
329 | 329 | # know whether readline is present or not system-wide to configure the |
|
330 | 330 | # completers, since the completion machinery can now operate |
|
331 | 331 | # independently of readline (e.g. over the network) |
|
332 | 332 | self.init_completer() |
|
333 | 333 | # TODO: init_io() needs to happen before init_traceback handlers |
|
334 | 334 | # because the traceback handlers hardcode the stdout/stderr streams. |
|
335 | 335 | # This logic in in debugger.Pdb and should eventually be changed. |
|
336 | 336 | self.init_io() |
|
337 | 337 | self.init_traceback_handlers(custom_exceptions) |
|
338 | 338 | self.init_prompts() |
|
339 | 339 | self.init_display_formatter() |
|
340 | 340 | self.init_display_pub() |
|
341 | 341 | self.init_displayhook() |
|
342 | 342 | self.init_reload_doctest() |
|
343 | 343 | self.init_magics() |
|
344 | 344 | self.init_pdb() |
|
345 | 345 | self.init_extension_manager() |
|
346 | 346 | self.init_plugin_manager() |
|
347 | 347 | self.init_payload() |
|
348 | 348 | self.hooks.late_startup_hook() |
|
349 | 349 | atexit.register(self.atexit_operations) |
|
350 | 350 | |
|
351 | 351 | @classmethod |
|
352 | 352 | def instance(cls, *args, **kwargs): |
|
353 | 353 | """Returns a global InteractiveShell instance.""" |
|
354 | 354 | if cls._instance is None: |
|
355 | 355 | inst = cls(*args, **kwargs) |
|
356 | 356 | # Now make sure that the instance will also be returned by |
|
357 | 357 | # the subclasses instance attribute. |
|
358 | 358 | for subclass in cls.mro(): |
|
359 | 359 | if issubclass(cls, subclass) and \ |
|
360 | 360 | issubclass(subclass, InteractiveShell): |
|
361 | 361 | subclass._instance = inst |
|
362 | 362 | else: |
|
363 | 363 | break |
|
364 | 364 | if isinstance(cls._instance, cls): |
|
365 | 365 | return cls._instance |
|
366 | 366 | else: |
|
367 | 367 | raise MultipleInstanceError( |
|
368 | 368 | 'Multiple incompatible subclass instances of ' |
|
369 | 369 | 'InteractiveShell are being created.' |
|
370 | 370 | ) |
|
371 | 371 | |
|
372 | 372 | @classmethod |
|
373 | 373 | def initialized(cls): |
|
374 | 374 | return hasattr(cls, "_instance") |
|
375 | 375 | |
|
376 | 376 | def get_ipython(self): |
|
377 | 377 | """Return the currently running IPython instance.""" |
|
378 | 378 | return self |
|
379 | 379 | |
|
380 | 380 | #------------------------------------------------------------------------- |
|
381 | 381 | # Trait changed handlers |
|
382 | 382 | #------------------------------------------------------------------------- |
|
383 | 383 | |
|
384 | 384 | def _ipython_dir_changed(self, name, new): |
|
385 | 385 | if not os.path.isdir(new): |
|
386 | 386 | os.makedirs(new, mode = 0777) |
|
387 | 387 | |
|
388 | 388 | def set_autoindent(self,value=None): |
|
389 | 389 | """Set the autoindent flag, checking for readline support. |
|
390 | 390 | |
|
391 | 391 | If called with no arguments, it acts as a toggle.""" |
|
392 | 392 | |
|
393 | 393 | if not self.has_readline: |
|
394 | 394 | if os.name == 'posix': |
|
395 | 395 | warn("The auto-indent feature requires the readline library") |
|
396 | 396 | self.autoindent = 0 |
|
397 | 397 | return |
|
398 | 398 | if value is None: |
|
399 | 399 | self.autoindent = not self.autoindent |
|
400 | 400 | else: |
|
401 | 401 | self.autoindent = value |
|
402 | 402 | |
|
403 | 403 | #------------------------------------------------------------------------- |
|
404 | 404 | # init_* methods called by __init__ |
|
405 | 405 | #------------------------------------------------------------------------- |
|
406 | 406 | |
|
407 | 407 | def init_ipython_dir(self, ipython_dir): |
|
408 | 408 | if ipython_dir is not None: |
|
409 | 409 | self.ipython_dir = ipython_dir |
|
410 | 410 | self.config.Global.ipython_dir = self.ipython_dir |
|
411 | 411 | return |
|
412 | 412 | |
|
413 | 413 | if hasattr(self.config.Global, 'ipython_dir'): |
|
414 | 414 | self.ipython_dir = self.config.Global.ipython_dir |
|
415 | 415 | else: |
|
416 | 416 | self.ipython_dir = get_ipython_dir() |
|
417 | 417 | |
|
418 | 418 | # All children can just read this |
|
419 | 419 | self.config.Global.ipython_dir = self.ipython_dir |
|
420 | 420 | |
|
421 | 421 | def init_instance_attrs(self): |
|
422 | 422 | self.more = False |
|
423 | 423 | |
|
424 | 424 | # command compiler |
|
425 | 425 | self.compile = CachingCompiler() |
|
426 | 426 | |
|
427 | 427 | # User input buffers |
|
428 | 428 | # NOTE: these variables are slated for full removal, once we are 100% |
|
429 | 429 | # sure that the new execution logic is solid. We will delte runlines, |
|
430 | 430 | # push_line and these buffers, as all input will be managed by the |
|
431 | 431 | # frontends via an inputsplitter instance. |
|
432 | 432 | self.buffer = [] |
|
433 | 433 | self.buffer_raw = [] |
|
434 | 434 | |
|
435 | 435 | # Make an empty namespace, which extension writers can rely on both |
|
436 | 436 | # existing and NEVER being used by ipython itself. This gives them a |
|
437 | 437 | # convenient location for storing additional information and state |
|
438 | 438 | # their extensions may require, without fear of collisions with other |
|
439 | 439 | # ipython names that may develop later. |
|
440 | 440 | self.meta = Struct() |
|
441 | 441 | |
|
442 | 442 | # Object variable to store code object waiting execution. This is |
|
443 | 443 | # used mainly by the multithreaded shells, but it can come in handy in |
|
444 | 444 | # other situations. No need to use a Queue here, since it's a single |
|
445 | 445 | # item which gets cleared once run. |
|
446 | 446 | self.code_to_run = None |
|
447 | 447 | |
|
448 | 448 | # Temporary files used for various purposes. Deleted at exit. |
|
449 | 449 | self.tempfiles = [] |
|
450 | 450 | |
|
451 | 451 | # Keep track of readline usage (later set by init_readline) |
|
452 | 452 | self.has_readline = False |
|
453 | 453 | |
|
454 | 454 | # keep track of where we started running (mainly for crash post-mortem) |
|
455 | 455 | # This is not being used anywhere currently. |
|
456 | 456 | self.starting_dir = os.getcwd() |
|
457 | 457 | |
|
458 | 458 | # Indentation management |
|
459 | 459 | self.indent_current_nsp = 0 |
|
460 | 460 | |
|
461 | 461 | def init_environment(self): |
|
462 | 462 | """Any changes we need to make to the user's environment.""" |
|
463 | 463 | pass |
|
464 | 464 | |
|
465 | 465 | def init_encoding(self): |
|
466 | 466 | # Get system encoding at startup time. Certain terminals (like Emacs |
|
467 | 467 | # under Win32 have it set to None, and we need to have a known valid |
|
468 | 468 | # encoding to use in the raw_input() method |
|
469 | 469 | try: |
|
470 | 470 | self.stdin_encoding = sys.stdin.encoding or 'ascii' |
|
471 | 471 | except AttributeError: |
|
472 | 472 | self.stdin_encoding = 'ascii' |
|
473 | 473 | |
|
474 | 474 | def init_syntax_highlighting(self): |
|
475 | 475 | # Python source parser/formatter for syntax highlighting |
|
476 | 476 | pyformat = PyColorize.Parser().format |
|
477 | 477 | self.pycolorize = lambda src: pyformat(src,'str',self.colors) |
|
478 | 478 | |
|
479 | 479 | def init_pushd_popd_magic(self): |
|
480 | 480 | # for pushd/popd management |
|
481 | 481 | try: |
|
482 | 482 | self.home_dir = get_home_dir() |
|
483 | 483 | except HomeDirError, msg: |
|
484 | 484 | fatal(msg) |
|
485 | 485 | |
|
486 | 486 | self.dir_stack = [] |
|
487 | 487 | |
|
488 | 488 | def init_logger(self): |
|
489 | 489 | self.logger = Logger(self.home_dir, logfname='ipython_log.py', |
|
490 | 490 | logmode='rotate') |
|
491 | 491 | |
|
492 | 492 | def init_logstart(self): |
|
493 | 493 | """Initialize logging in case it was requested at the command line. |
|
494 | 494 | """ |
|
495 | 495 | if self.logappend: |
|
496 | 496 | self.magic_logstart(self.logappend + ' append') |
|
497 | 497 | elif self.logfile: |
|
498 | 498 | self.magic_logstart(self.logfile) |
|
499 | 499 | elif self.logstart: |
|
500 | 500 | self.magic_logstart() |
|
501 | 501 | |
|
502 | 502 | def init_builtins(self): |
|
503 | 503 | self.builtin_trap = BuiltinTrap(shell=self) |
|
504 | 504 | |
|
505 | 505 | def init_inspector(self): |
|
506 | 506 | # Object inspector |
|
507 | 507 | self.inspector = oinspect.Inspector(oinspect.InspectColors, |
|
508 | 508 | PyColorize.ANSICodeColors, |
|
509 | 509 | 'NoColor', |
|
510 | 510 | self.object_info_string_level) |
|
511 | 511 | |
|
512 | 512 | def init_io(self): |
|
513 | 513 | # This will just use sys.stdout and sys.stderr. If you want to |
|
514 | 514 | # override sys.stdout and sys.stderr themselves, you need to do that |
|
515 | 515 | # *before* instantiating this class, because Term holds onto |
|
516 | 516 | # references to the underlying streams. |
|
517 | 517 | if sys.platform == 'win32' and self.has_readline: |
|
518 | 518 | Term = io.IOTerm(cout=self.readline._outputfile, |
|
519 | 519 | cerr=self.readline._outputfile) |
|
520 | 520 | else: |
|
521 | 521 | Term = io.IOTerm() |
|
522 | 522 | io.Term = Term |
|
523 | 523 | |
|
524 | 524 | def init_prompts(self): |
|
525 | 525 | # TODO: This is a pass for now because the prompts are managed inside |
|
526 | 526 | # the DisplayHook. Once there is a separate prompt manager, this |
|
527 | 527 | # will initialize that object and all prompt related information. |
|
528 | 528 | pass |
|
529 | 529 | |
|
530 | 530 | def init_display_formatter(self): |
|
531 | 531 | self.display_formatter = DisplayFormatter(config=self.config) |
|
532 | 532 | |
|
533 | 533 | def init_display_pub(self): |
|
534 | 534 | self.display_pub = self.display_pub_class(config=self.config) |
|
535 | 535 | |
|
536 | 536 | def init_displayhook(self): |
|
537 | 537 | # Initialize displayhook, set in/out prompts and printing system |
|
538 | 538 | self.displayhook = self.displayhook_class( |
|
539 | 539 | config=self.config, |
|
540 | 540 | shell=self, |
|
541 | 541 | cache_size=self.cache_size, |
|
542 | 542 | input_sep = self.separate_in, |
|
543 | 543 | output_sep = self.separate_out, |
|
544 | 544 | output_sep2 = self.separate_out2, |
|
545 | 545 | ps1 = self.prompt_in1, |
|
546 | 546 | ps2 = self.prompt_in2, |
|
547 | 547 | ps_out = self.prompt_out, |
|
548 | 548 | pad_left = self.prompts_pad_left |
|
549 | 549 | ) |
|
550 | 550 | # This is a context manager that installs/revmoes the displayhook at |
|
551 | 551 | # the appropriate time. |
|
552 | 552 | self.display_trap = DisplayTrap(hook=self.displayhook) |
|
553 | 553 | |
|
554 | 554 | def init_reload_doctest(self): |
|
555 | 555 | # Do a proper resetting of doctest, including the necessary displayhook |
|
556 | 556 | # monkeypatching |
|
557 | 557 | try: |
|
558 | 558 | doctest_reload() |
|
559 | 559 | except ImportError: |
|
560 | 560 | warn("doctest module does not exist.") |
|
561 | 561 | |
|
562 | 562 | #------------------------------------------------------------------------- |
|
563 | 563 | # Things related to injections into the sys module |
|
564 | 564 | #------------------------------------------------------------------------- |
|
565 | 565 | |
|
566 | 566 | def save_sys_module_state(self): |
|
567 | 567 | """Save the state of hooks in the sys module. |
|
568 | 568 | |
|
569 | 569 | This has to be called after self.user_ns is created. |
|
570 | 570 | """ |
|
571 | 571 | self._orig_sys_module_state = {} |
|
572 | 572 | self._orig_sys_module_state['stdin'] = sys.stdin |
|
573 | 573 | self._orig_sys_module_state['stdout'] = sys.stdout |
|
574 | 574 | self._orig_sys_module_state['stderr'] = sys.stderr |
|
575 | 575 | self._orig_sys_module_state['excepthook'] = sys.excepthook |
|
576 | 576 | try: |
|
577 | 577 | self._orig_sys_modules_main_name = self.user_ns['__name__'] |
|
578 | 578 | except KeyError: |
|
579 | 579 | pass |
|
580 | 580 | |
|
581 | 581 | def restore_sys_module_state(self): |
|
582 | 582 | """Restore the state of the sys module.""" |
|
583 | 583 | try: |
|
584 | 584 | for k, v in self._orig_sys_module_state.iteritems(): |
|
585 | 585 | setattr(sys, k, v) |
|
586 | 586 | except AttributeError: |
|
587 | 587 | pass |
|
588 | 588 | # Reset what what done in self.init_sys_modules |
|
589 | 589 | try: |
|
590 | 590 | sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name |
|
591 | 591 | except (AttributeError, KeyError): |
|
592 | 592 | pass |
|
593 | 593 | |
|
594 | 594 | #------------------------------------------------------------------------- |
|
595 | 595 | # Things related to hooks |
|
596 | 596 | #------------------------------------------------------------------------- |
|
597 | 597 | |
|
598 | 598 | def init_hooks(self): |
|
599 | 599 | # hooks holds pointers used for user-side customizations |
|
600 | 600 | self.hooks = Struct() |
|
601 | 601 | |
|
602 | 602 | self.strdispatchers = {} |
|
603 | 603 | |
|
604 | 604 | # Set all default hooks, defined in the IPython.hooks module. |
|
605 | 605 | hooks = IPython.core.hooks |
|
606 | 606 | for hook_name in hooks.__all__: |
|
607 | 607 | # default hooks have priority 100, i.e. low; user hooks should have |
|
608 | 608 | # 0-100 priority |
|
609 | 609 | self.set_hook(hook_name,getattr(hooks,hook_name), 100) |
|
610 | 610 | |
|
611 | 611 | def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None): |
|
612 | 612 | """set_hook(name,hook) -> sets an internal IPython hook. |
|
613 | 613 | |
|
614 | 614 | IPython exposes some of its internal API as user-modifiable hooks. By |
|
615 | 615 | adding your function to one of these hooks, you can modify IPython's |
|
616 | 616 | behavior to call at runtime your own routines.""" |
|
617 | 617 | |
|
618 | 618 | # At some point in the future, this should validate the hook before it |
|
619 | 619 | # accepts it. Probably at least check that the hook takes the number |
|
620 | 620 | # of args it's supposed to. |
|
621 | 621 | |
|
622 | 622 | f = types.MethodType(hook,self) |
|
623 | 623 | |
|
624 | 624 | # check if the hook is for strdispatcher first |
|
625 | 625 | if str_key is not None: |
|
626 | 626 | sdp = self.strdispatchers.get(name, StrDispatch()) |
|
627 | 627 | sdp.add_s(str_key, f, priority ) |
|
628 | 628 | self.strdispatchers[name] = sdp |
|
629 | 629 | return |
|
630 | 630 | if re_key is not None: |
|
631 | 631 | sdp = self.strdispatchers.get(name, StrDispatch()) |
|
632 | 632 | sdp.add_re(re.compile(re_key), f, priority ) |
|
633 | 633 | self.strdispatchers[name] = sdp |
|
634 | 634 | return |
|
635 | 635 | |
|
636 | 636 | dp = getattr(self.hooks, name, None) |
|
637 | 637 | if name not in IPython.core.hooks.__all__: |
|
638 | 638 | print "Warning! Hook '%s' is not one of %s" % \ |
|
639 | 639 | (name, IPython.core.hooks.__all__ ) |
|
640 | 640 | if not dp: |
|
641 | 641 | dp = IPython.core.hooks.CommandChainDispatcher() |
|
642 | 642 | |
|
643 | 643 | try: |
|
644 | 644 | dp.add(f,priority) |
|
645 | 645 | except AttributeError: |
|
646 | 646 | # it was not commandchain, plain old func - replace |
|
647 | 647 | dp = f |
|
648 | 648 | |
|
649 | 649 | setattr(self.hooks,name, dp) |
|
650 | 650 | |
|
651 | 651 | def register_post_execute(self, func): |
|
652 | 652 | """Register a function for calling after code execution. |
|
653 | 653 | """ |
|
654 | 654 | if not callable(func): |
|
655 | 655 | raise ValueError('argument %s must be callable' % func) |
|
656 | 656 | self._post_execute.add(func) |
|
657 | 657 | |
|
658 | 658 | #------------------------------------------------------------------------- |
|
659 | 659 | # Things related to the "main" module |
|
660 | 660 | #------------------------------------------------------------------------- |
|
661 | 661 | |
|
662 | 662 | def new_main_mod(self,ns=None): |
|
663 | 663 | """Return a new 'main' module object for user code execution. |
|
664 | 664 | """ |
|
665 | 665 | main_mod = self._user_main_module |
|
666 | 666 | init_fakemod_dict(main_mod,ns) |
|
667 | 667 | return main_mod |
|
668 | 668 | |
|
669 | 669 | def cache_main_mod(self,ns,fname): |
|
670 | 670 | """Cache a main module's namespace. |
|
671 | 671 | |
|
672 | 672 | When scripts are executed via %run, we must keep a reference to the |
|
673 | 673 | namespace of their __main__ module (a FakeModule instance) around so |
|
674 | 674 | that Python doesn't clear it, rendering objects defined therein |
|
675 | 675 | useless. |
|
676 | 676 | |
|
677 | 677 | This method keeps said reference in a private dict, keyed by the |
|
678 | 678 | absolute path of the module object (which corresponds to the script |
|
679 | 679 | path). This way, for multiple executions of the same script we only |
|
680 | 680 | keep one copy of the namespace (the last one), thus preventing memory |
|
681 | 681 | leaks from old references while allowing the objects from the last |
|
682 | 682 | execution to be accessible. |
|
683 | 683 | |
|
684 | 684 | Note: we can not allow the actual FakeModule instances to be deleted, |
|
685 | 685 | because of how Python tears down modules (it hard-sets all their |
|
686 | 686 | references to None without regard for reference counts). This method |
|
687 | 687 | must therefore make a *copy* of the given namespace, to allow the |
|
688 | 688 | original module's __dict__ to be cleared and reused. |
|
689 | 689 | |
|
690 | 690 | |
|
691 | 691 | Parameters |
|
692 | 692 | ---------- |
|
693 | 693 | ns : a namespace (a dict, typically) |
|
694 | 694 | |
|
695 | 695 | fname : str |
|
696 | 696 | Filename associated with the namespace. |
|
697 | 697 | |
|
698 | 698 | Examples |
|
699 | 699 | -------- |
|
700 | 700 | |
|
701 | 701 | In [10]: import IPython |
|
702 | 702 | |
|
703 | 703 | In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__) |
|
704 | 704 | |
|
705 | 705 | In [12]: IPython.__file__ in _ip._main_ns_cache |
|
706 | 706 | Out[12]: True |
|
707 | 707 | """ |
|
708 | 708 | self._main_ns_cache[os.path.abspath(fname)] = ns.copy() |
|
709 | 709 | |
|
710 | 710 | def clear_main_mod_cache(self): |
|
711 | 711 | """Clear the cache of main modules. |
|
712 | 712 | |
|
713 | 713 | Mainly for use by utilities like %reset. |
|
714 | 714 | |
|
715 | 715 | Examples |
|
716 | 716 | -------- |
|
717 | 717 | |
|
718 | 718 | In [15]: import IPython |
|
719 | 719 | |
|
720 | 720 | In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__) |
|
721 | 721 | |
|
722 | 722 | In [17]: len(_ip._main_ns_cache) > 0 |
|
723 | 723 | Out[17]: True |
|
724 | 724 | |
|
725 | 725 | In [18]: _ip.clear_main_mod_cache() |
|
726 | 726 | |
|
727 | 727 | In [19]: len(_ip._main_ns_cache) == 0 |
|
728 | 728 | Out[19]: True |
|
729 | 729 | """ |
|
730 | 730 | self._main_ns_cache.clear() |
|
731 | 731 | |
|
732 | 732 | #------------------------------------------------------------------------- |
|
733 | 733 | # Things related to debugging |
|
734 | 734 | #------------------------------------------------------------------------- |
|
735 | 735 | |
|
736 | 736 | def init_pdb(self): |
|
737 | 737 | # Set calling of pdb on exceptions |
|
738 | 738 | # self.call_pdb is a property |
|
739 | 739 | self.call_pdb = self.pdb |
|
740 | 740 | |
|
741 | 741 | def _get_call_pdb(self): |
|
742 | 742 | return self._call_pdb |
|
743 | 743 | |
|
744 | 744 | def _set_call_pdb(self,val): |
|
745 | 745 | |
|
746 | 746 | if val not in (0,1,False,True): |
|
747 | 747 | raise ValueError,'new call_pdb value must be boolean' |
|
748 | 748 | |
|
749 | 749 | # store value in instance |
|
750 | 750 | self._call_pdb = val |
|
751 | 751 | |
|
752 | 752 | # notify the actual exception handlers |
|
753 | 753 | self.InteractiveTB.call_pdb = val |
|
754 | 754 | |
|
755 | 755 | call_pdb = property(_get_call_pdb,_set_call_pdb,None, |
|
756 | 756 | 'Control auto-activation of pdb at exceptions') |
|
757 | 757 | |
|
758 | 758 | def debugger(self,force=False): |
|
759 | 759 | """Call the pydb/pdb debugger. |
|
760 | 760 | |
|
761 | 761 | Keywords: |
|
762 | 762 | |
|
763 | 763 | - force(False): by default, this routine checks the instance call_pdb |
|
764 | 764 | flag and does not actually invoke the debugger if the flag is false. |
|
765 | 765 | The 'force' option forces the debugger to activate even if the flag |
|
766 | 766 | is false. |
|
767 | 767 | """ |
|
768 | 768 | |
|
769 | 769 | if not (force or self.call_pdb): |
|
770 | 770 | return |
|
771 | 771 | |
|
772 | 772 | if not hasattr(sys,'last_traceback'): |
|
773 | 773 | error('No traceback has been produced, nothing to debug.') |
|
774 | 774 | return |
|
775 | 775 | |
|
776 | 776 | # use pydb if available |
|
777 | 777 | if debugger.has_pydb: |
|
778 | 778 | from pydb import pm |
|
779 | 779 | else: |
|
780 | 780 | # fallback to our internal debugger |
|
781 | 781 | pm = lambda : self.InteractiveTB.debugger(force=True) |
|
782 | 782 | |
|
783 | 783 | with self.readline_no_record: |
|
784 | 784 | pm() |
|
785 | 785 | |
|
786 | 786 | #------------------------------------------------------------------------- |
|
787 | 787 | # Things related to IPython's various namespaces |
|
788 | 788 | #------------------------------------------------------------------------- |
|
789 | 789 | |
|
790 | 790 | def init_create_namespaces(self, user_ns=None, user_global_ns=None): |
|
791 | 791 | # Create the namespace where the user will operate. user_ns is |
|
792 | 792 | # normally the only one used, and it is passed to the exec calls as |
|
793 | 793 | # the locals argument. But we do carry a user_global_ns namespace |
|
794 | 794 | # given as the exec 'globals' argument, This is useful in embedding |
|
795 | 795 | # situations where the ipython shell opens in a context where the |
|
796 | 796 | # distinction between locals and globals is meaningful. For |
|
797 | 797 | # non-embedded contexts, it is just the same object as the user_ns dict. |
|
798 | 798 | |
|
799 | 799 | # FIXME. For some strange reason, __builtins__ is showing up at user |
|
800 | 800 | # level as a dict instead of a module. This is a manual fix, but I |
|
801 | 801 | # should really track down where the problem is coming from. Alex |
|
802 | 802 | # Schmolck reported this problem first. |
|
803 | 803 | |
|
804 | 804 | # A useful post by Alex Martelli on this topic: |
|
805 | 805 | # Re: inconsistent value from __builtins__ |
|
806 | 806 | # Von: Alex Martelli <aleaxit@yahoo.com> |
|
807 | 807 | # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends |
|
808 | 808 | # Gruppen: comp.lang.python |
|
809 | 809 | |
|
810 | 810 | # Michael Hohn <hohn@hooknose.lbl.gov> wrote: |
|
811 | 811 | # > >>> print type(builtin_check.get_global_binding('__builtins__')) |
|
812 | 812 | # > <type 'dict'> |
|
813 | 813 | # > >>> print type(__builtins__) |
|
814 | 814 | # > <type 'module'> |
|
815 | 815 | # > Is this difference in return value intentional? |
|
816 | 816 | |
|
817 | 817 | # Well, it's documented that '__builtins__' can be either a dictionary |
|
818 | 818 | # or a module, and it's been that way for a long time. Whether it's |
|
819 | 819 | # intentional (or sensible), I don't know. In any case, the idea is |
|
820 | 820 | # that if you need to access the built-in namespace directly, you |
|
821 | 821 | # should start with "import __builtin__" (note, no 's') which will |
|
822 | 822 | # definitely give you a module. Yeah, it's somewhat confusing:-(. |
|
823 | 823 | |
|
824 | 824 | # These routines return properly built dicts as needed by the rest of |
|
825 | 825 | # the code, and can also be used by extension writers to generate |
|
826 | 826 | # properly initialized namespaces. |
|
827 | 827 | user_ns, user_global_ns = self.make_user_namespaces(user_ns, |
|
828 | 828 | user_global_ns) |
|
829 | 829 | |
|
830 | 830 | # Assign namespaces |
|
831 | 831 | # This is the namespace where all normal user variables live |
|
832 | 832 | self.user_ns = user_ns |
|
833 | 833 | self.user_global_ns = user_global_ns |
|
834 | 834 | |
|
835 | 835 | # An auxiliary namespace that checks what parts of the user_ns were |
|
836 | 836 | # loaded at startup, so we can list later only variables defined in |
|
837 | 837 | # actual interactive use. Since it is always a subset of user_ns, it |
|
838 | 838 | # doesn't need to be separately tracked in the ns_table. |
|
839 | 839 | self.user_ns_hidden = {} |
|
840 | 840 | |
|
841 | 841 | # A namespace to keep track of internal data structures to prevent |
|
842 | 842 | # them from cluttering user-visible stuff. Will be updated later |
|
843 | 843 | self.internal_ns = {} |
|
844 | 844 | |
|
845 | 845 | # Now that FakeModule produces a real module, we've run into a nasty |
|
846 | 846 | # problem: after script execution (via %run), the module where the user |
|
847 | 847 | # code ran is deleted. Now that this object is a true module (needed |
|
848 | 848 | # so docetst and other tools work correctly), the Python module |
|
849 | 849 | # teardown mechanism runs over it, and sets to None every variable |
|
850 | 850 | # present in that module. Top-level references to objects from the |
|
851 | 851 | # script survive, because the user_ns is updated with them. However, |
|
852 | 852 | # calling functions defined in the script that use other things from |
|
853 | 853 | # the script will fail, because the function's closure had references |
|
854 | 854 | # to the original objects, which are now all None. So we must protect |
|
855 | 855 | # these modules from deletion by keeping a cache. |
|
856 | 856 | # |
|
857 | 857 | # To avoid keeping stale modules around (we only need the one from the |
|
858 | 858 | # last run), we use a dict keyed with the full path to the script, so |
|
859 | 859 | # only the last version of the module is held in the cache. Note, |
|
860 | 860 | # however, that we must cache the module *namespace contents* (their |
|
861 | 861 | # __dict__). Because if we try to cache the actual modules, old ones |
|
862 | 862 | # (uncached) could be destroyed while still holding references (such as |
|
863 | 863 | # those held by GUI objects that tend to be long-lived)> |
|
864 | 864 | # |
|
865 | 865 | # The %reset command will flush this cache. See the cache_main_mod() |
|
866 | 866 | # and clear_main_mod_cache() methods for details on use. |
|
867 | 867 | |
|
868 | 868 | # This is the cache used for 'main' namespaces |
|
869 | 869 | self._main_ns_cache = {} |
|
870 | 870 | # And this is the single instance of FakeModule whose __dict__ we keep |
|
871 | 871 | # copying and clearing for reuse on each %run |
|
872 | 872 | self._user_main_module = FakeModule() |
|
873 | 873 | |
|
874 | 874 | # A table holding all the namespaces IPython deals with, so that |
|
875 | 875 | # introspection facilities can search easily. |
|
876 | 876 | self.ns_table = {'user':user_ns, |
|
877 | 877 | 'user_global':user_global_ns, |
|
878 | 878 | 'internal':self.internal_ns, |
|
879 | 879 | 'builtin':__builtin__.__dict__ |
|
880 | 880 | } |
|
881 | 881 | |
|
882 | 882 | # Similarly, track all namespaces where references can be held and that |
|
883 | 883 | # we can safely clear (so it can NOT include builtin). This one can be |
|
884 | 884 | # a simple list. Note that the main execution namespaces, user_ns and |
|
885 | 885 | # user_global_ns, can NOT be listed here, as clearing them blindly |
|
886 | 886 | # causes errors in object __del__ methods. Instead, the reset() method |
|
887 | 887 | # clears them manually and carefully. |
|
888 | 888 | self.ns_refs_table = [ self.user_ns_hidden, |
|
889 | 889 | self.internal_ns, self._main_ns_cache ] |
|
890 | 890 | |
|
891 | 891 | def make_user_namespaces(self, user_ns=None, user_global_ns=None): |
|
892 | 892 | """Return a valid local and global user interactive namespaces. |
|
893 | 893 | |
|
894 | 894 | This builds a dict with the minimal information needed to operate as a |
|
895 | 895 | valid IPython user namespace, which you can pass to the various |
|
896 | 896 | embedding classes in ipython. The default implementation returns the |
|
897 | 897 | same dict for both the locals and the globals to allow functions to |
|
898 | 898 | refer to variables in the namespace. Customized implementations can |
|
899 | 899 | return different dicts. The locals dictionary can actually be anything |
|
900 | 900 | following the basic mapping protocol of a dict, but the globals dict |
|
901 | 901 | must be a true dict, not even a subclass. It is recommended that any |
|
902 | 902 | custom object for the locals namespace synchronize with the globals |
|
903 | 903 | dict somehow. |
|
904 | 904 | |
|
905 | 905 | Raises TypeError if the provided globals namespace is not a true dict. |
|
906 | 906 | |
|
907 | 907 | Parameters |
|
908 | 908 | ---------- |
|
909 | 909 | user_ns : dict-like, optional |
|
910 | 910 | The current user namespace. The items in this namespace should |
|
911 | 911 | be included in the output. If None, an appropriate blank |
|
912 | 912 | namespace should be created. |
|
913 | 913 | user_global_ns : dict, optional |
|
914 | 914 | The current user global namespace. The items in this namespace |
|
915 | 915 | should be included in the output. If None, an appropriate |
|
916 | 916 | blank namespace should be created. |
|
917 | 917 | |
|
918 | 918 | Returns |
|
919 | 919 | ------- |
|
920 | 920 | A pair of dictionary-like object to be used as the local namespace |
|
921 | 921 | of the interpreter and a dict to be used as the global namespace. |
|
922 | 922 | """ |
|
923 | 923 | |
|
924 | 924 | |
|
925 | 925 | # We must ensure that __builtin__ (without the final 's') is always |
|
926 | 926 | # available and pointing to the __builtin__ *module*. For more details: |
|
927 | 927 | # http://mail.python.org/pipermail/python-dev/2001-April/014068.html |
|
928 | 928 | |
|
929 | 929 | if user_ns is None: |
|
930 | 930 | # Set __name__ to __main__ to better match the behavior of the |
|
931 | 931 | # normal interpreter. |
|
932 | 932 | user_ns = {'__name__' :'__main__', |
|
933 | 933 | '__builtin__' : __builtin__, |
|
934 | 934 | '__builtins__' : __builtin__, |
|
935 | 935 | } |
|
936 | 936 | else: |
|
937 | 937 | user_ns.setdefault('__name__','__main__') |
|
938 | 938 | user_ns.setdefault('__builtin__',__builtin__) |
|
939 | 939 | user_ns.setdefault('__builtins__',__builtin__) |
|
940 | 940 | |
|
941 | 941 | if user_global_ns is None: |
|
942 | 942 | user_global_ns = user_ns |
|
943 | 943 | if type(user_global_ns) is not dict: |
|
944 | 944 | raise TypeError("user_global_ns must be a true dict; got %r" |
|
945 | 945 | % type(user_global_ns)) |
|
946 | 946 | |
|
947 | 947 | return user_ns, user_global_ns |
|
948 | 948 | |
|
949 | 949 | def init_sys_modules(self): |
|
950 | 950 | # We need to insert into sys.modules something that looks like a |
|
951 | 951 | # module but which accesses the IPython namespace, for shelve and |
|
952 | 952 | # pickle to work interactively. Normally they rely on getting |
|
953 | 953 | # everything out of __main__, but for embedding purposes each IPython |
|
954 | 954 | # instance has its own private namespace, so we can't go shoving |
|
955 | 955 | # everything into __main__. |
|
956 | 956 | |
|
957 | 957 | # note, however, that we should only do this for non-embedded |
|
958 | 958 | # ipythons, which really mimic the __main__.__dict__ with their own |
|
959 | 959 | # namespace. Embedded instances, on the other hand, should not do |
|
960 | 960 | # this because they need to manage the user local/global namespaces |
|
961 | 961 | # only, but they live within a 'normal' __main__ (meaning, they |
|
962 | 962 | # shouldn't overtake the execution environment of the script they're |
|
963 | 963 | # embedded in). |
|
964 | 964 | |
|
965 | 965 | # This is overridden in the InteractiveShellEmbed subclass to a no-op. |
|
966 | 966 | |
|
967 | 967 | try: |
|
968 | 968 | main_name = self.user_ns['__name__'] |
|
969 | 969 | except KeyError: |
|
970 | 970 | raise KeyError('user_ns dictionary MUST have a "__name__" key') |
|
971 | 971 | else: |
|
972 | 972 | sys.modules[main_name] = FakeModule(self.user_ns) |
|
973 | 973 | |
|
974 | 974 | def init_user_ns(self): |
|
975 | 975 | """Initialize all user-visible namespaces to their minimum defaults. |
|
976 | 976 | |
|
977 | 977 | Certain history lists are also initialized here, as they effectively |
|
978 | 978 | act as user namespaces. |
|
979 | 979 | |
|
980 | 980 | Notes |
|
981 | 981 | ----- |
|
982 | 982 | All data structures here are only filled in, they are NOT reset by this |
|
983 | 983 | method. If they were not empty before, data will simply be added to |
|
984 | 984 | therm. |
|
985 | 985 | """ |
|
986 | 986 | # This function works in two parts: first we put a few things in |
|
987 | 987 | # user_ns, and we sync that contents into user_ns_hidden so that these |
|
988 | 988 | # initial variables aren't shown by %who. After the sync, we add the |
|
989 | 989 | # rest of what we *do* want the user to see with %who even on a new |
|
990 | 990 | # session (probably nothing, so theye really only see their own stuff) |
|
991 | 991 | |
|
992 | 992 | # The user dict must *always* have a __builtin__ reference to the |
|
993 | 993 | # Python standard __builtin__ namespace, which must be imported. |
|
994 | 994 | # This is so that certain operations in prompt evaluation can be |
|
995 | 995 | # reliably executed with builtins. Note that we can NOT use |
|
996 | 996 | # __builtins__ (note the 's'), because that can either be a dict or a |
|
997 | 997 | # module, and can even mutate at runtime, depending on the context |
|
998 | 998 | # (Python makes no guarantees on it). In contrast, __builtin__ is |
|
999 | 999 | # always a module object, though it must be explicitly imported. |
|
1000 | 1000 | |
|
1001 | 1001 | # For more details: |
|
1002 | 1002 | # http://mail.python.org/pipermail/python-dev/2001-April/014068.html |
|
1003 | 1003 | ns = dict(__builtin__ = __builtin__) |
|
1004 | 1004 | |
|
1005 | 1005 | # Put 'help' in the user namespace |
|
1006 | 1006 | try: |
|
1007 | 1007 | from site import _Helper |
|
1008 | 1008 | ns['help'] = _Helper() |
|
1009 | 1009 | except ImportError: |
|
1010 | 1010 | warn('help() not available - check site.py') |
|
1011 | 1011 | |
|
1012 | 1012 | # make global variables for user access to the histories |
|
1013 | 1013 | ns['_ih'] = self.history_manager.input_hist_parsed |
|
1014 | 1014 | ns['_oh'] = self.history_manager.output_hist |
|
1015 | 1015 | ns['_dh'] = self.history_manager.dir_hist |
|
1016 | 1016 | |
|
1017 | 1017 | ns['_sh'] = shadowns |
|
1018 | 1018 | |
|
1019 | 1019 | # user aliases to input and output histories. These shouldn't show up |
|
1020 | 1020 | # in %who, as they can have very large reprs. |
|
1021 | 1021 | ns['In'] = self.history_manager.input_hist_parsed |
|
1022 | 1022 | ns['Out'] = self.history_manager.output_hist |
|
1023 | 1023 | |
|
1024 | 1024 | # Store myself as the public api!!! |
|
1025 | 1025 | ns['get_ipython'] = self.get_ipython |
|
1026 | 1026 | |
|
1027 | 1027 | # Sync what we've added so far to user_ns_hidden so these aren't seen |
|
1028 | 1028 | # by %who |
|
1029 | 1029 | self.user_ns_hidden.update(ns) |
|
1030 | 1030 | |
|
1031 | 1031 | # Anything put into ns now would show up in %who. Think twice before |
|
1032 | 1032 | # putting anything here, as we really want %who to show the user their |
|
1033 | 1033 | # stuff, not our variables. |
|
1034 | 1034 | |
|
1035 | 1035 | # Finally, update the real user's namespace |
|
1036 | 1036 | self.user_ns.update(ns) |
|
1037 | 1037 | |
|
1038 | 1038 | def reset(self, new_session=True): |
|
1039 | 1039 | """Clear all internal namespaces. |
|
1040 | 1040 | |
|
1041 | 1041 | Note that this is much more aggressive than %reset, since it clears |
|
1042 | 1042 | fully all namespaces, as well as all input/output lists. |
|
1043 | 1043 | |
|
1044 | 1044 | If new_session is True, a new history session will be opened. |
|
1045 | 1045 | """ |
|
1046 | 1046 | # Clear histories |
|
1047 | 1047 | self.history_manager.reset(new_session) |
|
1048 | ||
|
1049 | # Flush cached output items | |
|
1050 | self.displayhook.flush() | |
|
1048 | 1051 | |
|
1049 | 1052 | # Reset counter used to index all histories |
|
1050 | 1053 | self.execution_count = 0 |
|
1051 | 1054 | |
|
1052 | 1055 | # Restore the user namespaces to minimal usability |
|
1053 | 1056 | for ns in self.ns_refs_table: |
|
1054 | 1057 | ns.clear() |
|
1055 | 1058 | |
|
1056 | 1059 | # The main execution namespaces must be cleared very carefully, |
|
1057 | 1060 | # skipping the deletion of the builtin-related keys, because doing so |
|
1058 | 1061 | # would cause errors in many object's __del__ methods. |
|
1059 | 1062 | for ns in [self.user_ns, self.user_global_ns]: |
|
1060 | 1063 | drop_keys = set(ns.keys()) |
|
1061 | 1064 | drop_keys.discard('__builtin__') |
|
1062 | 1065 | drop_keys.discard('__builtins__') |
|
1063 | 1066 | for k in drop_keys: |
|
1064 | 1067 | del ns[k] |
|
1065 | 1068 | |
|
1066 | 1069 | # Restore the user namespaces to minimal usability |
|
1067 | 1070 | self.init_user_ns() |
|
1068 | 1071 | |
|
1069 | 1072 | # Restore the default and user aliases |
|
1070 | 1073 | self.alias_manager.clear_aliases() |
|
1071 | 1074 | self.alias_manager.init_aliases() |
|
1075 | ||
|
1076 | # Flush the private list of module references kept for script | |
|
1077 | # execution protection | |
|
1078 | self.clear_main_mod_cache() | |
|
1072 | 1079 | |
|
1073 | 1080 | def reset_selective(self, regex=None): |
|
1074 | 1081 | """Clear selective variables from internal namespaces based on a |
|
1075 | 1082 | specified regular expression. |
|
1076 | 1083 | |
|
1077 | 1084 | Parameters |
|
1078 | 1085 | ---------- |
|
1079 | 1086 | regex : string or compiled pattern, optional |
|
1080 | 1087 | A regular expression pattern that will be used in searching |
|
1081 | 1088 | variable names in the users namespaces. |
|
1082 | 1089 | """ |
|
1083 | 1090 | if regex is not None: |
|
1084 | 1091 | try: |
|
1085 | 1092 | m = re.compile(regex) |
|
1086 | 1093 | except TypeError: |
|
1087 | 1094 | raise TypeError('regex must be a string or compiled pattern') |
|
1088 | 1095 | # Search for keys in each namespace that match the given regex |
|
1089 | 1096 | # If a match is found, delete the key/value pair. |
|
1090 | 1097 | for ns in self.ns_refs_table: |
|
1091 | 1098 | for var in ns: |
|
1092 | 1099 | if m.search(var): |
|
1093 | 1100 | del ns[var] |
|
1094 | 1101 | |
|
1095 | 1102 | def push(self, variables, interactive=True): |
|
1096 | 1103 | """Inject a group of variables into the IPython user namespace. |
|
1097 | 1104 | |
|
1098 | 1105 | Parameters |
|
1099 | 1106 | ---------- |
|
1100 | 1107 | variables : dict, str or list/tuple of str |
|
1101 | 1108 | The variables to inject into the user's namespace. If a dict, a |
|
1102 | 1109 | simple update is done. If a str, the string is assumed to have |
|
1103 | 1110 | variable names separated by spaces. A list/tuple of str can also |
|
1104 | 1111 | be used to give the variable names. If just the variable names are |
|
1105 | 1112 | give (list/tuple/str) then the variable values looked up in the |
|
1106 | 1113 | callers frame. |
|
1107 | 1114 | interactive : bool |
|
1108 | 1115 | If True (default), the variables will be listed with the ``who`` |
|
1109 | 1116 | magic. |
|
1110 | 1117 | """ |
|
1111 | 1118 | vdict = None |
|
1112 | 1119 | |
|
1113 | 1120 | # We need a dict of name/value pairs to do namespace updates. |
|
1114 | 1121 | if isinstance(variables, dict): |
|
1115 | 1122 | vdict = variables |
|
1116 | 1123 | elif isinstance(variables, (basestring, list, tuple)): |
|
1117 | 1124 | if isinstance(variables, basestring): |
|
1118 | 1125 | vlist = variables.split() |
|
1119 | 1126 | else: |
|
1120 | 1127 | vlist = variables |
|
1121 | 1128 | vdict = {} |
|
1122 | 1129 | cf = sys._getframe(1) |
|
1123 | 1130 | for name in vlist: |
|
1124 | 1131 | try: |
|
1125 | 1132 | vdict[name] = eval(name, cf.f_globals, cf.f_locals) |
|
1126 | 1133 | except: |
|
1127 | 1134 | print ('Could not get variable %s from %s' % |
|
1128 | 1135 | (name,cf.f_code.co_name)) |
|
1129 | 1136 | else: |
|
1130 | 1137 | raise ValueError('variables must be a dict/str/list/tuple') |
|
1131 | 1138 | |
|
1132 | 1139 | # Propagate variables to user namespace |
|
1133 | 1140 | self.user_ns.update(vdict) |
|
1134 | 1141 | |
|
1135 | 1142 | # And configure interactive visibility |
|
1136 | 1143 | config_ns = self.user_ns_hidden |
|
1137 | 1144 | if interactive: |
|
1138 | 1145 | for name, val in vdict.iteritems(): |
|
1139 | 1146 | config_ns.pop(name, None) |
|
1140 | 1147 | else: |
|
1141 | 1148 | for name,val in vdict.iteritems(): |
|
1142 | 1149 | config_ns[name] = val |
|
1143 | 1150 | |
|
1144 | 1151 | #------------------------------------------------------------------------- |
|
1145 | 1152 | # Things related to object introspection |
|
1146 | 1153 | #------------------------------------------------------------------------- |
|
1147 | 1154 | |
|
1148 | 1155 | def _ofind(self, oname, namespaces=None): |
|
1149 | 1156 | """Find an object in the available namespaces. |
|
1150 | 1157 | |
|
1151 | 1158 | self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic |
|
1152 | 1159 | |
|
1153 | 1160 | Has special code to detect magic functions. |
|
1154 | 1161 | """ |
|
1155 | 1162 | #oname = oname.strip() |
|
1156 | 1163 | #print '1- oname: <%r>' % oname # dbg |
|
1157 | 1164 | try: |
|
1158 | 1165 | oname = oname.strip().encode('ascii') |
|
1159 | 1166 | #print '2- oname: <%r>' % oname # dbg |
|
1160 | 1167 | except UnicodeEncodeError: |
|
1161 | 1168 | print 'Python identifiers can only contain ascii characters.' |
|
1162 | 1169 | return dict(found=False) |
|
1163 | 1170 | |
|
1164 | 1171 | alias_ns = None |
|
1165 | 1172 | if namespaces is None: |
|
1166 | 1173 | # Namespaces to search in: |
|
1167 | 1174 | # Put them in a list. The order is important so that we |
|
1168 | 1175 | # find things in the same order that Python finds them. |
|
1169 | 1176 | namespaces = [ ('Interactive', self.user_ns), |
|
1170 | 1177 | ('IPython internal', self.internal_ns), |
|
1171 | 1178 | ('Python builtin', __builtin__.__dict__), |
|
1172 | 1179 | ('Alias', self.alias_manager.alias_table), |
|
1173 | 1180 | ] |
|
1174 | 1181 | alias_ns = self.alias_manager.alias_table |
|
1175 | 1182 | |
|
1176 | 1183 | # initialize results to 'null' |
|
1177 | 1184 | found = False; obj = None; ospace = None; ds = None; |
|
1178 | 1185 | ismagic = False; isalias = False; parent = None |
|
1179 | 1186 | |
|
1180 | 1187 | # We need to special-case 'print', which as of python2.6 registers as a |
|
1181 | 1188 | # function but should only be treated as one if print_function was |
|
1182 | 1189 | # loaded with a future import. In this case, just bail. |
|
1183 | 1190 | if (oname == 'print' and not (self.compile.compiler_flags & |
|
1184 | 1191 | __future__.CO_FUTURE_PRINT_FUNCTION)): |
|
1185 | 1192 | return {'found':found, 'obj':obj, 'namespace':ospace, |
|
1186 | 1193 | 'ismagic':ismagic, 'isalias':isalias, 'parent':parent} |
|
1187 | 1194 | |
|
1188 | 1195 | # Look for the given name by splitting it in parts. If the head is |
|
1189 | 1196 | # found, then we look for all the remaining parts as members, and only |
|
1190 | 1197 | # declare success if we can find them all. |
|
1191 | 1198 | oname_parts = oname.split('.') |
|
1192 | 1199 | oname_head, oname_rest = oname_parts[0],oname_parts[1:] |
|
1193 | 1200 | for nsname,ns in namespaces: |
|
1194 | 1201 | try: |
|
1195 | 1202 | obj = ns[oname_head] |
|
1196 | 1203 | except KeyError: |
|
1197 | 1204 | continue |
|
1198 | 1205 | else: |
|
1199 | 1206 | #print 'oname_rest:', oname_rest # dbg |
|
1200 | 1207 | for part in oname_rest: |
|
1201 | 1208 | try: |
|
1202 | 1209 | parent = obj |
|
1203 | 1210 | obj = getattr(obj,part) |
|
1204 | 1211 | except: |
|
1205 | 1212 | # Blanket except b/c some badly implemented objects |
|
1206 | 1213 | # allow __getattr__ to raise exceptions other than |
|
1207 | 1214 | # AttributeError, which then crashes IPython. |
|
1208 | 1215 | break |
|
1209 | 1216 | else: |
|
1210 | 1217 | # If we finish the for loop (no break), we got all members |
|
1211 | 1218 | found = True |
|
1212 | 1219 | ospace = nsname |
|
1213 | 1220 | if ns == alias_ns: |
|
1214 | 1221 | isalias = True |
|
1215 | 1222 | break # namespace loop |
|
1216 | 1223 | |
|
1217 | 1224 | # Try to see if it's magic |
|
1218 | 1225 | if not found: |
|
1219 | 1226 | if oname.startswith(ESC_MAGIC): |
|
1220 | 1227 | oname = oname[1:] |
|
1221 | 1228 | obj = getattr(self,'magic_'+oname,None) |
|
1222 | 1229 | if obj is not None: |
|
1223 | 1230 | found = True |
|
1224 | 1231 | ospace = 'IPython internal' |
|
1225 | 1232 | ismagic = True |
|
1226 | 1233 | |
|
1227 | 1234 | # Last try: special-case some literals like '', [], {}, etc: |
|
1228 | 1235 | if not found and oname_head in ["''",'""','[]','{}','()']: |
|
1229 | 1236 | obj = eval(oname_head) |
|
1230 | 1237 | found = True |
|
1231 | 1238 | ospace = 'Interactive' |
|
1232 | 1239 | |
|
1233 | 1240 | return {'found':found, 'obj':obj, 'namespace':ospace, |
|
1234 | 1241 | 'ismagic':ismagic, 'isalias':isalias, 'parent':parent} |
|
1235 | 1242 | |
|
1236 | 1243 | def _ofind_property(self, oname, info): |
|
1237 | 1244 | """Second part of object finding, to look for property details.""" |
|
1238 | 1245 | if info.found: |
|
1239 | 1246 | # Get the docstring of the class property if it exists. |
|
1240 | 1247 | path = oname.split('.') |
|
1241 | 1248 | root = '.'.join(path[:-1]) |
|
1242 | 1249 | if info.parent is not None: |
|
1243 | 1250 | try: |
|
1244 | 1251 | target = getattr(info.parent, '__class__') |
|
1245 | 1252 | # The object belongs to a class instance. |
|
1246 | 1253 | try: |
|
1247 | 1254 | target = getattr(target, path[-1]) |
|
1248 | 1255 | # The class defines the object. |
|
1249 | 1256 | if isinstance(target, property): |
|
1250 | 1257 | oname = root + '.__class__.' + path[-1] |
|
1251 | 1258 | info = Struct(self._ofind(oname)) |
|
1252 | 1259 | except AttributeError: pass |
|
1253 | 1260 | except AttributeError: pass |
|
1254 | 1261 | |
|
1255 | 1262 | # We return either the new info or the unmodified input if the object |
|
1256 | 1263 | # hadn't been found |
|
1257 | 1264 | return info |
|
1258 | 1265 | |
|
1259 | 1266 | def _object_find(self, oname, namespaces=None): |
|
1260 | 1267 | """Find an object and return a struct with info about it.""" |
|
1261 | 1268 | inf = Struct(self._ofind(oname, namespaces)) |
|
1262 | 1269 | return Struct(self._ofind_property(oname, inf)) |
|
1263 | 1270 | |
|
1264 | 1271 | def _inspect(self, meth, oname, namespaces=None, **kw): |
|
1265 | 1272 | """Generic interface to the inspector system. |
|
1266 | 1273 | |
|
1267 | 1274 | This function is meant to be called by pdef, pdoc & friends.""" |
|
1268 | 1275 | info = self._object_find(oname) |
|
1269 | 1276 | if info.found: |
|
1270 | 1277 | pmethod = getattr(self.inspector, meth) |
|
1271 | 1278 | formatter = format_screen if info.ismagic else None |
|
1272 | 1279 | if meth == 'pdoc': |
|
1273 | 1280 | pmethod(info.obj, oname, formatter) |
|
1274 | 1281 | elif meth == 'pinfo': |
|
1275 | 1282 | pmethod(info.obj, oname, formatter, info, **kw) |
|
1276 | 1283 | else: |
|
1277 | 1284 | pmethod(info.obj, oname) |
|
1278 | 1285 | else: |
|
1279 | 1286 | print 'Object `%s` not found.' % oname |
|
1280 | 1287 | return 'not found' # so callers can take other action |
|
1281 | 1288 | |
|
1282 | 1289 | def object_inspect(self, oname): |
|
1283 | 1290 | info = self._object_find(oname) |
|
1284 | 1291 | if info.found: |
|
1285 | 1292 | return self.inspector.info(info.obj, oname, info=info) |
|
1286 | 1293 | else: |
|
1287 | 1294 | return oinspect.object_info(name=oname, found=False) |
|
1288 | 1295 | |
|
1289 | 1296 | #------------------------------------------------------------------------- |
|
1290 | 1297 | # Things related to history management |
|
1291 | 1298 | #------------------------------------------------------------------------- |
|
1292 | 1299 | |
|
1293 | 1300 | def init_history(self): |
|
1294 | 1301 | """Sets up the command history, and starts regular autosaves.""" |
|
1295 | 1302 | self.history_manager = HistoryManager(shell=self, config=self.config) |
|
1296 | 1303 | |
|
1297 | 1304 | #------------------------------------------------------------------------- |
|
1298 | 1305 | # Things related to exception handling and tracebacks (not debugging) |
|
1299 | 1306 | #------------------------------------------------------------------------- |
|
1300 | 1307 | |
|
1301 | 1308 | def init_traceback_handlers(self, custom_exceptions): |
|
1302 | 1309 | # Syntax error handler. |
|
1303 | 1310 | self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor') |
|
1304 | 1311 | |
|
1305 | 1312 | # The interactive one is initialized with an offset, meaning we always |
|
1306 | 1313 | # want to remove the topmost item in the traceback, which is our own |
|
1307 | 1314 | # internal code. Valid modes: ['Plain','Context','Verbose'] |
|
1308 | 1315 | self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain', |
|
1309 | 1316 | color_scheme='NoColor', |
|
1310 | 1317 | tb_offset = 1, |
|
1311 | 1318 | check_cache=self.compile.check_cache) |
|
1312 | 1319 | |
|
1313 | 1320 | # The instance will store a pointer to the system-wide exception hook, |
|
1314 | 1321 | # so that runtime code (such as magics) can access it. This is because |
|
1315 | 1322 | # during the read-eval loop, it may get temporarily overwritten. |
|
1316 | 1323 | self.sys_excepthook = sys.excepthook |
|
1317 | 1324 | |
|
1318 | 1325 | # and add any custom exception handlers the user may have specified |
|
1319 | 1326 | self.set_custom_exc(*custom_exceptions) |
|
1320 | 1327 | |
|
1321 | 1328 | # Set the exception mode |
|
1322 | 1329 | self.InteractiveTB.set_mode(mode=self.xmode) |
|
1323 | 1330 | |
|
1324 | 1331 | def set_custom_exc(self, exc_tuple, handler): |
|
1325 | 1332 | """set_custom_exc(exc_tuple,handler) |
|
1326 | 1333 | |
|
1327 | 1334 | Set a custom exception handler, which will be called if any of the |
|
1328 | 1335 | exceptions in exc_tuple occur in the mainloop (specifically, in the |
|
1329 | 1336 | run_code() method. |
|
1330 | 1337 | |
|
1331 | 1338 | Inputs: |
|
1332 | 1339 | |
|
1333 | 1340 | - exc_tuple: a *tuple* of valid exceptions to call the defined |
|
1334 | 1341 | handler for. It is very important that you use a tuple, and NOT A |
|
1335 | 1342 | LIST here, because of the way Python's except statement works. If |
|
1336 | 1343 | you only want to trap a single exception, use a singleton tuple: |
|
1337 | 1344 | |
|
1338 | 1345 | exc_tuple == (MyCustomException,) |
|
1339 | 1346 | |
|
1340 | 1347 | - handler: this must be defined as a function with the following |
|
1341 | 1348 | basic interface:: |
|
1342 | 1349 | |
|
1343 | 1350 | def my_handler(self, etype, value, tb, tb_offset=None) |
|
1344 | 1351 | ... |
|
1345 | 1352 | # The return value must be |
|
1346 | 1353 | return structured_traceback |
|
1347 | 1354 | |
|
1348 | 1355 | This will be made into an instance method (via types.MethodType) |
|
1349 | 1356 | of IPython itself, and it will be called if any of the exceptions |
|
1350 | 1357 | listed in the exc_tuple are caught. If the handler is None, an |
|
1351 | 1358 | internal basic one is used, which just prints basic info. |
|
1352 | 1359 | |
|
1353 | 1360 | WARNING: by putting in your own exception handler into IPython's main |
|
1354 | 1361 | execution loop, you run a very good chance of nasty crashes. This |
|
1355 | 1362 | facility should only be used if you really know what you are doing.""" |
|
1356 | 1363 | |
|
1357 | 1364 | assert type(exc_tuple)==type(()) , \ |
|
1358 | 1365 | "The custom exceptions must be given AS A TUPLE." |
|
1359 | 1366 | |
|
1360 | 1367 | def dummy_handler(self,etype,value,tb): |
|
1361 | 1368 | print '*** Simple custom exception handler ***' |
|
1362 | 1369 | print 'Exception type :',etype |
|
1363 | 1370 | print 'Exception value:',value |
|
1364 | 1371 | print 'Traceback :',tb |
|
1365 | 1372 | print 'Source code :','\n'.join(self.buffer) |
|
1366 | 1373 | |
|
1367 | 1374 | if handler is None: handler = dummy_handler |
|
1368 | 1375 | |
|
1369 | 1376 | self.CustomTB = types.MethodType(handler,self) |
|
1370 | 1377 | self.custom_exceptions = exc_tuple |
|
1371 | 1378 | |
|
1372 | 1379 | def excepthook(self, etype, value, tb): |
|
1373 | 1380 | """One more defense for GUI apps that call sys.excepthook. |
|
1374 | 1381 | |
|
1375 | 1382 | GUI frameworks like wxPython trap exceptions and call |
|
1376 | 1383 | sys.excepthook themselves. I guess this is a feature that |
|
1377 | 1384 | enables them to keep running after exceptions that would |
|
1378 | 1385 | otherwise kill their mainloop. This is a bother for IPython |
|
1379 | 1386 | which excepts to catch all of the program exceptions with a try: |
|
1380 | 1387 | except: statement. |
|
1381 | 1388 | |
|
1382 | 1389 | Normally, IPython sets sys.excepthook to a CrashHandler instance, so if |
|
1383 | 1390 | any app directly invokes sys.excepthook, it will look to the user like |
|
1384 | 1391 | IPython crashed. In order to work around this, we can disable the |
|
1385 | 1392 | CrashHandler and replace it with this excepthook instead, which prints a |
|
1386 | 1393 | regular traceback using our InteractiveTB. In this fashion, apps which |
|
1387 | 1394 | call sys.excepthook will generate a regular-looking exception from |
|
1388 | 1395 | IPython, and the CrashHandler will only be triggered by real IPython |
|
1389 | 1396 | crashes. |
|
1390 | 1397 | |
|
1391 | 1398 | This hook should be used sparingly, only in places which are not likely |
|
1392 | 1399 | to be true IPython errors. |
|
1393 | 1400 | """ |
|
1394 | 1401 | self.showtraceback((etype,value,tb),tb_offset=0) |
|
1395 | 1402 | |
|
1396 | 1403 | def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None, |
|
1397 | 1404 | exception_only=False): |
|
1398 | 1405 | """Display the exception that just occurred. |
|
1399 | 1406 | |
|
1400 | 1407 | If nothing is known about the exception, this is the method which |
|
1401 | 1408 | should be used throughout the code for presenting user tracebacks, |
|
1402 | 1409 | rather than directly invoking the InteractiveTB object. |
|
1403 | 1410 | |
|
1404 | 1411 | A specific showsyntaxerror() also exists, but this method can take |
|
1405 | 1412 | care of calling it if needed, so unless you are explicitly catching a |
|
1406 | 1413 | SyntaxError exception, don't try to analyze the stack manually and |
|
1407 | 1414 | simply call this method.""" |
|
1408 | 1415 | |
|
1409 | 1416 | try: |
|
1410 | 1417 | if exc_tuple is None: |
|
1411 | 1418 | etype, value, tb = sys.exc_info() |
|
1412 | 1419 | else: |
|
1413 | 1420 | etype, value, tb = exc_tuple |
|
1414 | 1421 | |
|
1415 | 1422 | if etype is None: |
|
1416 | 1423 | if hasattr(sys, 'last_type'): |
|
1417 | 1424 | etype, value, tb = sys.last_type, sys.last_value, \ |
|
1418 | 1425 | sys.last_traceback |
|
1419 | 1426 | else: |
|
1420 | 1427 | self.write_err('No traceback available to show.\n') |
|
1421 | 1428 | return |
|
1422 | 1429 | |
|
1423 | 1430 | if etype is SyntaxError: |
|
1424 | 1431 | # Though this won't be called by syntax errors in the input |
|
1425 | 1432 | # line, there may be SyntaxError cases whith imported code. |
|
1426 | 1433 | self.showsyntaxerror(filename) |
|
1427 | 1434 | elif etype is UsageError: |
|
1428 | 1435 | print "UsageError:", value |
|
1429 | 1436 | else: |
|
1430 | 1437 | # WARNING: these variables are somewhat deprecated and not |
|
1431 | 1438 | # necessarily safe to use in a threaded environment, but tools |
|
1432 | 1439 | # like pdb depend on their existence, so let's set them. If we |
|
1433 | 1440 | # find problems in the field, we'll need to revisit their use. |
|
1434 | 1441 | sys.last_type = etype |
|
1435 | 1442 | sys.last_value = value |
|
1436 | 1443 | sys.last_traceback = tb |
|
1437 | 1444 | |
|
1438 | 1445 | if etype in self.custom_exceptions: |
|
1439 | 1446 | # FIXME: Old custom traceback objects may just return a |
|
1440 | 1447 | # string, in that case we just put it into a list |
|
1441 | 1448 | stb = self.CustomTB(etype, value, tb, tb_offset) |
|
1442 | 1449 | if isinstance(ctb, basestring): |
|
1443 | 1450 | stb = [stb] |
|
1444 | 1451 | else: |
|
1445 | 1452 | if exception_only: |
|
1446 | 1453 | stb = ['An exception has occurred, use %tb to see ' |
|
1447 | 1454 | 'the full traceback.\n'] |
|
1448 | 1455 | stb.extend(self.InteractiveTB.get_exception_only(etype, |
|
1449 | 1456 | value)) |
|
1450 | 1457 | else: |
|
1451 | 1458 | stb = self.InteractiveTB.structured_traceback(etype, |
|
1452 | 1459 | value, tb, tb_offset=tb_offset) |
|
1453 | 1460 | # FIXME: the pdb calling should be done by us, not by |
|
1454 | 1461 | # the code computing the traceback. |
|
1455 | 1462 | if self.InteractiveTB.call_pdb: |
|
1456 | 1463 | # pdb mucks up readline, fix it back |
|
1457 | 1464 | self.set_readline_completer() |
|
1458 | 1465 | |
|
1459 | 1466 | # Actually show the traceback |
|
1460 | 1467 | self._showtraceback(etype, value, stb) |
|
1461 | 1468 | |
|
1462 | 1469 | except KeyboardInterrupt: |
|
1463 | 1470 | self.write_err("\nKeyboardInterrupt\n") |
|
1464 | 1471 | |
|
1465 | 1472 | def _showtraceback(self, etype, evalue, stb): |
|
1466 | 1473 | """Actually show a traceback. |
|
1467 | 1474 | |
|
1468 | 1475 | Subclasses may override this method to put the traceback on a different |
|
1469 | 1476 | place, like a side channel. |
|
1470 | 1477 | """ |
|
1471 | 1478 | print >> io.Term.cout, self.InteractiveTB.stb2text(stb) |
|
1472 | 1479 | |
|
1473 | 1480 | def showsyntaxerror(self, filename=None): |
|
1474 | 1481 | """Display the syntax error that just occurred. |
|
1475 | 1482 | |
|
1476 | 1483 | This doesn't display a stack trace because there isn't one. |
|
1477 | 1484 | |
|
1478 | 1485 | If a filename is given, it is stuffed in the exception instead |
|
1479 | 1486 | of what was there before (because Python's parser always uses |
|
1480 | 1487 | "<string>" when reading from a string). |
|
1481 | 1488 | """ |
|
1482 | 1489 | etype, value, last_traceback = sys.exc_info() |
|
1483 | 1490 | |
|
1484 | 1491 | # See note about these variables in showtraceback() above |
|
1485 | 1492 | sys.last_type = etype |
|
1486 | 1493 | sys.last_value = value |
|
1487 | 1494 | sys.last_traceback = last_traceback |
|
1488 | 1495 | |
|
1489 | 1496 | if filename and etype is SyntaxError: |
|
1490 | 1497 | # Work hard to stuff the correct filename in the exception |
|
1491 | 1498 | try: |
|
1492 | 1499 | msg, (dummy_filename, lineno, offset, line) = value |
|
1493 | 1500 | except: |
|
1494 | 1501 | # Not the format we expect; leave it alone |
|
1495 | 1502 | pass |
|
1496 | 1503 | else: |
|
1497 | 1504 | # Stuff in the right filename |
|
1498 | 1505 | try: |
|
1499 | 1506 | # Assume SyntaxError is a class exception |
|
1500 | 1507 | value = SyntaxError(msg, (filename, lineno, offset, line)) |
|
1501 | 1508 | except: |
|
1502 | 1509 | # If that failed, assume SyntaxError is a string |
|
1503 | 1510 | value = msg, (filename, lineno, offset, line) |
|
1504 | 1511 | stb = self.SyntaxTB.structured_traceback(etype, value, []) |
|
1505 | 1512 | self._showtraceback(etype, value, stb) |
|
1506 | 1513 | |
|
1507 | 1514 | #------------------------------------------------------------------------- |
|
1508 | 1515 | # Things related to readline |
|
1509 | 1516 | #------------------------------------------------------------------------- |
|
1510 | 1517 | |
|
1511 | 1518 | def init_readline(self): |
|
1512 | 1519 | """Command history completion/saving/reloading.""" |
|
1513 | 1520 | |
|
1514 | 1521 | if self.readline_use: |
|
1515 | 1522 | import IPython.utils.rlineimpl as readline |
|
1516 | 1523 | |
|
1517 | 1524 | self.rl_next_input = None |
|
1518 | 1525 | self.rl_do_indent = False |
|
1519 | 1526 | |
|
1520 | 1527 | if not self.readline_use or not readline.have_readline: |
|
1521 | 1528 | self.has_readline = False |
|
1522 | 1529 | self.readline = None |
|
1523 | 1530 | # Set a number of methods that depend on readline to be no-op |
|
1524 | 1531 | self.set_readline_completer = no_op |
|
1525 | 1532 | self.set_custom_completer = no_op |
|
1526 | 1533 | self.set_completer_frame = no_op |
|
1527 | 1534 | warn('Readline services not available or not loaded.') |
|
1528 | 1535 | else: |
|
1529 | 1536 | self.has_readline = True |
|
1530 | 1537 | self.readline = readline |
|
1531 | 1538 | sys.modules['readline'] = readline |
|
1532 | 1539 | |
|
1533 | 1540 | # Platform-specific configuration |
|
1534 | 1541 | if os.name == 'nt': |
|
1535 | 1542 | # FIXME - check with Frederick to see if we can harmonize |
|
1536 | 1543 | # naming conventions with pyreadline to avoid this |
|
1537 | 1544 | # platform-dependent check |
|
1538 | 1545 | self.readline_startup_hook = readline.set_pre_input_hook |
|
1539 | 1546 | else: |
|
1540 | 1547 | self.readline_startup_hook = readline.set_startup_hook |
|
1541 | 1548 | |
|
1542 | 1549 | # Load user's initrc file (readline config) |
|
1543 | 1550 | # Or if libedit is used, load editrc. |
|
1544 | 1551 | inputrc_name = os.environ.get('INPUTRC') |
|
1545 | 1552 | if inputrc_name is None: |
|
1546 | 1553 | home_dir = get_home_dir() |
|
1547 | 1554 | if home_dir is not None: |
|
1548 | 1555 | inputrc_name = '.inputrc' |
|
1549 | 1556 | if readline.uses_libedit: |
|
1550 | 1557 | inputrc_name = '.editrc' |
|
1551 | 1558 | inputrc_name = os.path.join(home_dir, inputrc_name) |
|
1552 | 1559 | if os.path.isfile(inputrc_name): |
|
1553 | 1560 | try: |
|
1554 | 1561 | readline.read_init_file(inputrc_name) |
|
1555 | 1562 | except: |
|
1556 | 1563 | warn('Problems reading readline initialization file <%s>' |
|
1557 | 1564 | % inputrc_name) |
|
1558 | 1565 | |
|
1559 | 1566 | # Configure readline according to user's prefs |
|
1560 | 1567 | # This is only done if GNU readline is being used. If libedit |
|
1561 | 1568 | # is being used (as on Leopard) the readline config is |
|
1562 | 1569 | # not run as the syntax for libedit is different. |
|
1563 | 1570 | if not readline.uses_libedit: |
|
1564 | 1571 | for rlcommand in self.readline_parse_and_bind: |
|
1565 | 1572 | #print "loading rl:",rlcommand # dbg |
|
1566 | 1573 | readline.parse_and_bind(rlcommand) |
|
1567 | 1574 | |
|
1568 | 1575 | # Remove some chars from the delimiters list. If we encounter |
|
1569 | 1576 | # unicode chars, discard them. |
|
1570 | 1577 | delims = readline.get_completer_delims().encode("ascii", "ignore") |
|
1571 | 1578 | delims = delims.translate(None, self.readline_remove_delims) |
|
1572 | 1579 | delims = delims.replace(ESC_MAGIC, '') |
|
1573 | 1580 | readline.set_completer_delims(delims) |
|
1574 | 1581 | # otherwise we end up with a monster history after a while: |
|
1575 | 1582 | readline.set_history_length(self.history_length) |
|
1576 | 1583 | |
|
1577 | 1584 | self.refill_readline_hist() |
|
1578 | 1585 | self.readline_no_record = ReadlineNoRecord(self) |
|
1579 | 1586 | |
|
1580 | 1587 | # Configure auto-indent for all platforms |
|
1581 | 1588 | self.set_autoindent(self.autoindent) |
|
1582 | 1589 | |
|
1583 | 1590 | def refill_readline_hist(self): |
|
1584 | 1591 | # Load the last 1000 lines from history |
|
1585 | 1592 | self.readline.clear_history() |
|
1586 | 1593 | stdin_encoding = sys.stdin.encoding or "utf-8" |
|
1587 | 1594 | for _, _, cell in self.history_manager.get_tail(1000, |
|
1588 | 1595 | include_latest=True): |
|
1589 | 1596 | if cell.strip(): # Ignore blank lines |
|
1590 | 1597 | for line in cell.splitlines(): |
|
1591 | 1598 | self.readline.add_history(line.encode(stdin_encoding)) |
|
1592 | 1599 | |
|
1593 | 1600 | def set_next_input(self, s): |
|
1594 | 1601 | """ Sets the 'default' input string for the next command line. |
|
1595 | 1602 | |
|
1596 | 1603 | Requires readline. |
|
1597 | 1604 | |
|
1598 | 1605 | Example: |
|
1599 | 1606 | |
|
1600 | 1607 | [D:\ipython]|1> _ip.set_next_input("Hello Word") |
|
1601 | 1608 | [D:\ipython]|2> Hello Word_ # cursor is here |
|
1602 | 1609 | """ |
|
1603 | 1610 | |
|
1604 | 1611 | self.rl_next_input = s |
|
1605 | 1612 | |
|
1606 | 1613 | # Maybe move this to the terminal subclass? |
|
1607 | 1614 | def pre_readline(self): |
|
1608 | 1615 | """readline hook to be used at the start of each line. |
|
1609 | 1616 | |
|
1610 | 1617 | Currently it handles auto-indent only.""" |
|
1611 | 1618 | |
|
1612 | 1619 | if self.rl_do_indent: |
|
1613 | 1620 | self.readline.insert_text(self._indent_current_str()) |
|
1614 | 1621 | if self.rl_next_input is not None: |
|
1615 | 1622 | self.readline.insert_text(self.rl_next_input) |
|
1616 | 1623 | self.rl_next_input = None |
|
1617 | 1624 | |
|
1618 | 1625 | def _indent_current_str(self): |
|
1619 | 1626 | """return the current level of indentation as a string""" |
|
1620 | 1627 | return self.input_splitter.indent_spaces * ' ' |
|
1621 | 1628 | |
|
1622 | 1629 | #------------------------------------------------------------------------- |
|
1623 | 1630 | # Things related to text completion |
|
1624 | 1631 | #------------------------------------------------------------------------- |
|
1625 | 1632 | |
|
1626 | 1633 | def init_completer(self): |
|
1627 | 1634 | """Initialize the completion machinery. |
|
1628 | 1635 | |
|
1629 | 1636 | This creates completion machinery that can be used by client code, |
|
1630 | 1637 | either interactively in-process (typically triggered by the readline |
|
1631 | 1638 | library), programatically (such as in test suites) or out-of-prcess |
|
1632 | 1639 | (typically over the network by remote frontends). |
|
1633 | 1640 | """ |
|
1634 | 1641 | from IPython.core.completer import IPCompleter |
|
1635 | 1642 | from IPython.core.completerlib import (module_completer, |
|
1636 | 1643 | magic_run_completer, cd_completer) |
|
1637 | 1644 | |
|
1638 | 1645 | self.Completer = IPCompleter(self, |
|
1639 | 1646 | self.user_ns, |
|
1640 | 1647 | self.user_global_ns, |
|
1641 | 1648 | self.readline_omit__names, |
|
1642 | 1649 | self.alias_manager.alias_table, |
|
1643 | 1650 | self.has_readline) |
|
1644 | 1651 | |
|
1645 | 1652 | # Add custom completers to the basic ones built into IPCompleter |
|
1646 | 1653 | sdisp = self.strdispatchers.get('complete_command', StrDispatch()) |
|
1647 | 1654 | self.strdispatchers['complete_command'] = sdisp |
|
1648 | 1655 | self.Completer.custom_completers = sdisp |
|
1649 | 1656 | |
|
1650 | 1657 | self.set_hook('complete_command', module_completer, str_key = 'import') |
|
1651 | 1658 | self.set_hook('complete_command', module_completer, str_key = 'from') |
|
1652 | 1659 | self.set_hook('complete_command', magic_run_completer, str_key = '%run') |
|
1653 | 1660 | self.set_hook('complete_command', cd_completer, str_key = '%cd') |
|
1654 | 1661 | |
|
1655 | 1662 | # Only configure readline if we truly are using readline. IPython can |
|
1656 | 1663 | # do tab-completion over the network, in GUIs, etc, where readline |
|
1657 | 1664 | # itself may be absent |
|
1658 | 1665 | if self.has_readline: |
|
1659 | 1666 | self.set_readline_completer() |
|
1660 | 1667 | |
|
1661 | 1668 | def complete(self, text, line=None, cursor_pos=None): |
|
1662 | 1669 | """Return the completed text and a list of completions. |
|
1663 | 1670 | |
|
1664 | 1671 | Parameters |
|
1665 | 1672 | ---------- |
|
1666 | 1673 | |
|
1667 | 1674 | text : string |
|
1668 | 1675 | A string of text to be completed on. It can be given as empty and |
|
1669 | 1676 | instead a line/position pair are given. In this case, the |
|
1670 | 1677 | completer itself will split the line like readline does. |
|
1671 | 1678 | |
|
1672 | 1679 | line : string, optional |
|
1673 | 1680 | The complete line that text is part of. |
|
1674 | 1681 | |
|
1675 | 1682 | cursor_pos : int, optional |
|
1676 | 1683 | The position of the cursor on the input line. |
|
1677 | 1684 | |
|
1678 | 1685 | Returns |
|
1679 | 1686 | ------- |
|
1680 | 1687 | text : string |
|
1681 | 1688 | The actual text that was completed. |
|
1682 | 1689 | |
|
1683 | 1690 | matches : list |
|
1684 | 1691 | A sorted list with all possible completions. |
|
1685 | 1692 | |
|
1686 | 1693 | The optional arguments allow the completion to take more context into |
|
1687 | 1694 | account, and are part of the low-level completion API. |
|
1688 | 1695 | |
|
1689 | 1696 | This is a wrapper around the completion mechanism, similar to what |
|
1690 | 1697 | readline does at the command line when the TAB key is hit. By |
|
1691 | 1698 | exposing it as a method, it can be used by other non-readline |
|
1692 | 1699 | environments (such as GUIs) for text completion. |
|
1693 | 1700 | |
|
1694 | 1701 | Simple usage example: |
|
1695 | 1702 | |
|
1696 | 1703 | In [1]: x = 'hello' |
|
1697 | 1704 | |
|
1698 | 1705 | In [2]: _ip.complete('x.l') |
|
1699 | 1706 | Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip']) |
|
1700 | 1707 | """ |
|
1701 | 1708 | |
|
1702 | 1709 | # Inject names into __builtin__ so we can complete on the added names. |
|
1703 | 1710 | with self.builtin_trap: |
|
1704 | 1711 | return self.Completer.complete(text, line, cursor_pos) |
|
1705 | 1712 | |
|
1706 | 1713 | def set_custom_completer(self, completer, pos=0): |
|
1707 | 1714 | """Adds a new custom completer function. |
|
1708 | 1715 | |
|
1709 | 1716 | The position argument (defaults to 0) is the index in the completers |
|
1710 | 1717 | list where you want the completer to be inserted.""" |
|
1711 | 1718 | |
|
1712 | 1719 | newcomp = types.MethodType(completer,self.Completer) |
|
1713 | 1720 | self.Completer.matchers.insert(pos,newcomp) |
|
1714 | 1721 | |
|
1715 | 1722 | def set_readline_completer(self): |
|
1716 | 1723 | """Reset readline's completer to be our own.""" |
|
1717 | 1724 | self.readline.set_completer(self.Completer.rlcomplete) |
|
1718 | 1725 | |
|
1719 | 1726 | def set_completer_frame(self, frame=None): |
|
1720 | 1727 | """Set the frame of the completer.""" |
|
1721 | 1728 | if frame: |
|
1722 | 1729 | self.Completer.namespace = frame.f_locals |
|
1723 | 1730 | self.Completer.global_namespace = frame.f_globals |
|
1724 | 1731 | else: |
|
1725 | 1732 | self.Completer.namespace = self.user_ns |
|
1726 | 1733 | self.Completer.global_namespace = self.user_global_ns |
|
1727 | 1734 | |
|
1728 | 1735 | #------------------------------------------------------------------------- |
|
1729 | 1736 | # Things related to magics |
|
1730 | 1737 | #------------------------------------------------------------------------- |
|
1731 | 1738 | |
|
1732 | 1739 | def init_magics(self): |
|
1733 | 1740 | # FIXME: Move the color initialization to the DisplayHook, which |
|
1734 | 1741 | # should be split into a prompt manager and displayhook. We probably |
|
1735 | 1742 | # even need a centralize colors management object. |
|
1736 | 1743 | self.magic_colors(self.colors) |
|
1737 | 1744 | # History was moved to a separate module |
|
1738 | 1745 | from . import history |
|
1739 | 1746 | history.init_ipython(self) |
|
1740 | 1747 | |
|
1741 | 1748 | def magic(self,arg_s): |
|
1742 | 1749 | """Call a magic function by name. |
|
1743 | 1750 | |
|
1744 | 1751 | Input: a string containing the name of the magic function to call and |
|
1745 | 1752 | any additional arguments to be passed to the magic. |
|
1746 | 1753 | |
|
1747 | 1754 | magic('name -opt foo bar') is equivalent to typing at the ipython |
|
1748 | 1755 | prompt: |
|
1749 | 1756 | |
|
1750 | 1757 | In[1]: %name -opt foo bar |
|
1751 | 1758 | |
|
1752 | 1759 | To call a magic without arguments, simply use magic('name'). |
|
1753 | 1760 | |
|
1754 | 1761 | This provides a proper Python function to call IPython's magics in any |
|
1755 | 1762 | valid Python code you can type at the interpreter, including loops and |
|
1756 | 1763 | compound statements. |
|
1757 | 1764 | """ |
|
1758 | 1765 | args = arg_s.split(' ',1) |
|
1759 | 1766 | magic_name = args[0] |
|
1760 | 1767 | magic_name = magic_name.lstrip(prefilter.ESC_MAGIC) |
|
1761 | 1768 | |
|
1762 | 1769 | try: |
|
1763 | 1770 | magic_args = args[1] |
|
1764 | 1771 | except IndexError: |
|
1765 | 1772 | magic_args = '' |
|
1766 | 1773 | fn = getattr(self,'magic_'+magic_name,None) |
|
1767 | 1774 | if fn is None: |
|
1768 | 1775 | error("Magic function `%s` not found." % magic_name) |
|
1769 | 1776 | else: |
|
1770 | 1777 | magic_args = self.var_expand(magic_args,1) |
|
1771 | 1778 | # Grab local namespace if we need it: |
|
1772 | 1779 | if getattr(fn, "needs_local_scope", False): |
|
1773 | 1780 | self._magic_locals = sys._getframe(1).f_locals |
|
1774 | 1781 | with nested(self.builtin_trap,): |
|
1775 | 1782 | result = fn(magic_args) |
|
1776 | 1783 | # Ensure we're not keeping object references around: |
|
1777 | 1784 | self._magic_locals = {} |
|
1778 | 1785 | return result |
|
1779 | 1786 | |
|
1780 | 1787 | def define_magic(self, magicname, func): |
|
1781 | 1788 | """Expose own function as magic function for ipython |
|
1782 | 1789 | |
|
1783 | 1790 | def foo_impl(self,parameter_s=''): |
|
1784 | 1791 | 'My very own magic!. (Use docstrings, IPython reads them).' |
|
1785 | 1792 | print 'Magic function. Passed parameter is between < >:' |
|
1786 | 1793 | print '<%s>' % parameter_s |
|
1787 | 1794 | print 'The self object is:',self |
|
1788 | 1795 | |
|
1789 | 1796 | self.define_magic('foo',foo_impl) |
|
1790 | 1797 | """ |
|
1791 | 1798 | |
|
1792 | 1799 | import new |
|
1793 | 1800 | im = types.MethodType(func,self) |
|
1794 | 1801 | old = getattr(self, "magic_" + magicname, None) |
|
1795 | 1802 | setattr(self, "magic_" + magicname, im) |
|
1796 | 1803 | return old |
|
1797 | 1804 | |
|
1798 | 1805 | #------------------------------------------------------------------------- |
|
1799 | 1806 | # Things related to macros |
|
1800 | 1807 | #------------------------------------------------------------------------- |
|
1801 | 1808 | |
|
1802 | 1809 | def define_macro(self, name, themacro): |
|
1803 | 1810 | """Define a new macro |
|
1804 | 1811 | |
|
1805 | 1812 | Parameters |
|
1806 | 1813 | ---------- |
|
1807 | 1814 | name : str |
|
1808 | 1815 | The name of the macro. |
|
1809 | 1816 | themacro : str or Macro |
|
1810 | 1817 | The action to do upon invoking the macro. If a string, a new |
|
1811 | 1818 | Macro object is created by passing the string to it. |
|
1812 | 1819 | """ |
|
1813 | 1820 | |
|
1814 | 1821 | from IPython.core import macro |
|
1815 | 1822 | |
|
1816 | 1823 | if isinstance(themacro, basestring): |
|
1817 | 1824 | themacro = macro.Macro(themacro) |
|
1818 | 1825 | if not isinstance(themacro, macro.Macro): |
|
1819 | 1826 | raise ValueError('A macro must be a string or a Macro instance.') |
|
1820 | 1827 | self.user_ns[name] = themacro |
|
1821 | 1828 | |
|
1822 | 1829 | #------------------------------------------------------------------------- |
|
1823 | 1830 | # Things related to the running of system commands |
|
1824 | 1831 | #------------------------------------------------------------------------- |
|
1825 | 1832 | |
|
1826 | 1833 | def system(self, cmd): |
|
1827 | 1834 | """Call the given cmd in a subprocess. |
|
1828 | 1835 | |
|
1829 | 1836 | Parameters |
|
1830 | 1837 | ---------- |
|
1831 | 1838 | cmd : str |
|
1832 | 1839 | Command to execute (can not end in '&', as bacground processes are |
|
1833 | 1840 | not supported. |
|
1834 | 1841 | """ |
|
1835 | 1842 | # We do not support backgrounding processes because we either use |
|
1836 | 1843 | # pexpect or pipes to read from. Users can always just call |
|
1837 | 1844 | # os.system() if they really want a background process. |
|
1838 | 1845 | if cmd.endswith('&'): |
|
1839 | 1846 | raise OSError("Background processes not supported.") |
|
1840 | 1847 | |
|
1841 | 1848 | return system(self.var_expand(cmd, depth=2)) |
|
1842 | 1849 | |
|
1843 | 1850 | def getoutput(self, cmd, split=True): |
|
1844 | 1851 | """Get output (possibly including stderr) from a subprocess. |
|
1845 | 1852 | |
|
1846 | 1853 | Parameters |
|
1847 | 1854 | ---------- |
|
1848 | 1855 | cmd : str |
|
1849 | 1856 | Command to execute (can not end in '&', as background processes are |
|
1850 | 1857 | not supported. |
|
1851 | 1858 | split : bool, optional |
|
1852 | 1859 | |
|
1853 | 1860 | If True, split the output into an IPython SList. Otherwise, an |
|
1854 | 1861 | IPython LSString is returned. These are objects similar to normal |
|
1855 | 1862 | lists and strings, with a few convenience attributes for easier |
|
1856 | 1863 | manipulation of line-based output. You can use '?' on them for |
|
1857 | 1864 | details. |
|
1858 | 1865 | """ |
|
1859 | 1866 | if cmd.endswith('&'): |
|
1860 | 1867 | raise OSError("Background processes not supported.") |
|
1861 | 1868 | out = getoutput(self.var_expand(cmd, depth=2)) |
|
1862 | 1869 | if split: |
|
1863 | 1870 | out = SList(out.splitlines()) |
|
1864 | 1871 | else: |
|
1865 | 1872 | out = LSString(out) |
|
1866 | 1873 | return out |
|
1867 | 1874 | |
|
1868 | 1875 | #------------------------------------------------------------------------- |
|
1869 | 1876 | # Things related to aliases |
|
1870 | 1877 | #------------------------------------------------------------------------- |
|
1871 | 1878 | |
|
1872 | 1879 | def init_alias(self): |
|
1873 | 1880 | self.alias_manager = AliasManager(shell=self, config=self.config) |
|
1874 | 1881 | self.ns_table['alias'] = self.alias_manager.alias_table, |
|
1875 | 1882 | |
|
1876 | 1883 | #------------------------------------------------------------------------- |
|
1877 | 1884 | # Things related to extensions and plugins |
|
1878 | 1885 | #------------------------------------------------------------------------- |
|
1879 | 1886 | |
|
1880 | 1887 | def init_extension_manager(self): |
|
1881 | 1888 | self.extension_manager = ExtensionManager(shell=self, config=self.config) |
|
1882 | 1889 | |
|
1883 | 1890 | def init_plugin_manager(self): |
|
1884 | 1891 | self.plugin_manager = PluginManager(config=self.config) |
|
1885 | 1892 | |
|
1886 | 1893 | #------------------------------------------------------------------------- |
|
1887 | 1894 | # Things related to payloads |
|
1888 | 1895 | #------------------------------------------------------------------------- |
|
1889 | 1896 | |
|
1890 | 1897 | def init_payload(self): |
|
1891 | 1898 | self.payload_manager = PayloadManager(config=self.config) |
|
1892 | 1899 | |
|
1893 | 1900 | #------------------------------------------------------------------------- |
|
1894 | 1901 | # Things related to the prefilter |
|
1895 | 1902 | #------------------------------------------------------------------------- |
|
1896 | 1903 | |
|
1897 | 1904 | def init_prefilter(self): |
|
1898 | 1905 | self.prefilter_manager = PrefilterManager(shell=self, config=self.config) |
|
1899 | 1906 | # Ultimately this will be refactored in the new interpreter code, but |
|
1900 | 1907 | # for now, we should expose the main prefilter method (there's legacy |
|
1901 | 1908 | # code out there that may rely on this). |
|
1902 | 1909 | self.prefilter = self.prefilter_manager.prefilter_lines |
|
1903 | 1910 | |
|
1904 | 1911 | def auto_rewrite_input(self, cmd): |
|
1905 | 1912 | """Print to the screen the rewritten form of the user's command. |
|
1906 | 1913 | |
|
1907 | 1914 | This shows visual feedback by rewriting input lines that cause |
|
1908 | 1915 | automatic calling to kick in, like:: |
|
1909 | 1916 | |
|
1910 | 1917 | /f x |
|
1911 | 1918 | |
|
1912 | 1919 | into:: |
|
1913 | 1920 | |
|
1914 | 1921 | ------> f(x) |
|
1915 | 1922 | |
|
1916 | 1923 | after the user's input prompt. This helps the user understand that the |
|
1917 | 1924 | input line was transformed automatically by IPython. |
|
1918 | 1925 | """ |
|
1919 | 1926 | rw = self.displayhook.prompt1.auto_rewrite() + cmd |
|
1920 | 1927 | |
|
1921 | 1928 | try: |
|
1922 | 1929 | # plain ascii works better w/ pyreadline, on some machines, so |
|
1923 | 1930 | # we use it and only print uncolored rewrite if we have unicode |
|
1924 | 1931 | rw = str(rw) |
|
1925 | 1932 | print >> IPython.utils.io.Term.cout, rw |
|
1926 | 1933 | except UnicodeEncodeError: |
|
1927 | 1934 | print "------> " + cmd |
|
1928 | 1935 | |
|
1929 | 1936 | #------------------------------------------------------------------------- |
|
1930 | 1937 | # Things related to extracting values/expressions from kernel and user_ns |
|
1931 | 1938 | #------------------------------------------------------------------------- |
|
1932 | 1939 | |
|
1933 | 1940 | def _simple_error(self): |
|
1934 | 1941 | etype, value = sys.exc_info()[:2] |
|
1935 | 1942 | return u'[ERROR] {e.__name__}: {v}'.format(e=etype, v=value) |
|
1936 | 1943 | |
|
1937 | 1944 | def user_variables(self, names): |
|
1938 | 1945 | """Get a list of variable names from the user's namespace. |
|
1939 | 1946 | |
|
1940 | 1947 | Parameters |
|
1941 | 1948 | ---------- |
|
1942 | 1949 | names : list of strings |
|
1943 | 1950 | A list of names of variables to be read from the user namespace. |
|
1944 | 1951 | |
|
1945 | 1952 | Returns |
|
1946 | 1953 | ------- |
|
1947 | 1954 | A dict, keyed by the input names and with the repr() of each value. |
|
1948 | 1955 | """ |
|
1949 | 1956 | out = {} |
|
1950 | 1957 | user_ns = self.user_ns |
|
1951 | 1958 | for varname in names: |
|
1952 | 1959 | try: |
|
1953 | 1960 | value = repr(user_ns[varname]) |
|
1954 | 1961 | except: |
|
1955 | 1962 | value = self._simple_error() |
|
1956 | 1963 | out[varname] = value |
|
1957 | 1964 | return out |
|
1958 | 1965 | |
|
1959 | 1966 | def user_expressions(self, expressions): |
|
1960 | 1967 | """Evaluate a dict of expressions in the user's namespace. |
|
1961 | 1968 | |
|
1962 | 1969 | Parameters |
|
1963 | 1970 | ---------- |
|
1964 | 1971 | expressions : dict |
|
1965 | 1972 | A dict with string keys and string values. The expression values |
|
1966 | 1973 | should be valid Python expressions, each of which will be evaluated |
|
1967 | 1974 | in the user namespace. |
|
1968 | 1975 | |
|
1969 | 1976 | Returns |
|
1970 | 1977 | ------- |
|
1971 | 1978 | A dict, keyed like the input expressions dict, with the repr() of each |
|
1972 | 1979 | value. |
|
1973 | 1980 | """ |
|
1974 | 1981 | out = {} |
|
1975 | 1982 | user_ns = self.user_ns |
|
1976 | 1983 | global_ns = self.user_global_ns |
|
1977 | 1984 | for key, expr in expressions.iteritems(): |
|
1978 | 1985 | try: |
|
1979 | 1986 | value = repr(eval(expr, global_ns, user_ns)) |
|
1980 | 1987 | except: |
|
1981 | 1988 | value = self._simple_error() |
|
1982 | 1989 | out[key] = value |
|
1983 | 1990 | return out |
|
1984 | 1991 | |
|
1985 | 1992 | #------------------------------------------------------------------------- |
|
1986 | 1993 | # Things related to the running of code |
|
1987 | 1994 | #------------------------------------------------------------------------- |
|
1988 | 1995 | |
|
1989 | 1996 | def ex(self, cmd): |
|
1990 | 1997 | """Execute a normal python statement in user namespace.""" |
|
1991 | 1998 | with nested(self.builtin_trap,): |
|
1992 | 1999 | exec cmd in self.user_global_ns, self.user_ns |
|
1993 | 2000 | |
|
1994 | 2001 | def ev(self, expr): |
|
1995 | 2002 | """Evaluate python expression expr in user namespace. |
|
1996 | 2003 | |
|
1997 | 2004 | Returns the result of evaluation |
|
1998 | 2005 | """ |
|
1999 | 2006 | with nested(self.builtin_trap,): |
|
2000 | 2007 | return eval(expr, self.user_global_ns, self.user_ns) |
|
2001 | 2008 | |
|
2002 | 2009 | def safe_execfile(self, fname, *where, **kw): |
|
2003 | 2010 | """A safe version of the builtin execfile(). |
|
2004 | 2011 | |
|
2005 | 2012 | This version will never throw an exception, but instead print |
|
2006 | 2013 | helpful error messages to the screen. This only works on pure |
|
2007 | 2014 | Python files with the .py extension. |
|
2008 | 2015 | |
|
2009 | 2016 | Parameters |
|
2010 | 2017 | ---------- |
|
2011 | 2018 | fname : string |
|
2012 | 2019 | The name of the file to be executed. |
|
2013 | 2020 | where : tuple |
|
2014 | 2021 | One or two namespaces, passed to execfile() as (globals,locals). |
|
2015 | 2022 | If only one is given, it is passed as both. |
|
2016 | 2023 | exit_ignore : bool (False) |
|
2017 | 2024 | If True, then silence SystemExit for non-zero status (it is always |
|
2018 | 2025 | silenced for zero status, as it is so common). |
|
2019 | 2026 | """ |
|
2020 | 2027 | kw.setdefault('exit_ignore', False) |
|
2021 | 2028 | |
|
2022 | 2029 | fname = os.path.abspath(os.path.expanduser(fname)) |
|
2023 | 2030 | # Make sure we have a .py file |
|
2024 | 2031 | if not fname.endswith('.py'): |
|
2025 | 2032 | warn('File must end with .py to be run using execfile: <%s>' % fname) |
|
2026 | 2033 | |
|
2027 | 2034 | # Make sure we can open the file |
|
2028 | 2035 | try: |
|
2029 | 2036 | with open(fname) as thefile: |
|
2030 | 2037 | pass |
|
2031 | 2038 | except: |
|
2032 | 2039 | warn('Could not open file <%s> for safe execution.' % fname) |
|
2033 | 2040 | return |
|
2034 | 2041 | |
|
2035 | 2042 | # Find things also in current directory. This is needed to mimic the |
|
2036 | 2043 | # behavior of running a script from the system command line, where |
|
2037 | 2044 | # Python inserts the script's directory into sys.path |
|
2038 | 2045 | dname = os.path.dirname(fname) |
|
2039 | 2046 | |
|
2040 | 2047 | if isinstance(fname, unicode): |
|
2041 | 2048 | # execfile uses default encoding instead of filesystem encoding |
|
2042 | 2049 | # so unicode filenames will fail |
|
2043 | 2050 | fname = fname.encode(sys.getfilesystemencoding() or sys.getdefaultencoding()) |
|
2044 | 2051 | |
|
2045 | 2052 | with prepended_to_syspath(dname): |
|
2046 | 2053 | try: |
|
2047 | 2054 | execfile(fname,*where) |
|
2048 | 2055 | except SystemExit, status: |
|
2049 | 2056 | # If the call was made with 0 or None exit status (sys.exit(0) |
|
2050 | 2057 | # or sys.exit() ), don't bother showing a traceback, as both of |
|
2051 | 2058 | # these are considered normal by the OS: |
|
2052 | 2059 | # > python -c'import sys;sys.exit(0)'; echo $? |
|
2053 | 2060 | # 0 |
|
2054 | 2061 | # > python -c'import sys;sys.exit()'; echo $? |
|
2055 | 2062 | # 0 |
|
2056 | 2063 | # For other exit status, we show the exception unless |
|
2057 | 2064 | # explicitly silenced, but only in short form. |
|
2058 | 2065 | if status.code not in (0, None) and not kw['exit_ignore']: |
|
2059 | 2066 | self.showtraceback(exception_only=True) |
|
2060 | 2067 | except: |
|
2061 | 2068 | self.showtraceback() |
|
2062 | 2069 | |
|
2063 | 2070 | def safe_execfile_ipy(self, fname): |
|
2064 | 2071 | """Like safe_execfile, but for .ipy files with IPython syntax. |
|
2065 | 2072 | |
|
2066 | 2073 | Parameters |
|
2067 | 2074 | ---------- |
|
2068 | 2075 | fname : str |
|
2069 | 2076 | The name of the file to execute. The filename must have a |
|
2070 | 2077 | .ipy extension. |
|
2071 | 2078 | """ |
|
2072 | 2079 | fname = os.path.abspath(os.path.expanduser(fname)) |
|
2073 | 2080 | |
|
2074 | 2081 | # Make sure we have a .py file |
|
2075 | 2082 | if not fname.endswith('.ipy'): |
|
2076 | 2083 | warn('File must end with .py to be run using execfile: <%s>' % fname) |
|
2077 | 2084 | |
|
2078 | 2085 | # Make sure we can open the file |
|
2079 | 2086 | try: |
|
2080 | 2087 | with open(fname) as thefile: |
|
2081 | 2088 | pass |
|
2082 | 2089 | except: |
|
2083 | 2090 | warn('Could not open file <%s> for safe execution.' % fname) |
|
2084 | 2091 | return |
|
2085 | 2092 | |
|
2086 | 2093 | # Find things also in current directory. This is needed to mimic the |
|
2087 | 2094 | # behavior of running a script from the system command line, where |
|
2088 | 2095 | # Python inserts the script's directory into sys.path |
|
2089 | 2096 | dname = os.path.dirname(fname) |
|
2090 | 2097 | |
|
2091 | 2098 | with prepended_to_syspath(dname): |
|
2092 | 2099 | try: |
|
2093 | 2100 | with open(fname) as thefile: |
|
2094 | 2101 | # self.run_cell currently captures all exceptions |
|
2095 | 2102 | # raised in user code. It would be nice if there were |
|
2096 | 2103 | # versions of runlines, execfile that did raise, so |
|
2097 | 2104 | # we could catch the errors. |
|
2098 | 2105 | self.run_cell(thefile.read(), store_history=False) |
|
2099 | 2106 | except: |
|
2100 | 2107 | self.showtraceback() |
|
2101 | 2108 | warn('Unknown failure executing file: <%s>' % fname) |
|
2102 | 2109 | |
|
2103 | 2110 | def run_cell(self, cell, store_history=True): |
|
2104 | 2111 | """Run a complete IPython cell. |
|
2105 | 2112 | |
|
2106 | 2113 | Parameters |
|
2107 | 2114 | ---------- |
|
2108 | 2115 | cell : str |
|
2109 | 2116 | The code (including IPython code such as %magic functions) to run. |
|
2110 | 2117 | store_history : bool |
|
2111 | 2118 | If True, the raw and translated cell will be stored in IPython's |
|
2112 | 2119 | history. For user code calling back into IPython's machinery, this |
|
2113 | 2120 | should be set to False. |
|
2114 | 2121 | """ |
|
2115 | 2122 | raw_cell = cell |
|
2116 | 2123 | with self.builtin_trap: |
|
2117 | 2124 | cell = self.prefilter_manager.prefilter_lines(cell) |
|
2118 | 2125 | |
|
2119 | 2126 | # Store raw and processed history |
|
2120 | 2127 | if store_history: |
|
2121 | 2128 | self.history_manager.store_inputs(self.execution_count, |
|
2122 | 2129 | cell, raw_cell) |
|
2123 | 2130 | |
|
2124 | 2131 | self.logger.log(cell, raw_cell) |
|
2125 | 2132 | |
|
2126 | 2133 | cell_name = self.compile.cache(cell, self.execution_count) |
|
2127 | 2134 | |
|
2128 | 2135 | with self.display_trap: |
|
2129 | 2136 | try: |
|
2130 | 2137 | code_ast = ast.parse(cell, filename=cell_name) |
|
2131 | 2138 | except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError): |
|
2132 | 2139 | # Case 1 |
|
2133 | 2140 | self.showsyntaxerror() |
|
2134 | 2141 | self.execution_count += 1 |
|
2135 | 2142 | return None |
|
2136 | 2143 | |
|
2137 | 2144 | interactivity = 'last' # Last node to be run interactive |
|
2138 | 2145 | if len(cell.splitlines()) == 1: |
|
2139 | 2146 | interactivity = 'all' # Single line; run fully interactive |
|
2140 | 2147 | |
|
2141 | 2148 | self.run_ast_nodes(code_ast.body, cell_name, interactivity) |
|
2142 | 2149 | |
|
2143 | 2150 | if store_history: |
|
2144 | 2151 | # Write output to the database. Does nothing unless |
|
2145 | 2152 | # history output logging is enabled. |
|
2146 | 2153 | self.history_manager.store_output(self.execution_count) |
|
2147 | 2154 | # Each cell is a *single* input, regardless of how many lines it has |
|
2148 | 2155 | self.execution_count += 1 |
|
2149 | 2156 | |
|
2150 | 2157 | def run_ast_nodes(self, nodelist, cell_name, interactivity='last'): |
|
2151 | 2158 | """Run a sequence of AST nodes. The execution mode depends on the |
|
2152 | 2159 | interactivity parameter. |
|
2153 | 2160 | |
|
2154 | 2161 | Parameters |
|
2155 | 2162 | ---------- |
|
2156 | 2163 | nodelist : list |
|
2157 | 2164 | A sequence of AST nodes to run. |
|
2158 | 2165 | cell_name : str |
|
2159 | 2166 | Will be passed to the compiler as the filename of the cell. Typically |
|
2160 | 2167 | the value returned by ip.compile.cache(cell). |
|
2161 | 2168 | interactivity : str |
|
2162 | 2169 | 'all', 'last' or 'none', specifying which nodes should be run |
|
2163 | 2170 | interactively (displaying output from expressions). Other values for |
|
2164 | 2171 | this parameter will raise a ValueError. |
|
2165 | 2172 | """ |
|
2166 | 2173 | if not nodelist: |
|
2167 | 2174 | return |
|
2168 | 2175 | |
|
2169 | 2176 | if interactivity == 'none': |
|
2170 | 2177 | to_run_exec, to_run_interactive = nodelist, [] |
|
2171 | 2178 | elif interactivity == 'last': |
|
2172 | 2179 | to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:] |
|
2173 | 2180 | elif interactivity == 'all': |
|
2174 | 2181 | to_run_exec, to_run_interactive = [], nodelist |
|
2175 | 2182 | else: |
|
2176 | 2183 | raise ValueError("Interactivity was %r" % interactivity) |
|
2177 | 2184 | |
|
2178 | 2185 | exec_count = self.execution_count |
|
2179 | 2186 | if to_run_exec: |
|
2180 | 2187 | mod = ast.Module(to_run_exec) |
|
2181 | 2188 | self.code_to_run = code = self.compile(mod, cell_name, "exec") |
|
2182 | 2189 | if self.run_code(code) == 1: |
|
2183 | 2190 | return |
|
2184 | 2191 | |
|
2185 | 2192 | if to_run_interactive: |
|
2186 | 2193 | mod = ast.Interactive(to_run_interactive) |
|
2187 | 2194 | self.code_to_run = code = self.compile(mod, cell_name, "single") |
|
2188 | 2195 | return self.run_code(code) |
|
2189 | 2196 | |
|
2190 | 2197 | |
|
2191 | 2198 | # PENDING REMOVAL: this method is slated for deletion, once our new |
|
2192 | 2199 | # input logic has been 100% moved to frontends and is stable. |
|
2193 | 2200 | def runlines(self, lines, clean=False): |
|
2194 | 2201 | """Run a string of one or more lines of source. |
|
2195 | 2202 | |
|
2196 | 2203 | This method is capable of running a string containing multiple source |
|
2197 | 2204 | lines, as if they had been entered at the IPython prompt. Since it |
|
2198 | 2205 | exposes IPython's processing machinery, the given strings can contain |
|
2199 | 2206 | magic calls (%magic), special shell access (!cmd), etc. |
|
2200 | 2207 | """ |
|
2201 | 2208 | |
|
2202 | 2209 | if not isinstance(lines, (list, tuple)): |
|
2203 | 2210 | lines = lines.splitlines() |
|
2204 | 2211 | |
|
2205 | 2212 | if clean: |
|
2206 | 2213 | lines = self._cleanup_ipy_script(lines) |
|
2207 | 2214 | |
|
2208 | 2215 | # We must start with a clean buffer, in case this is run from an |
|
2209 | 2216 | # interactive IPython session (via a magic, for example). |
|
2210 | 2217 | self.reset_buffer() |
|
2211 | 2218 | |
|
2212 | 2219 | # Since we will prefilter all lines, store the user's raw input too |
|
2213 | 2220 | # before we apply any transformations |
|
2214 | 2221 | self.buffer_raw[:] = [ l+'\n' for l in lines] |
|
2215 | 2222 | |
|
2216 | 2223 | more = False |
|
2217 | 2224 | prefilter_lines = self.prefilter_manager.prefilter_lines |
|
2218 | 2225 | with nested(self.builtin_trap, self.display_trap): |
|
2219 | 2226 | for line in lines: |
|
2220 | 2227 | # skip blank lines so we don't mess up the prompt counter, but |
|
2221 | 2228 | # do NOT skip even a blank line if we are in a code block (more |
|
2222 | 2229 | # is true) |
|
2223 | 2230 | |
|
2224 | 2231 | if line or more: |
|
2225 | 2232 | more = self.push_line(prefilter_lines(line, more)) |
|
2226 | 2233 | # IPython's run_source returns None if there was an error |
|
2227 | 2234 | # compiling the code. This allows us to stop processing |
|
2228 | 2235 | # right away, so the user gets the error message at the |
|
2229 | 2236 | # right place. |
|
2230 | 2237 | if more is None: |
|
2231 | 2238 | break |
|
2232 | 2239 | # final newline in case the input didn't have it, so that the code |
|
2233 | 2240 | # actually does get executed |
|
2234 | 2241 | if more: |
|
2235 | 2242 | self.push_line('\n') |
|
2236 | 2243 | |
|
2237 | 2244 | def run_source(self, source, filename=None, |
|
2238 | 2245 | symbol='single', post_execute=True): |
|
2239 | 2246 | """Compile and run some source in the interpreter. |
|
2240 | 2247 | |
|
2241 | 2248 | Arguments are as for compile_command(). |
|
2242 | 2249 | |
|
2243 | 2250 | One several things can happen: |
|
2244 | 2251 | |
|
2245 | 2252 | 1) The input is incorrect; compile_command() raised an |
|
2246 | 2253 | exception (SyntaxError or OverflowError). A syntax traceback |
|
2247 | 2254 | will be printed by calling the showsyntaxerror() method. |
|
2248 | 2255 | |
|
2249 | 2256 | 2) The input is incomplete, and more input is required; |
|
2250 | 2257 | compile_command() returned None. Nothing happens. |
|
2251 | 2258 | |
|
2252 | 2259 | 3) The input is complete; compile_command() returned a code |
|
2253 | 2260 | object. The code is executed by calling self.run_code() (which |
|
2254 | 2261 | also handles run-time exceptions, except for SystemExit). |
|
2255 | 2262 | |
|
2256 | 2263 | The return value is: |
|
2257 | 2264 | |
|
2258 | 2265 | - True in case 2 |
|
2259 | 2266 | |
|
2260 | 2267 | - False in the other cases, unless an exception is raised, where |
|
2261 | 2268 | None is returned instead. This can be used by external callers to |
|
2262 | 2269 | know whether to continue feeding input or not. |
|
2263 | 2270 | |
|
2264 | 2271 | The return value can be used to decide whether to use sys.ps1 or |
|
2265 | 2272 | sys.ps2 to prompt the next line.""" |
|
2266 | 2273 | |
|
2267 | 2274 | # We need to ensure that the source is unicode from here on. |
|
2268 | 2275 | if type(source)==str: |
|
2269 | 2276 | usource = source.decode(self.stdin_encoding) |
|
2270 | 2277 | else: |
|
2271 | 2278 | usource = source |
|
2272 | 2279 | |
|
2273 | 2280 | if False: # dbg |
|
2274 | 2281 | print 'Source:', repr(source) # dbg |
|
2275 | 2282 | print 'USource:', repr(usource) # dbg |
|
2276 | 2283 | print 'type:', type(source) # dbg |
|
2277 | 2284 | print 'encoding', self.stdin_encoding # dbg |
|
2278 | 2285 | |
|
2279 | 2286 | try: |
|
2280 | 2287 | code_name = self.compile.cache(usource, self.execution_count) |
|
2281 | 2288 | code = self.compile(usource, code_name, symbol) |
|
2282 | 2289 | except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError): |
|
2283 | 2290 | # Case 1 |
|
2284 | 2291 | self.showsyntaxerror(filename) |
|
2285 | 2292 | return None |
|
2286 | 2293 | |
|
2287 | 2294 | if code is None: |
|
2288 | 2295 | # Case 2 |
|
2289 | 2296 | return True |
|
2290 | 2297 | |
|
2291 | 2298 | # Case 3 |
|
2292 | 2299 | # We store the code object so that threaded shells and |
|
2293 | 2300 | # custom exception handlers can access all this info if needed. |
|
2294 | 2301 | # The source corresponding to this can be obtained from the |
|
2295 | 2302 | # buffer attribute as '\n'.join(self.buffer). |
|
2296 | 2303 | self.code_to_run = code |
|
2297 | 2304 | # now actually execute the code object |
|
2298 | 2305 | if self.run_code(code, post_execute) == 0: |
|
2299 | 2306 | return False |
|
2300 | 2307 | else: |
|
2301 | 2308 | return None |
|
2302 | 2309 | |
|
2303 | 2310 | # For backwards compatibility |
|
2304 | 2311 | runsource = run_source |
|
2305 | 2312 | |
|
2306 | 2313 | def run_code(self, code_obj, post_execute=True): |
|
2307 | 2314 | """Execute a code object. |
|
2308 | 2315 | |
|
2309 | 2316 | When an exception occurs, self.showtraceback() is called to display a |
|
2310 | 2317 | traceback. |
|
2311 | 2318 | |
|
2312 | 2319 | Return value: a flag indicating whether the code to be run completed |
|
2313 | 2320 | successfully: |
|
2314 | 2321 | |
|
2315 | 2322 | - 0: successful execution. |
|
2316 | 2323 | - 1: an error occurred. |
|
2317 | 2324 | """ |
|
2318 | 2325 | |
|
2319 | 2326 | # Set our own excepthook in case the user code tries to call it |
|
2320 | 2327 | # directly, so that the IPython crash handler doesn't get triggered |
|
2321 | 2328 | old_excepthook,sys.excepthook = sys.excepthook, self.excepthook |
|
2322 | 2329 | |
|
2323 | 2330 | # we save the original sys.excepthook in the instance, in case config |
|
2324 | 2331 | # code (such as magics) needs access to it. |
|
2325 | 2332 | self.sys_excepthook = old_excepthook |
|
2326 | 2333 | outflag = 1 # happens in more places, so it's easier as default |
|
2327 | 2334 | try: |
|
2328 | 2335 | try: |
|
2329 | 2336 | self.hooks.pre_run_code_hook() |
|
2330 | 2337 | #rprint('Running code', repr(code_obj)) # dbg |
|
2331 | 2338 | exec code_obj in self.user_global_ns, self.user_ns |
|
2332 | 2339 | finally: |
|
2333 | 2340 | # Reset our crash handler in place |
|
2334 | 2341 | sys.excepthook = old_excepthook |
|
2335 | 2342 | except SystemExit: |
|
2336 | 2343 | self.reset_buffer() |
|
2337 | 2344 | self.showtraceback(exception_only=True) |
|
2338 | 2345 | warn("To exit: use any of 'exit', 'quit', %Exit or Ctrl-D.", level=1) |
|
2339 | 2346 | except self.custom_exceptions: |
|
2340 | 2347 | etype,value,tb = sys.exc_info() |
|
2341 | 2348 | self.CustomTB(etype,value,tb) |
|
2342 | 2349 | except: |
|
2343 | 2350 | self.showtraceback() |
|
2344 | 2351 | else: |
|
2345 | 2352 | outflag = 0 |
|
2346 | 2353 | if softspace(sys.stdout, 0): |
|
2347 | 2354 | |
|
2348 | 2355 | |
|
2349 | 2356 | # Execute any registered post-execution functions. Here, any errors |
|
2350 | 2357 | # are reported only minimally and just on the terminal, because the |
|
2351 | 2358 | # main exception channel may be occupied with a user traceback. |
|
2352 | 2359 | # FIXME: we need to think this mechanism a little more carefully. |
|
2353 | 2360 | if post_execute: |
|
2354 | 2361 | for func in self._post_execute: |
|
2355 | 2362 | try: |
|
2356 | 2363 | func() |
|
2357 | 2364 | except: |
|
2358 | 2365 | head = '[ ERROR ] Evaluating post_execute function: %s' % \ |
|
2359 | 2366 | func |
|
2360 | 2367 | print >> io.Term.cout, head |
|
2361 | 2368 | print >> io.Term.cout, self._simple_error() |
|
2362 | 2369 | print >> io.Term.cout, 'Removing from post_execute' |
|
2363 | 2370 | self._post_execute.remove(func) |
|
2364 | 2371 | |
|
2365 | 2372 | # Flush out code object which has been run (and source) |
|
2366 | 2373 | self.code_to_run = None |
|
2367 | 2374 | return outflag |
|
2368 | 2375 | |
|
2369 | 2376 | # For backwards compatibility |
|
2370 | 2377 | runcode = run_code |
|
2371 | 2378 | |
|
2372 | 2379 | # PENDING REMOVAL: this method is slated for deletion, once our new |
|
2373 | 2380 | # input logic has been 100% moved to frontends and is stable. |
|
2374 | 2381 | def push_line(self, line): |
|
2375 | 2382 | """Push a line to the interpreter. |
|
2376 | 2383 | |
|
2377 | 2384 | The line should not have a trailing newline; it may have |
|
2378 | 2385 | internal newlines. The line is appended to a buffer and the |
|
2379 | 2386 | interpreter's run_source() method is called with the |
|
2380 | 2387 | concatenated contents of the buffer as source. If this |
|
2381 | 2388 | indicates that the command was executed or invalid, the buffer |
|
2382 | 2389 | is reset; otherwise, the command is incomplete, and the buffer |
|
2383 | 2390 | is left as it was after the line was appended. The return |
|
2384 | 2391 | value is 1 if more input is required, 0 if the line was dealt |
|
2385 | 2392 | with in some way (this is the same as run_source()). |
|
2386 | 2393 | """ |
|
2387 | 2394 | |
|
2388 | 2395 | # autoindent management should be done here, and not in the |
|
2389 | 2396 | # interactive loop, since that one is only seen by keyboard input. We |
|
2390 | 2397 | # need this done correctly even for code run via runlines (which uses |
|
2391 | 2398 | # push). |
|
2392 | 2399 | |
|
2393 | 2400 | #print 'push line: <%s>' % line # dbg |
|
2394 | 2401 | self.buffer.append(line) |
|
2395 | 2402 | full_source = '\n'.join(self.buffer) |
|
2396 | 2403 | more = self.run_source(full_source, self.filename) |
|
2397 | 2404 | if not more: |
|
2398 | 2405 | self.history_manager.store_inputs(self.execution_count, |
|
2399 | 2406 | '\n'.join(self.buffer_raw), full_source) |
|
2400 | 2407 | self.reset_buffer() |
|
2401 | 2408 | self.execution_count += 1 |
|
2402 | 2409 | return more |
|
2403 | 2410 | |
|
2404 | 2411 | def reset_buffer(self): |
|
2405 | 2412 | """Reset the input buffer.""" |
|
2406 | 2413 | self.buffer[:] = [] |
|
2407 | 2414 | self.buffer_raw[:] = [] |
|
2408 | 2415 | self.input_splitter.reset() |
|
2409 | 2416 | |
|
2410 | 2417 | # For backwards compatibility |
|
2411 | 2418 | resetbuffer = reset_buffer |
|
2412 | 2419 | |
|
2413 | 2420 | def _is_secondary_block_start(self, s): |
|
2414 | 2421 | if not s.endswith(':'): |
|
2415 | 2422 | return False |
|
2416 | 2423 | if (s.startswith('elif') or |
|
2417 | 2424 | s.startswith('else') or |
|
2418 | 2425 | s.startswith('except') or |
|
2419 | 2426 | s.startswith('finally')): |
|
2420 | 2427 | return True |
|
2421 | 2428 | |
|
2422 | 2429 | def _cleanup_ipy_script(self, script): |
|
2423 | 2430 | """Make a script safe for self.runlines() |
|
2424 | 2431 | |
|
2425 | 2432 | Currently, IPython is lines based, with blocks being detected by |
|
2426 | 2433 | empty lines. This is a problem for block based scripts that may |
|
2427 | 2434 | not have empty lines after blocks. This script adds those empty |
|
2428 | 2435 | lines to make scripts safe for running in the current line based |
|
2429 | 2436 | IPython. |
|
2430 | 2437 | """ |
|
2431 | 2438 | res = [] |
|
2432 | 2439 | lines = script.splitlines() |
|
2433 | 2440 | level = 0 |
|
2434 | 2441 | |
|
2435 | 2442 | for l in lines: |
|
2436 | 2443 | lstripped = l.lstrip() |
|
2437 | 2444 | stripped = l.strip() |
|
2438 | 2445 | if not stripped: |
|
2439 | 2446 | continue |
|
2440 | 2447 | newlevel = len(l) - len(lstripped) |
|
2441 | 2448 | if level > 0 and newlevel == 0 and \ |
|
2442 | 2449 | not self._is_secondary_block_start(stripped): |
|
2443 | 2450 | # add empty line |
|
2444 | 2451 | res.append('') |
|
2445 | 2452 | res.append(l) |
|
2446 | 2453 | level = newlevel |
|
2447 | 2454 | |
|
2448 | 2455 | return '\n'.join(res) + '\n' |
|
2449 | 2456 | |
|
2450 | 2457 | #------------------------------------------------------------------------- |
|
2451 | 2458 | # Things related to GUI support and pylab |
|
2452 | 2459 | #------------------------------------------------------------------------- |
|
2453 | 2460 | |
|
2454 | 2461 | def enable_pylab(self, gui=None): |
|
2455 | 2462 | raise NotImplementedError('Implement enable_pylab in a subclass') |
|
2456 | 2463 | |
|
2457 | 2464 | #------------------------------------------------------------------------- |
|
2458 | 2465 | # Utilities |
|
2459 | 2466 | #------------------------------------------------------------------------- |
|
2460 | 2467 | |
|
2461 | 2468 | def var_expand(self,cmd,depth=0): |
|
2462 | 2469 | """Expand python variables in a string. |
|
2463 | 2470 | |
|
2464 | 2471 | The depth argument indicates how many frames above the caller should |
|
2465 | 2472 | be walked to look for the local namespace where to expand variables. |
|
2466 | 2473 | |
|
2467 | 2474 | The global namespace for expansion is always the user's interactive |
|
2468 | 2475 | namespace. |
|
2469 | 2476 | """ |
|
2470 | 2477 | res = ItplNS(cmd, self.user_ns, # globals |
|
2471 | 2478 | # Skip our own frame in searching for locals: |
|
2472 | 2479 | sys._getframe(depth+1).f_locals # locals |
|
2473 | 2480 | ) |
|
2474 | 2481 | return str(res).decode(res.codec) |
|
2475 | 2482 | |
|
2476 | 2483 | def mktempfile(self, data=None, prefix='ipython_edit_'): |
|
2477 | 2484 | """Make a new tempfile and return its filename. |
|
2478 | 2485 | |
|
2479 | 2486 | This makes a call to tempfile.mktemp, but it registers the created |
|
2480 | 2487 | filename internally so ipython cleans it up at exit time. |
|
2481 | 2488 | |
|
2482 | 2489 | Optional inputs: |
|
2483 | 2490 | |
|
2484 | 2491 | - data(None): if data is given, it gets written out to the temp file |
|
2485 | 2492 | immediately, and the file is closed again.""" |
|
2486 | 2493 | |
|
2487 | 2494 | filename = tempfile.mktemp('.py', prefix) |
|
2488 | 2495 | self.tempfiles.append(filename) |
|
2489 | 2496 | |
|
2490 | 2497 | if data: |
|
2491 | 2498 | tmp_file = open(filename,'w') |
|
2492 | 2499 | tmp_file.write(data) |
|
2493 | 2500 | tmp_file.close() |
|
2494 | 2501 | return filename |
|
2495 | 2502 | |
|
2496 | 2503 | # TODO: This should be removed when Term is refactored. |
|
2497 | 2504 | def write(self,data): |
|
2498 | 2505 | """Write a string to the default output""" |
|
2499 | 2506 | io.Term.cout.write(data) |
|
2500 | 2507 | |
|
2501 | 2508 | # TODO: This should be removed when Term is refactored. |
|
2502 | 2509 | def write_err(self,data): |
|
2503 | 2510 | """Write a string to the default error output""" |
|
2504 | 2511 | io.Term.cerr.write(data) |
|
2505 | 2512 | |
|
2506 | 2513 | def ask_yes_no(self,prompt,default=True): |
|
2507 | 2514 | if self.quiet: |
|
2508 | 2515 | return True |
|
2509 | 2516 | return ask_yes_no(prompt,default) |
|
2510 | 2517 | |
|
2511 | 2518 | def show_usage(self): |
|
2512 | 2519 | """Show a usage message""" |
|
2513 | 2520 | page.page(IPython.core.usage.interactive_usage) |
|
2514 | 2521 | |
|
2515 | 2522 | def find_user_code(self, target, raw=True): |
|
2516 | 2523 | """Get a code string from history, file, or a string or macro. |
|
2517 | 2524 | |
|
2518 | 2525 | This is mainly used by magic functions. |
|
2519 | 2526 | |
|
2520 | 2527 | Parameters |
|
2521 | 2528 | ---------- |
|
2522 | 2529 | target : str |
|
2523 | 2530 | A string specifying code to retrieve. This will be tried respectively |
|
2524 | 2531 | as: ranges of input history (see %history for syntax), a filename, or |
|
2525 | 2532 | an expression evaluating to a string or Macro in the user namespace. |
|
2526 | 2533 | raw : bool |
|
2527 | 2534 | If true (default), retrieve raw history. Has no effect on the other |
|
2528 | 2535 | retrieval mechanisms. |
|
2529 | 2536 | |
|
2530 | 2537 | Returns |
|
2531 | 2538 | ------- |
|
2532 | 2539 | A string of code. |
|
2533 | 2540 | |
|
2534 | 2541 | ValueError is raised if nothing is found, and TypeError if it evaluates |
|
2535 | 2542 | to an object of another type. In each case, .args[0] is a printable |
|
2536 | 2543 | message. |
|
2537 | 2544 | """ |
|
2538 | 2545 | code = self.extract_input_lines(target, raw=raw) # Grab history |
|
2539 | 2546 | if code: |
|
2540 | 2547 | return code |
|
2541 | 2548 | if os.path.isfile(target): # Read file |
|
2542 | 2549 | return open(target, "r").read() |
|
2543 | 2550 | |
|
2544 | 2551 | try: # User namespace |
|
2545 | 2552 | codeobj = eval(target, self.user_ns) |
|
2546 | 2553 | except Exception: |
|
2547 | 2554 | raise ValueError(("'%s' was not found in history, as a file, nor in" |
|
2548 | 2555 | " the user namespace.") % target) |
|
2549 | 2556 | if isinstance(codeobj, basestring): |
|
2550 | 2557 | return codeobj |
|
2551 | 2558 | elif isinstance(codeobj, Macro): |
|
2552 | 2559 | return codeobj.value |
|
2553 | 2560 | |
|
2554 | 2561 | raise TypeError("%s is neither a string nor a macro." % target, |
|
2555 | 2562 | codeobj) |
|
2556 | 2563 | |
|
2557 | 2564 | #------------------------------------------------------------------------- |
|
2558 | 2565 | # Things related to IPython exiting |
|
2559 | 2566 | #------------------------------------------------------------------------- |
|
2560 | 2567 | def atexit_operations(self): |
|
2561 | 2568 | """This will be executed at the time of exit. |
|
2562 | 2569 | |
|
2563 | 2570 | Cleanup operations and saving of persistent data that is done |
|
2564 | 2571 | unconditionally by IPython should be performed here. |
|
2565 | 2572 | |
|
2566 | 2573 | For things that may depend on startup flags or platform specifics (such |
|
2567 | 2574 | as having readline or not), register a separate atexit function in the |
|
2568 | 2575 | code that has the appropriate information, rather than trying to |
|
2569 | 2576 | clutter |
|
2570 | 2577 | """ |
|
2571 | 2578 | # Cleanup all tempfiles left around |
|
2572 | 2579 | for tfile in self.tempfiles: |
|
2573 | 2580 | try: |
|
2574 | 2581 | os.unlink(tfile) |
|
2575 | 2582 | except OSError: |
|
2576 | 2583 | pass |
|
2577 | 2584 | |
|
2578 | 2585 | # Close the history session (this stores the end time and line count) |
|
2579 | 2586 | self.history_manager.end_session() |
|
2580 | 2587 | |
|
2581 | 2588 | # Clear all user namespaces to release all references cleanly. |
|
2582 | 2589 | self.reset(new_session=False) |
|
2583 | 2590 | |
|
2584 | 2591 | # Run user hooks |
|
2585 | 2592 | self.hooks.shutdown_hook() |
|
2586 | 2593 | |
|
2587 | 2594 | def cleanup(self): |
|
2588 | 2595 | self.restore_sys_module_state() |
|
2589 | 2596 | |
|
2590 | 2597 | |
|
2591 | 2598 | class InteractiveShellABC(object): |
|
2592 | 2599 | """An abstract base class for InteractiveShell.""" |
|
2593 | 2600 | __metaclass__ = abc.ABCMeta |
|
2594 | 2601 | |
|
2595 | 2602 | InteractiveShellABC.register(InteractiveShell) |
@@ -1,3472 +1,3478 b'' | |||
|
1 | 1 | # encoding: utf-8 |
|
2 | 2 | """Magic functions for InteractiveShell. |
|
3 | 3 | """ |
|
4 | 4 | |
|
5 | 5 | #----------------------------------------------------------------------------- |
|
6 | 6 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and |
|
7 | 7 | # Copyright (C) 2001-2007 Fernando Perez <fperez@colorado.edu> |
|
8 | 8 | # Copyright (C) 2008-2009 The IPython Development Team |
|
9 | 9 | |
|
10 | 10 | # Distributed under the terms of the BSD License. The full license is in |
|
11 | 11 | # the file COPYING, distributed as part of this software. |
|
12 | 12 | #----------------------------------------------------------------------------- |
|
13 | 13 | |
|
14 | 14 | #----------------------------------------------------------------------------- |
|
15 | 15 | # Imports |
|
16 | 16 | #----------------------------------------------------------------------------- |
|
17 | 17 | |
|
18 | 18 | import __builtin__ |
|
19 | 19 | import __future__ |
|
20 | 20 | import bdb |
|
21 | 21 | import inspect |
|
22 | 22 | import os |
|
23 | 23 | import sys |
|
24 | 24 | import shutil |
|
25 | 25 | import re |
|
26 | 26 | import time |
|
27 | 27 | import textwrap |
|
28 | 28 | from cStringIO import StringIO |
|
29 | 29 | from getopt import getopt,GetoptError |
|
30 | 30 | from pprint import pformat |
|
31 | 31 | from xmlrpclib import ServerProxy |
|
32 | 32 | |
|
33 | 33 | # cProfile was added in Python2.5 |
|
34 | 34 | try: |
|
35 | 35 | import cProfile as profile |
|
36 | 36 | import pstats |
|
37 | 37 | except ImportError: |
|
38 | 38 | # profile isn't bundled by default in Debian for license reasons |
|
39 | 39 | try: |
|
40 | 40 | import profile,pstats |
|
41 | 41 | except ImportError: |
|
42 | 42 | profile = pstats = None |
|
43 | 43 | |
|
44 | 44 | import IPython |
|
45 | 45 | from IPython.core import debugger, oinspect |
|
46 | 46 | from IPython.core.error import TryNext |
|
47 | 47 | from IPython.core.error import UsageError |
|
48 | 48 | from IPython.core.fakemodule import FakeModule |
|
49 | 49 | from IPython.core.macro import Macro |
|
50 | 50 | from IPython.core import page |
|
51 | 51 | from IPython.core.prefilter import ESC_MAGIC |
|
52 | 52 | from IPython.lib.pylabtools import mpl_runner |
|
53 | 53 | from IPython.external.Itpl import itpl, printpl |
|
54 | 54 | from IPython.testing import decorators as testdec |
|
55 | 55 | from IPython.utils.io import file_read, nlprint |
|
56 | 56 | import IPython.utils.io |
|
57 | 57 | from IPython.utils.path import get_py_filename |
|
58 | 58 | from IPython.utils.process import arg_split, abbrev_cwd |
|
59 | 59 | from IPython.utils.terminal import set_term_title |
|
60 | 60 | from IPython.utils.text import LSString, SList, format_screen |
|
61 | 61 | from IPython.utils.timing import clock, clock2 |
|
62 | 62 | from IPython.utils.warn import warn, error |
|
63 | 63 | from IPython.utils.ipstruct import Struct |
|
64 | 64 | import IPython.utils.generics |
|
65 | 65 | |
|
66 | 66 | #----------------------------------------------------------------------------- |
|
67 | 67 | # Utility functions |
|
68 | 68 | #----------------------------------------------------------------------------- |
|
69 | 69 | |
|
70 | 70 | def on_off(tag): |
|
71 | 71 | """Return an ON/OFF string for a 1/0 input. Simple utility function.""" |
|
72 | 72 | return ['OFF','ON'][tag] |
|
73 | 73 | |
|
74 | 74 | class Bunch: pass |
|
75 | 75 | |
|
76 | 76 | def compress_dhist(dh): |
|
77 | 77 | head, tail = dh[:-10], dh[-10:] |
|
78 | 78 | |
|
79 | 79 | newhead = [] |
|
80 | 80 | done = set() |
|
81 | 81 | for h in head: |
|
82 | 82 | if h in done: |
|
83 | 83 | continue |
|
84 | 84 | newhead.append(h) |
|
85 | 85 | done.add(h) |
|
86 | 86 | |
|
87 | 87 | return newhead + tail |
|
88 | 88 | |
|
89 | 89 | def needs_local_scope(func): |
|
90 | 90 | """Decorator to mark magic functions which need to local scope to run.""" |
|
91 | 91 | func.needs_local_scope = True |
|
92 | 92 | return func |
|
93 | 93 | |
|
94 | 94 | #*************************************************************************** |
|
95 | 95 | # Main class implementing Magic functionality |
|
96 | 96 | |
|
97 | 97 | # XXX - for some odd reason, if Magic is made a new-style class, we get errors |
|
98 | 98 | # on construction of the main InteractiveShell object. Something odd is going |
|
99 | 99 | # on with super() calls, Configurable and the MRO... For now leave it as-is, but |
|
100 | 100 | # eventually this needs to be clarified. |
|
101 | 101 | # BG: This is because InteractiveShell inherits from this, but is itself a |
|
102 | 102 | # Configurable. This messes up the MRO in some way. The fix is that we need to |
|
103 | 103 | # make Magic a configurable that InteractiveShell does not subclass. |
|
104 | 104 | |
|
105 | 105 | class Magic: |
|
106 | 106 | """Magic functions for InteractiveShell. |
|
107 | 107 | |
|
108 | 108 | Shell functions which can be reached as %function_name. All magic |
|
109 | 109 | functions should accept a string, which they can parse for their own |
|
110 | 110 | needs. This can make some functions easier to type, eg `%cd ../` |
|
111 | 111 | vs. `%cd("../")` |
|
112 | 112 | |
|
113 | 113 | ALL definitions MUST begin with the prefix magic_. The user won't need it |
|
114 | 114 | at the command line, but it is is needed in the definition. """ |
|
115 | 115 | |
|
116 | 116 | # class globals |
|
117 | 117 | auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.', |
|
118 | 118 | 'Automagic is ON, % prefix NOT needed for magic functions.'] |
|
119 | 119 | |
|
120 | 120 | #...................................................................... |
|
121 | 121 | # some utility functions |
|
122 | 122 | |
|
123 | 123 | def __init__(self,shell): |
|
124 | 124 | |
|
125 | 125 | self.options_table = {} |
|
126 | 126 | if profile is None: |
|
127 | 127 | self.magic_prun = self.profile_missing_notice |
|
128 | 128 | self.shell = shell |
|
129 | 129 | |
|
130 | 130 | # namespace for holding state we may need |
|
131 | 131 | self._magic_state = Bunch() |
|
132 | 132 | |
|
133 | 133 | def profile_missing_notice(self, *args, **kwargs): |
|
134 | 134 | error("""\ |
|
135 | 135 | The profile module could not be found. It has been removed from the standard |
|
136 | 136 | python packages because of its non-free license. To use profiling, install the |
|
137 | 137 | python-profiler package from non-free.""") |
|
138 | 138 | |
|
139 | 139 | def default_option(self,fn,optstr): |
|
140 | 140 | """Make an entry in the options_table for fn, with value optstr""" |
|
141 | 141 | |
|
142 | 142 | if fn not in self.lsmagic(): |
|
143 | 143 | error("%s is not a magic function" % fn) |
|
144 | 144 | self.options_table[fn] = optstr |
|
145 | 145 | |
|
146 | 146 | def lsmagic(self): |
|
147 | 147 | """Return a list of currently available magic functions. |
|
148 | 148 | |
|
149 | 149 | Gives a list of the bare names after mangling (['ls','cd', ...], not |
|
150 | 150 | ['magic_ls','magic_cd',...]""" |
|
151 | 151 | |
|
152 | 152 | # FIXME. This needs a cleanup, in the way the magics list is built. |
|
153 | 153 | |
|
154 | 154 | # magics in class definition |
|
155 | 155 | class_magic = lambda fn: fn.startswith('magic_') and \ |
|
156 | 156 | callable(Magic.__dict__[fn]) |
|
157 | 157 | # in instance namespace (run-time user additions) |
|
158 | 158 | inst_magic = lambda fn: fn.startswith('magic_') and \ |
|
159 | 159 | callable(self.__dict__[fn]) |
|
160 | 160 | # and bound magics by user (so they can access self): |
|
161 | 161 | inst_bound_magic = lambda fn: fn.startswith('magic_') and \ |
|
162 | 162 | callable(self.__class__.__dict__[fn]) |
|
163 | 163 | magics = filter(class_magic,Magic.__dict__.keys()) + \ |
|
164 | 164 | filter(inst_magic,self.__dict__.keys()) + \ |
|
165 | 165 | filter(inst_bound_magic,self.__class__.__dict__.keys()) |
|
166 | 166 | out = [] |
|
167 | 167 | for fn in set(magics): |
|
168 | 168 | out.append(fn.replace('magic_','',1)) |
|
169 | 169 | out.sort() |
|
170 | 170 | return out |
|
171 | 171 | |
|
172 | 172 | def extract_input_lines(self, range_str, raw=False): |
|
173 | 173 | """Return as a string a set of input history slices. |
|
174 | 174 | |
|
175 | 175 | Inputs: |
|
176 | 176 | |
|
177 | 177 | - range_str: the set of slices is given as a string, like |
|
178 | 178 | "~5/6-~4/2 4:8 9", since this function is for use by magic functions |
|
179 | 179 | which get their arguments as strings. The number before the / is the |
|
180 | 180 | session number: ~n goes n back from the current session. |
|
181 | 181 | |
|
182 | 182 | Optional inputs: |
|
183 | 183 | |
|
184 | 184 | - raw(False): by default, the processed input is used. If this is |
|
185 | 185 | true, the raw input history is used instead. |
|
186 | 186 | |
|
187 | 187 | Note that slices can be called with two notations: |
|
188 | 188 | |
|
189 | 189 | N:M -> standard python form, means including items N...(M-1). |
|
190 | 190 | |
|
191 | 191 | N-M -> include items N..M (closed endpoint).""" |
|
192 | 192 | lines = self.shell.history_manager.\ |
|
193 | 193 | get_range_by_str(range_str, raw=raw) |
|
194 | 194 | return "\n".join(x for _, _, x in lines) |
|
195 | 195 | |
|
196 | 196 | def arg_err(self,func): |
|
197 | 197 | """Print docstring if incorrect arguments were passed""" |
|
198 | 198 | print 'Error in arguments:' |
|
199 | 199 | print oinspect.getdoc(func) |
|
200 | 200 | |
|
201 | 201 | def format_latex(self,strng): |
|
202 | 202 | """Format a string for latex inclusion.""" |
|
203 | 203 | |
|
204 | 204 | # Characters that need to be escaped for latex: |
|
205 | 205 | escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE) |
|
206 | 206 | # Magic command names as headers: |
|
207 | 207 | cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC, |
|
208 | 208 | re.MULTILINE) |
|
209 | 209 | # Magic commands |
|
210 | 210 | cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC, |
|
211 | 211 | re.MULTILINE) |
|
212 | 212 | # Paragraph continue |
|
213 | 213 | par_re = re.compile(r'\\$',re.MULTILINE) |
|
214 | 214 | |
|
215 | 215 | # The "\n" symbol |
|
216 | 216 | newline_re = re.compile(r'\\n') |
|
217 | 217 | |
|
218 | 218 | # Now build the string for output: |
|
219 | 219 | #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng) |
|
220 | 220 | strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:', |
|
221 | 221 | strng) |
|
222 | 222 | strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng) |
|
223 | 223 | strng = par_re.sub(r'\\\\',strng) |
|
224 | 224 | strng = escape_re.sub(r'\\\1',strng) |
|
225 | 225 | strng = newline_re.sub(r'\\textbackslash{}n',strng) |
|
226 | 226 | return strng |
|
227 | 227 | |
|
228 | 228 | def parse_options(self,arg_str,opt_str,*long_opts,**kw): |
|
229 | 229 | """Parse options passed to an argument string. |
|
230 | 230 | |
|
231 | 231 | The interface is similar to that of getopt(), but it returns back a |
|
232 | 232 | Struct with the options as keys and the stripped argument string still |
|
233 | 233 | as a string. |
|
234 | 234 | |
|
235 | 235 | arg_str is quoted as a true sys.argv vector by using shlex.split. |
|
236 | 236 | This allows us to easily expand variables, glob files, quote |
|
237 | 237 | arguments, etc. |
|
238 | 238 | |
|
239 | 239 | Options: |
|
240 | 240 | -mode: default 'string'. If given as 'list', the argument string is |
|
241 | 241 | returned as a list (split on whitespace) instead of a string. |
|
242 | 242 | |
|
243 | 243 | -list_all: put all option values in lists. Normally only options |
|
244 | 244 | appearing more than once are put in a list. |
|
245 | 245 | |
|
246 | 246 | -posix (True): whether to split the input line in POSIX mode or not, |
|
247 | 247 | as per the conventions outlined in the shlex module from the |
|
248 | 248 | standard library.""" |
|
249 | 249 | |
|
250 | 250 | # inject default options at the beginning of the input line |
|
251 | 251 | caller = sys._getframe(1).f_code.co_name.replace('magic_','') |
|
252 | 252 | arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str) |
|
253 | 253 | |
|
254 | 254 | mode = kw.get('mode','string') |
|
255 | 255 | if mode not in ['string','list']: |
|
256 | 256 | raise ValueError,'incorrect mode given: %s' % mode |
|
257 | 257 | # Get options |
|
258 | 258 | list_all = kw.get('list_all',0) |
|
259 | 259 | posix = kw.get('posix', os.name == 'posix') |
|
260 | 260 | |
|
261 | 261 | # Check if we have more than one argument to warrant extra processing: |
|
262 | 262 | odict = {} # Dictionary with options |
|
263 | 263 | args = arg_str.split() |
|
264 | 264 | if len(args) >= 1: |
|
265 | 265 | # If the list of inputs only has 0 or 1 thing in it, there's no |
|
266 | 266 | # need to look for options |
|
267 | 267 | argv = arg_split(arg_str,posix) |
|
268 | 268 | # Do regular option processing |
|
269 | 269 | try: |
|
270 | 270 | opts,args = getopt(argv,opt_str,*long_opts) |
|
271 | 271 | except GetoptError,e: |
|
272 | 272 | raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str, |
|
273 | 273 | " ".join(long_opts))) |
|
274 | 274 | for o,a in opts: |
|
275 | 275 | if o.startswith('--'): |
|
276 | 276 | o = o[2:] |
|
277 | 277 | else: |
|
278 | 278 | o = o[1:] |
|
279 | 279 | try: |
|
280 | 280 | odict[o].append(a) |
|
281 | 281 | except AttributeError: |
|
282 | 282 | odict[o] = [odict[o],a] |
|
283 | 283 | except KeyError: |
|
284 | 284 | if list_all: |
|
285 | 285 | odict[o] = [a] |
|
286 | 286 | else: |
|
287 | 287 | odict[o] = a |
|
288 | 288 | |
|
289 | 289 | # Prepare opts,args for return |
|
290 | 290 | opts = Struct(odict) |
|
291 | 291 | if mode == 'string': |
|
292 | 292 | args = ' '.join(args) |
|
293 | 293 | |
|
294 | 294 | return opts,args |
|
295 | 295 | |
|
296 | 296 | #...................................................................... |
|
297 | 297 | # And now the actual magic functions |
|
298 | 298 | |
|
299 | 299 | # Functions for IPython shell work (vars,funcs, config, etc) |
|
300 | 300 | def magic_lsmagic(self, parameter_s = ''): |
|
301 | 301 | """List currently available magic functions.""" |
|
302 | 302 | mesc = ESC_MAGIC |
|
303 | 303 | print 'Available magic functions:\n'+mesc+\ |
|
304 | 304 | (' '+mesc).join(self.lsmagic()) |
|
305 | 305 | print '\n' + Magic.auto_status[self.shell.automagic] |
|
306 | 306 | return None |
|
307 | 307 | |
|
308 | 308 | def magic_magic(self, parameter_s = ''): |
|
309 | 309 | """Print information about the magic function system. |
|
310 | 310 | |
|
311 | 311 | Supported formats: -latex, -brief, -rest |
|
312 | 312 | """ |
|
313 | 313 | |
|
314 | 314 | mode = '' |
|
315 | 315 | try: |
|
316 | 316 | if parameter_s.split()[0] == '-latex': |
|
317 | 317 | mode = 'latex' |
|
318 | 318 | if parameter_s.split()[0] == '-brief': |
|
319 | 319 | mode = 'brief' |
|
320 | 320 | if parameter_s.split()[0] == '-rest': |
|
321 | 321 | mode = 'rest' |
|
322 | 322 | rest_docs = [] |
|
323 | 323 | except: |
|
324 | 324 | pass |
|
325 | 325 | |
|
326 | 326 | magic_docs = [] |
|
327 | 327 | for fname in self.lsmagic(): |
|
328 | 328 | mname = 'magic_' + fname |
|
329 | 329 | for space in (Magic,self,self.__class__): |
|
330 | 330 | try: |
|
331 | 331 | fn = space.__dict__[mname] |
|
332 | 332 | except KeyError: |
|
333 | 333 | pass |
|
334 | 334 | else: |
|
335 | 335 | break |
|
336 | 336 | if mode == 'brief': |
|
337 | 337 | # only first line |
|
338 | 338 | if fn.__doc__: |
|
339 | 339 | fndoc = fn.__doc__.split('\n',1)[0] |
|
340 | 340 | else: |
|
341 | 341 | fndoc = 'No documentation' |
|
342 | 342 | else: |
|
343 | 343 | if fn.__doc__: |
|
344 | 344 | fndoc = fn.__doc__.rstrip() |
|
345 | 345 | else: |
|
346 | 346 | fndoc = 'No documentation' |
|
347 | 347 | |
|
348 | 348 | |
|
349 | 349 | if mode == 'rest': |
|
350 | 350 | rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(ESC_MAGIC, |
|
351 | 351 | fname,fndoc)) |
|
352 | 352 | |
|
353 | 353 | else: |
|
354 | 354 | magic_docs.append('%s%s:\n\t%s\n' %(ESC_MAGIC, |
|
355 | 355 | fname,fndoc)) |
|
356 | 356 | |
|
357 | 357 | magic_docs = ''.join(magic_docs) |
|
358 | 358 | |
|
359 | 359 | if mode == 'rest': |
|
360 | 360 | return "".join(rest_docs) |
|
361 | 361 | |
|
362 | 362 | if mode == 'latex': |
|
363 | 363 | print self.format_latex(magic_docs) |
|
364 | 364 | return |
|
365 | 365 | else: |
|
366 | 366 | magic_docs = format_screen(magic_docs) |
|
367 | 367 | if mode == 'brief': |
|
368 | 368 | return magic_docs |
|
369 | 369 | |
|
370 | 370 | outmsg = """ |
|
371 | 371 | IPython's 'magic' functions |
|
372 | 372 | =========================== |
|
373 | 373 | |
|
374 | 374 | The magic function system provides a series of functions which allow you to |
|
375 | 375 | control the behavior of IPython itself, plus a lot of system-type |
|
376 | 376 | features. All these functions are prefixed with a % character, but parameters |
|
377 | 377 | are given without parentheses or quotes. |
|
378 | 378 | |
|
379 | 379 | NOTE: If you have 'automagic' enabled (via the command line option or with the |
|
380 | 380 | %automagic function), you don't need to type in the % explicitly. By default, |
|
381 | 381 | IPython ships with automagic on, so you should only rarely need the % escape. |
|
382 | 382 | |
|
383 | 383 | Example: typing '%cd mydir' (without the quotes) changes you working directory |
|
384 | 384 | to 'mydir', if it exists. |
|
385 | 385 | |
|
386 | 386 | You can define your own magic functions to extend the system. See the supplied |
|
387 | 387 | ipythonrc and example-magic.py files for details (in your ipython |
|
388 | 388 | configuration directory, typically $HOME/.config/ipython on Linux or $HOME/.ipython elsewhere). |
|
389 | 389 | |
|
390 | 390 | You can also define your own aliased names for magic functions. In your |
|
391 | 391 | ipythonrc file, placing a line like: |
|
392 | 392 | |
|
393 | 393 | execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile |
|
394 | 394 | |
|
395 | 395 | will define %pf as a new name for %profile. |
|
396 | 396 | |
|
397 | 397 | You can also call magics in code using the magic() function, which IPython |
|
398 | 398 | automatically adds to the builtin namespace. Type 'magic?' for details. |
|
399 | 399 | |
|
400 | 400 | For a list of the available magic functions, use %lsmagic. For a description |
|
401 | 401 | of any of them, type %magic_name?, e.g. '%cd?'. |
|
402 | 402 | |
|
403 | 403 | Currently the magic system has the following functions:\n""" |
|
404 | 404 | |
|
405 | 405 | mesc = ESC_MAGIC |
|
406 | 406 | outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):" |
|
407 | 407 | "\n\n%s%s\n\n%s" % (outmsg, |
|
408 | 408 | magic_docs,mesc,mesc, |
|
409 | 409 | (' '+mesc).join(self.lsmagic()), |
|
410 | 410 | Magic.auto_status[self.shell.automagic] ) ) |
|
411 | 411 | page.page(outmsg) |
|
412 | 412 | |
|
413 | 413 | def magic_automagic(self, parameter_s = ''): |
|
414 | 414 | """Make magic functions callable without having to type the initial %. |
|
415 | 415 | |
|
416 | 416 | Without argumentsl toggles on/off (when off, you must call it as |
|
417 | 417 | %automagic, of course). With arguments it sets the value, and you can |
|
418 | 418 | use any of (case insensitive): |
|
419 | 419 | |
|
420 | 420 | - on,1,True: to activate |
|
421 | 421 | |
|
422 | 422 | - off,0,False: to deactivate. |
|
423 | 423 | |
|
424 | 424 | Note that magic functions have lowest priority, so if there's a |
|
425 | 425 | variable whose name collides with that of a magic fn, automagic won't |
|
426 | 426 | work for that function (you get the variable instead). However, if you |
|
427 | 427 | delete the variable (del var), the previously shadowed magic function |
|
428 | 428 | becomes visible to automagic again.""" |
|
429 | 429 | |
|
430 | 430 | arg = parameter_s.lower() |
|
431 | 431 | if parameter_s in ('on','1','true'): |
|
432 | 432 | self.shell.automagic = True |
|
433 | 433 | elif parameter_s in ('off','0','false'): |
|
434 | 434 | self.shell.automagic = False |
|
435 | 435 | else: |
|
436 | 436 | self.shell.automagic = not self.shell.automagic |
|
437 | 437 | print '\n' + Magic.auto_status[self.shell.automagic] |
|
438 | 438 | |
|
439 | 439 | @testdec.skip_doctest |
|
440 | 440 | def magic_autocall(self, parameter_s = ''): |
|
441 | 441 | """Make functions callable without having to type parentheses. |
|
442 | 442 | |
|
443 | 443 | Usage: |
|
444 | 444 | |
|
445 | 445 | %autocall [mode] |
|
446 | 446 | |
|
447 | 447 | The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the |
|
448 | 448 | value is toggled on and off (remembering the previous state). |
|
449 | 449 | |
|
450 | 450 | In more detail, these values mean: |
|
451 | 451 | |
|
452 | 452 | 0 -> fully disabled |
|
453 | 453 | |
|
454 | 454 | 1 -> active, but do not apply if there are no arguments on the line. |
|
455 | 455 | |
|
456 | 456 | In this mode, you get: |
|
457 | 457 | |
|
458 | 458 | In [1]: callable |
|
459 | 459 | Out[1]: <built-in function callable> |
|
460 | 460 | |
|
461 | 461 | In [2]: callable 'hello' |
|
462 | 462 | ------> callable('hello') |
|
463 | 463 | Out[2]: False |
|
464 | 464 | |
|
465 | 465 | 2 -> Active always. Even if no arguments are present, the callable |
|
466 | 466 | object is called: |
|
467 | 467 | |
|
468 | 468 | In [2]: float |
|
469 | 469 | ------> float() |
|
470 | 470 | Out[2]: 0.0 |
|
471 | 471 | |
|
472 | 472 | Note that even with autocall off, you can still use '/' at the start of |
|
473 | 473 | a line to treat the first argument on the command line as a function |
|
474 | 474 | and add parentheses to it: |
|
475 | 475 | |
|
476 | 476 | In [8]: /str 43 |
|
477 | 477 | ------> str(43) |
|
478 | 478 | Out[8]: '43' |
|
479 | 479 | |
|
480 | 480 | # all-random (note for auto-testing) |
|
481 | 481 | """ |
|
482 | 482 | |
|
483 | 483 | if parameter_s: |
|
484 | 484 | arg = int(parameter_s) |
|
485 | 485 | else: |
|
486 | 486 | arg = 'toggle' |
|
487 | 487 | |
|
488 | 488 | if not arg in (0,1,2,'toggle'): |
|
489 | 489 | error('Valid modes: (0->Off, 1->Smart, 2->Full') |
|
490 | 490 | return |
|
491 | 491 | |
|
492 | 492 | if arg in (0,1,2): |
|
493 | 493 | self.shell.autocall = arg |
|
494 | 494 | else: # toggle |
|
495 | 495 | if self.shell.autocall: |
|
496 | 496 | self._magic_state.autocall_save = self.shell.autocall |
|
497 | 497 | self.shell.autocall = 0 |
|
498 | 498 | else: |
|
499 | 499 | try: |
|
500 | 500 | self.shell.autocall = self._magic_state.autocall_save |
|
501 | 501 | except AttributeError: |
|
502 | 502 | self.shell.autocall = self._magic_state.autocall_save = 1 |
|
503 | 503 | |
|
504 | 504 | print "Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall] |
|
505 | 505 | |
|
506 | 506 | |
|
507 | 507 | def magic_page(self, parameter_s=''): |
|
508 | 508 | """Pretty print the object and display it through a pager. |
|
509 | 509 | |
|
510 | 510 | %page [options] OBJECT |
|
511 | 511 | |
|
512 | 512 | If no object is given, use _ (last output). |
|
513 | 513 | |
|
514 | 514 | Options: |
|
515 | 515 | |
|
516 | 516 | -r: page str(object), don't pretty-print it.""" |
|
517 | 517 | |
|
518 | 518 | # After a function contributed by Olivier Aubert, slightly modified. |
|
519 | 519 | |
|
520 | 520 | # Process options/args |
|
521 | 521 | opts,args = self.parse_options(parameter_s,'r') |
|
522 | 522 | raw = 'r' in opts |
|
523 | 523 | |
|
524 | 524 | oname = args and args or '_' |
|
525 | 525 | info = self._ofind(oname) |
|
526 | 526 | if info['found']: |
|
527 | 527 | txt = (raw and str or pformat)( info['obj'] ) |
|
528 | 528 | page.page(txt) |
|
529 | 529 | else: |
|
530 | 530 | print 'Object `%s` not found' % oname |
|
531 | 531 | |
|
532 | 532 | def magic_profile(self, parameter_s=''): |
|
533 | 533 | """Print your currently active IPython profile.""" |
|
534 | 534 | if self.shell.profile: |
|
535 | 535 | printpl('Current IPython profile: $self.shell.profile.') |
|
536 | 536 | else: |
|
537 | 537 | print 'No profile active.' |
|
538 | 538 | |
|
539 | 539 | def magic_pinfo(self, parameter_s='', namespaces=None): |
|
540 | 540 | """Provide detailed information about an object. |
|
541 | 541 | |
|
542 | 542 | '%pinfo object' is just a synonym for object? or ?object.""" |
|
543 | 543 | |
|
544 | 544 | #print 'pinfo par: <%s>' % parameter_s # dbg |
|
545 | 545 | |
|
546 | 546 | |
|
547 | 547 | # detail_level: 0 -> obj? , 1 -> obj?? |
|
548 | 548 | detail_level = 0 |
|
549 | 549 | # We need to detect if we got called as 'pinfo pinfo foo', which can |
|
550 | 550 | # happen if the user types 'pinfo foo?' at the cmd line. |
|
551 | 551 | pinfo,qmark1,oname,qmark2 = \ |
|
552 | 552 | re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups() |
|
553 | 553 | if pinfo or qmark1 or qmark2: |
|
554 | 554 | detail_level = 1 |
|
555 | 555 | if "*" in oname: |
|
556 | 556 | self.magic_psearch(oname) |
|
557 | 557 | else: |
|
558 | 558 | self.shell._inspect('pinfo', oname, detail_level=detail_level, |
|
559 | 559 | namespaces=namespaces) |
|
560 | 560 | |
|
561 | 561 | def magic_pinfo2(self, parameter_s='', namespaces=None): |
|
562 | 562 | """Provide extra detailed information about an object. |
|
563 | 563 | |
|
564 | 564 | '%pinfo2 object' is just a synonym for object?? or ??object.""" |
|
565 | 565 | self.shell._inspect('pinfo', parameter_s, detail_level=1, |
|
566 | 566 | namespaces=namespaces) |
|
567 | 567 | |
|
568 | 568 | @testdec.skip_doctest |
|
569 | 569 | def magic_pdef(self, parameter_s='', namespaces=None): |
|
570 | 570 | """Print the definition header for any callable object. |
|
571 | 571 | |
|
572 | 572 | If the object is a class, print the constructor information. |
|
573 | 573 | |
|
574 | 574 | Examples |
|
575 | 575 | -------- |
|
576 | 576 | :: |
|
577 | 577 | |
|
578 | 578 | In [3]: %pdef urllib.urlopen |
|
579 | 579 | urllib.urlopen(url, data=None, proxies=None) |
|
580 | 580 | """ |
|
581 | 581 | self._inspect('pdef',parameter_s, namespaces) |
|
582 | 582 | |
|
583 | 583 | def magic_pdoc(self, parameter_s='', namespaces=None): |
|
584 | 584 | """Print the docstring for an object. |
|
585 | 585 | |
|
586 | 586 | If the given object is a class, it will print both the class and the |
|
587 | 587 | constructor docstrings.""" |
|
588 | 588 | self._inspect('pdoc',parameter_s, namespaces) |
|
589 | 589 | |
|
590 | 590 | def magic_psource(self, parameter_s='', namespaces=None): |
|
591 | 591 | """Print (or run through pager) the source code for an object.""" |
|
592 | 592 | self._inspect('psource',parameter_s, namespaces) |
|
593 | 593 | |
|
594 | 594 | def magic_pfile(self, parameter_s=''): |
|
595 | 595 | """Print (or run through pager) the file where an object is defined. |
|
596 | 596 | |
|
597 | 597 | The file opens at the line where the object definition begins. IPython |
|
598 | 598 | will honor the environment variable PAGER if set, and otherwise will |
|
599 | 599 | do its best to print the file in a convenient form. |
|
600 | 600 | |
|
601 | 601 | If the given argument is not an object currently defined, IPython will |
|
602 | 602 | try to interpret it as a filename (automatically adding a .py extension |
|
603 | 603 | if needed). You can thus use %pfile as a syntax highlighting code |
|
604 | 604 | viewer.""" |
|
605 | 605 | |
|
606 | 606 | # first interpret argument as an object name |
|
607 | 607 | out = self._inspect('pfile',parameter_s) |
|
608 | 608 | # if not, try the input as a filename |
|
609 | 609 | if out == 'not found': |
|
610 | 610 | try: |
|
611 | 611 | filename = get_py_filename(parameter_s) |
|
612 | 612 | except IOError,msg: |
|
613 | 613 | print msg |
|
614 | 614 | return |
|
615 | 615 | page.page(self.shell.inspector.format(file(filename).read())) |
|
616 | 616 | |
|
617 | 617 | def magic_psearch(self, parameter_s=''): |
|
618 | 618 | """Search for object in namespaces by wildcard. |
|
619 | 619 | |
|
620 | 620 | %psearch [options] PATTERN [OBJECT TYPE] |
|
621 | 621 | |
|
622 | 622 | Note: ? can be used as a synonym for %psearch, at the beginning or at |
|
623 | 623 | the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the |
|
624 | 624 | rest of the command line must be unchanged (options come first), so |
|
625 | 625 | for example the following forms are equivalent |
|
626 | 626 | |
|
627 | 627 | %psearch -i a* function |
|
628 | 628 | -i a* function? |
|
629 | 629 | ?-i a* function |
|
630 | 630 | |
|
631 | 631 | Arguments: |
|
632 | 632 | |
|
633 | 633 | PATTERN |
|
634 | 634 | |
|
635 | 635 | where PATTERN is a string containing * as a wildcard similar to its |
|
636 | 636 | use in a shell. The pattern is matched in all namespaces on the |
|
637 | 637 | search path. By default objects starting with a single _ are not |
|
638 | 638 | matched, many IPython generated objects have a single |
|
639 | 639 | underscore. The default is case insensitive matching. Matching is |
|
640 | 640 | also done on the attributes of objects and not only on the objects |
|
641 | 641 | in a module. |
|
642 | 642 | |
|
643 | 643 | [OBJECT TYPE] |
|
644 | 644 | |
|
645 | 645 | Is the name of a python type from the types module. The name is |
|
646 | 646 | given in lowercase without the ending type, ex. StringType is |
|
647 | 647 | written string. By adding a type here only objects matching the |
|
648 | 648 | given type are matched. Using all here makes the pattern match all |
|
649 | 649 | types (this is the default). |
|
650 | 650 | |
|
651 | 651 | Options: |
|
652 | 652 | |
|
653 | 653 | -a: makes the pattern match even objects whose names start with a |
|
654 | 654 | single underscore. These names are normally ommitted from the |
|
655 | 655 | search. |
|
656 | 656 | |
|
657 | 657 | -i/-c: make the pattern case insensitive/sensitive. If neither of |
|
658 | 658 | these options is given, the default is read from your ipythonrc |
|
659 | 659 | file. The option name which sets this value is |
|
660 | 660 | 'wildcards_case_sensitive'. If this option is not specified in your |
|
661 | 661 | ipythonrc file, IPython's internal default is to do a case sensitive |
|
662 | 662 | search. |
|
663 | 663 | |
|
664 | 664 | -e/-s NAMESPACE: exclude/search a given namespace. The pattern you |
|
665 | 665 | specifiy can be searched in any of the following namespaces: |
|
666 | 666 | 'builtin', 'user', 'user_global','internal', 'alias', where |
|
667 | 667 | 'builtin' and 'user' are the search defaults. Note that you should |
|
668 | 668 | not use quotes when specifying namespaces. |
|
669 | 669 | |
|
670 | 670 | 'Builtin' contains the python module builtin, 'user' contains all |
|
671 | 671 | user data, 'alias' only contain the shell aliases and no python |
|
672 | 672 | objects, 'internal' contains objects used by IPython. The |
|
673 | 673 | 'user_global' namespace is only used by embedded IPython instances, |
|
674 | 674 | and it contains module-level globals. You can add namespaces to the |
|
675 | 675 | search with -s or exclude them with -e (these options can be given |
|
676 | 676 | more than once). |
|
677 | 677 | |
|
678 | 678 | Examples: |
|
679 | 679 | |
|
680 | 680 | %psearch a* -> objects beginning with an a |
|
681 | 681 | %psearch -e builtin a* -> objects NOT in the builtin space starting in a |
|
682 | 682 | %psearch a* function -> all functions beginning with an a |
|
683 | 683 | %psearch re.e* -> objects beginning with an e in module re |
|
684 | 684 | %psearch r*.e* -> objects that start with e in modules starting in r |
|
685 | 685 | %psearch r*.* string -> all strings in modules beginning with r |
|
686 | 686 | |
|
687 | 687 | Case sensitve search: |
|
688 | 688 | |
|
689 | 689 | %psearch -c a* list all object beginning with lower case a |
|
690 | 690 | |
|
691 | 691 | Show objects beginning with a single _: |
|
692 | 692 | |
|
693 | 693 | %psearch -a _* list objects beginning with a single underscore""" |
|
694 | 694 | try: |
|
695 | 695 | parameter_s = parameter_s.encode('ascii') |
|
696 | 696 | except UnicodeEncodeError: |
|
697 | 697 | print 'Python identifiers can only contain ascii characters.' |
|
698 | 698 | return |
|
699 | 699 | |
|
700 | 700 | # default namespaces to be searched |
|
701 | 701 | def_search = ['user','builtin'] |
|
702 | 702 | |
|
703 | 703 | # Process options/args |
|
704 | 704 | opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True) |
|
705 | 705 | opt = opts.get |
|
706 | 706 | shell = self.shell |
|
707 | 707 | psearch = shell.inspector.psearch |
|
708 | 708 | |
|
709 | 709 | # select case options |
|
710 | 710 | if opts.has_key('i'): |
|
711 | 711 | ignore_case = True |
|
712 | 712 | elif opts.has_key('c'): |
|
713 | 713 | ignore_case = False |
|
714 | 714 | else: |
|
715 | 715 | ignore_case = not shell.wildcards_case_sensitive |
|
716 | 716 | |
|
717 | 717 | # Build list of namespaces to search from user options |
|
718 | 718 | def_search.extend(opt('s',[])) |
|
719 | 719 | ns_exclude = ns_exclude=opt('e',[]) |
|
720 | 720 | ns_search = [nm for nm in def_search if nm not in ns_exclude] |
|
721 | 721 | |
|
722 | 722 | # Call the actual search |
|
723 | 723 | try: |
|
724 | 724 | psearch(args,shell.ns_table,ns_search, |
|
725 | 725 | show_all=opt('a'),ignore_case=ignore_case) |
|
726 | 726 | except: |
|
727 | 727 | shell.showtraceback() |
|
728 | 728 | |
|
729 | 729 | @testdec.skip_doctest |
|
730 | 730 | def magic_who_ls(self, parameter_s=''): |
|
731 | 731 | """Return a sorted list of all interactive variables. |
|
732 | 732 | |
|
733 | 733 | If arguments are given, only variables of types matching these |
|
734 | 734 | arguments are returned. |
|
735 | 735 | |
|
736 | 736 | Examples |
|
737 | 737 | -------- |
|
738 | 738 | |
|
739 | 739 | Define two variables and list them with who_ls:: |
|
740 | 740 | |
|
741 | 741 | In [1]: alpha = 123 |
|
742 | 742 | |
|
743 | 743 | In [2]: beta = 'test' |
|
744 | 744 | |
|
745 | 745 | In [3]: %who_ls |
|
746 | 746 | Out[3]: ['alpha', 'beta'] |
|
747 | 747 | |
|
748 | 748 | In [4]: %who_ls int |
|
749 | 749 | Out[4]: ['alpha'] |
|
750 | 750 | |
|
751 | 751 | In [5]: %who_ls str |
|
752 | 752 | Out[5]: ['beta'] |
|
753 | 753 | """ |
|
754 | 754 | |
|
755 | 755 | user_ns = self.shell.user_ns |
|
756 | 756 | internal_ns = self.shell.internal_ns |
|
757 | 757 | user_ns_hidden = self.shell.user_ns_hidden |
|
758 | 758 | out = [ i for i in user_ns |
|
759 | 759 | if not i.startswith('_') \ |
|
760 | 760 | and not (i in internal_ns or i in user_ns_hidden) ] |
|
761 | 761 | |
|
762 | 762 | typelist = parameter_s.split() |
|
763 | 763 | if typelist: |
|
764 | 764 | typeset = set(typelist) |
|
765 | 765 | out = [i for i in out if type(user_ns[i]).__name__ in typeset] |
|
766 | 766 | |
|
767 | 767 | out.sort() |
|
768 | 768 | return out |
|
769 | 769 | |
|
770 | 770 | @testdec.skip_doctest |
|
771 | 771 | def magic_who(self, parameter_s=''): |
|
772 | 772 | """Print all interactive variables, with some minimal formatting. |
|
773 | 773 | |
|
774 | 774 | If any arguments are given, only variables whose type matches one of |
|
775 | 775 | these are printed. For example: |
|
776 | 776 | |
|
777 | 777 | %who function str |
|
778 | 778 | |
|
779 | 779 | will only list functions and strings, excluding all other types of |
|
780 | 780 | variables. To find the proper type names, simply use type(var) at a |
|
781 | 781 | command line to see how python prints type names. For example: |
|
782 | 782 | |
|
783 | 783 | In [1]: type('hello')\\ |
|
784 | 784 | Out[1]: <type 'str'> |
|
785 | 785 | |
|
786 | 786 | indicates that the type name for strings is 'str'. |
|
787 | 787 | |
|
788 | 788 | %who always excludes executed names loaded through your configuration |
|
789 | 789 | file and things which are internal to IPython. |
|
790 | 790 | |
|
791 | 791 | This is deliberate, as typically you may load many modules and the |
|
792 | 792 | purpose of %who is to show you only what you've manually defined. |
|
793 | 793 | |
|
794 | 794 | Examples |
|
795 | 795 | -------- |
|
796 | 796 | |
|
797 | 797 | Define two variables and list them with who:: |
|
798 | 798 | |
|
799 | 799 | In [1]: alpha = 123 |
|
800 | 800 | |
|
801 | 801 | In [2]: beta = 'test' |
|
802 | 802 | |
|
803 | 803 | In [3]: %who |
|
804 | 804 | alpha beta |
|
805 | 805 | |
|
806 | 806 | In [4]: %who int |
|
807 | 807 | alpha |
|
808 | 808 | |
|
809 | 809 | In [5]: %who str |
|
810 | 810 | beta |
|
811 | 811 | """ |
|
812 | 812 | |
|
813 | 813 | varlist = self.magic_who_ls(parameter_s) |
|
814 | 814 | if not varlist: |
|
815 | 815 | if parameter_s: |
|
816 | 816 | print 'No variables match your requested type.' |
|
817 | 817 | else: |
|
818 | 818 | print 'Interactive namespace is empty.' |
|
819 | 819 | return |
|
820 | 820 | |
|
821 | 821 | # if we have variables, move on... |
|
822 | 822 | count = 0 |
|
823 | 823 | for i in varlist: |
|
824 | 824 | print i+'\t', |
|
825 | 825 | count += 1 |
|
826 | 826 | if count > 8: |
|
827 | 827 | count = 0 |
|
828 | 828 | |
|
829 | 829 | |
|
830 | 830 | |
|
831 | 831 | @testdec.skip_doctest |
|
832 | 832 | def magic_whos(self, parameter_s=''): |
|
833 | 833 | """Like %who, but gives some extra information about each variable. |
|
834 | 834 | |
|
835 | 835 | The same type filtering of %who can be applied here. |
|
836 | 836 | |
|
837 | 837 | For all variables, the type is printed. Additionally it prints: |
|
838 | 838 | |
|
839 | 839 | - For {},[],(): their length. |
|
840 | 840 | |
|
841 | 841 | - For numpy arrays, a summary with shape, number of |
|
842 | 842 | elements, typecode and size in memory. |
|
843 | 843 | |
|
844 | 844 | - Everything else: a string representation, snipping their middle if |
|
845 | 845 | too long. |
|
846 | 846 | |
|
847 | 847 | Examples |
|
848 | 848 | -------- |
|
849 | 849 | |
|
850 | 850 | Define two variables and list them with whos:: |
|
851 | 851 | |
|
852 | 852 | In [1]: alpha = 123 |
|
853 | 853 | |
|
854 | 854 | In [2]: beta = 'test' |
|
855 | 855 | |
|
856 | 856 | In [3]: %whos |
|
857 | 857 | Variable Type Data/Info |
|
858 | 858 | -------------------------------- |
|
859 | 859 | alpha int 123 |
|
860 | 860 | beta str test |
|
861 | 861 | """ |
|
862 | 862 | |
|
863 | 863 | varnames = self.magic_who_ls(parameter_s) |
|
864 | 864 | if not varnames: |
|
865 | 865 | if parameter_s: |
|
866 | 866 | print 'No variables match your requested type.' |
|
867 | 867 | else: |
|
868 | 868 | print 'Interactive namespace is empty.' |
|
869 | 869 | return |
|
870 | 870 | |
|
871 | 871 | # if we have variables, move on... |
|
872 | 872 | |
|
873 | 873 | # for these types, show len() instead of data: |
|
874 | 874 | seq_types = ['dict', 'list', 'tuple'] |
|
875 | 875 | |
|
876 | 876 | # for numpy/Numeric arrays, display summary info |
|
877 | 877 | try: |
|
878 | 878 | import numpy |
|
879 | 879 | except ImportError: |
|
880 | 880 | ndarray_type = None |
|
881 | 881 | else: |
|
882 | 882 | ndarray_type = numpy.ndarray.__name__ |
|
883 | 883 | try: |
|
884 | 884 | import Numeric |
|
885 | 885 | except ImportError: |
|
886 | 886 | array_type = None |
|
887 | 887 | else: |
|
888 | 888 | array_type = Numeric.ArrayType.__name__ |
|
889 | 889 | |
|
890 | 890 | # Find all variable names and types so we can figure out column sizes |
|
891 | 891 | def get_vars(i): |
|
892 | 892 | return self.shell.user_ns[i] |
|
893 | 893 | |
|
894 | 894 | # some types are well known and can be shorter |
|
895 | 895 | abbrevs = {'IPython.core.macro.Macro' : 'Macro'} |
|
896 | 896 | def type_name(v): |
|
897 | 897 | tn = type(v).__name__ |
|
898 | 898 | return abbrevs.get(tn,tn) |
|
899 | 899 | |
|
900 | 900 | varlist = map(get_vars,varnames) |
|
901 | 901 | |
|
902 | 902 | typelist = [] |
|
903 | 903 | for vv in varlist: |
|
904 | 904 | tt = type_name(vv) |
|
905 | 905 | |
|
906 | 906 | if tt=='instance': |
|
907 | 907 | typelist.append( abbrevs.get(str(vv.__class__), |
|
908 | 908 | str(vv.__class__))) |
|
909 | 909 | else: |
|
910 | 910 | typelist.append(tt) |
|
911 | 911 | |
|
912 | 912 | # column labels and # of spaces as separator |
|
913 | 913 | varlabel = 'Variable' |
|
914 | 914 | typelabel = 'Type' |
|
915 | 915 | datalabel = 'Data/Info' |
|
916 | 916 | colsep = 3 |
|
917 | 917 | # variable format strings |
|
918 | 918 | vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)" |
|
919 | 919 | vfmt_short = '$vstr[:25]<...>$vstr[-25:]' |
|
920 | 920 | aformat = "%s: %s elems, type `%s`, %s bytes" |
|
921 | 921 | # find the size of the columns to format the output nicely |
|
922 | 922 | varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep |
|
923 | 923 | typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep |
|
924 | 924 | # table header |
|
925 | 925 | print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \ |
|
926 | 926 | ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1) |
|
927 | 927 | # and the table itself |
|
928 | 928 | kb = 1024 |
|
929 | 929 | Mb = 1048576 # kb**2 |
|
930 | 930 | for vname,var,vtype in zip(varnames,varlist,typelist): |
|
931 | 931 | print itpl(vformat), |
|
932 | 932 | if vtype in seq_types: |
|
933 | 933 | print "n="+str(len(var)) |
|
934 | 934 | elif vtype in [array_type,ndarray_type]: |
|
935 | 935 | vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1] |
|
936 | 936 | if vtype==ndarray_type: |
|
937 | 937 | # numpy |
|
938 | 938 | vsize = var.size |
|
939 | 939 | vbytes = vsize*var.itemsize |
|
940 | 940 | vdtype = var.dtype |
|
941 | 941 | else: |
|
942 | 942 | # Numeric |
|
943 | 943 | vsize = Numeric.size(var) |
|
944 | 944 | vbytes = vsize*var.itemsize() |
|
945 | 945 | vdtype = var.typecode() |
|
946 | 946 | |
|
947 | 947 | if vbytes < 100000: |
|
948 | 948 | print aformat % (vshape,vsize,vdtype,vbytes) |
|
949 | 949 | else: |
|
950 | 950 | print aformat % (vshape,vsize,vdtype,vbytes), |
|
951 | 951 | if vbytes < Mb: |
|
952 | 952 | print '(%s kb)' % (vbytes/kb,) |
|
953 | 953 | else: |
|
954 | 954 | print '(%s Mb)' % (vbytes/Mb,) |
|
955 | 955 | else: |
|
956 | 956 | try: |
|
957 | 957 | vstr = str(var) |
|
958 | 958 | except UnicodeEncodeError: |
|
959 | 959 | vstr = unicode(var).encode(sys.getdefaultencoding(), |
|
960 | 960 | 'backslashreplace') |
|
961 | 961 | vstr = vstr.replace('\n','\\n') |
|
962 | 962 | if len(vstr) < 50: |
|
963 | 963 | print vstr |
|
964 | 964 | else: |
|
965 | 965 | printpl(vfmt_short) |
|
966 | 966 | |
|
967 | 967 | def magic_reset(self, parameter_s=''): |
|
968 | 968 | """Resets the namespace by removing all names defined by the user. |
|
969 | 969 | |
|
970 | Input/Output history are left around in case you need them. | |
|
971 | ||
|
972 | 970 | Parameters |
|
973 | 971 | ---------- |
|
974 | 972 | -f : force reset without asking for confirmation. |
|
975 | ||
|
973 | ||
|
974 | -s : 'Soft' reset: Only clears your namespace, leaving history intact. | |
|
975 | References to objects may be kept. By default (without this option), | |
|
976 | we do a 'hard' reset, giving you a new session and removing all | |
|
977 | references to objects from the current session. | |
|
978 | ||
|
976 | 979 | Examples |
|
977 | 980 | -------- |
|
978 | 981 | In [6]: a = 1 |
|
979 | 982 | |
|
980 | 983 | In [7]: a |
|
981 | 984 | Out[7]: 1 |
|
982 | 985 | |
|
983 | 986 | In [8]: 'a' in _ip.user_ns |
|
984 | 987 | Out[8]: True |
|
985 | 988 | |
|
986 | 989 | In [9]: %reset -f |
|
987 | 990 | |
|
988 |
In [1 |
|
|
989 |
Out[1 |
|
|
991 | In [1]: 'a' in _ip.user_ns | |
|
992 | Out[1]: False | |
|
990 | 993 | """ |
|
991 | ||
|
992 | if parameter_s == '-f': | |
|
994 | opts, args = self.parse_options(parameter_s,'sh') | |
|
995 | if 'f' in opts: | |
|
993 | 996 | ans = True |
|
994 | 997 | else: |
|
995 | 998 | ans = self.shell.ask_yes_no( |
|
996 | 999 | "Once deleted, variables cannot be recovered. Proceed (y/[n])? ") |
|
997 | 1000 | if not ans: |
|
998 | 1001 | print 'Nothing done.' |
|
999 | 1002 | return |
|
1000 | user_ns = self.shell.user_ns | |
|
1001 | for i in self.magic_who_ls(): | |
|
1002 | del(user_ns[i]) | |
|
1003 | ||
|
1004 | if 's' in opts: # Soft reset | |
|
1005 | user_ns = self.shell.user_ns | |
|
1006 | for i in self.magic_who_ls(): | |
|
1007 | del(user_ns[i]) | |
|
1003 | 1008 | |
|
1004 | # Also flush the private list of module references kept for script | |
|
1005 | # execution protection | |
|
1006 | self.shell.clear_main_mod_cache() | |
|
1009 | else: # Hard reset | |
|
1010 | self.shell.reset(new_session = True) | |
|
1011 | ||
|
1012 | ||
|
1007 | 1013 | |
|
1008 | 1014 | def magic_reset_selective(self, parameter_s=''): |
|
1009 | 1015 | """Resets the namespace by removing names defined by the user. |
|
1010 | 1016 | |
|
1011 | 1017 | Input/Output history are left around in case you need them. |
|
1012 | 1018 | |
|
1013 | 1019 | %reset_selective [-f] regex |
|
1014 | 1020 | |
|
1015 | 1021 | No action is taken if regex is not included |
|
1016 | 1022 | |
|
1017 | 1023 | Options |
|
1018 | 1024 | -f : force reset without asking for confirmation. |
|
1019 | 1025 | |
|
1020 | 1026 | Examples |
|
1021 | 1027 | -------- |
|
1022 | 1028 | |
|
1023 | 1029 | We first fully reset the namespace so your output looks identical to |
|
1024 | 1030 | this example for pedagogical reasons; in practice you do not need a |
|
1025 | 1031 | full reset. |
|
1026 | 1032 | |
|
1027 | 1033 | In [1]: %reset -f |
|
1028 | 1034 | |
|
1029 | 1035 | Now, with a clean namespace we can make a few variables and use |
|
1030 | 1036 | %reset_selective to only delete names that match our regexp: |
|
1031 | 1037 | |
|
1032 | 1038 | In [2]: a=1; b=2; c=3; b1m=4; b2m=5; b3m=6; b4m=7; b2s=8 |
|
1033 | 1039 | |
|
1034 | 1040 | In [3]: who_ls |
|
1035 | 1041 | Out[3]: ['a', 'b', 'b1m', 'b2m', 'b2s', 'b3m', 'b4m', 'c'] |
|
1036 | 1042 | |
|
1037 | 1043 | In [4]: %reset_selective -f b[2-3]m |
|
1038 | 1044 | |
|
1039 | 1045 | In [5]: who_ls |
|
1040 | 1046 | Out[5]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c'] |
|
1041 | 1047 | |
|
1042 | 1048 | In [6]: %reset_selective -f d |
|
1043 | 1049 | |
|
1044 | 1050 | In [7]: who_ls |
|
1045 | 1051 | Out[7]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c'] |
|
1046 | 1052 | |
|
1047 | 1053 | In [8]: %reset_selective -f c |
|
1048 | 1054 | |
|
1049 | 1055 | In [9]: who_ls |
|
1050 | 1056 | Out[9]: ['a', 'b', 'b1m', 'b2s', 'b4m'] |
|
1051 | 1057 | |
|
1052 | 1058 | In [10]: %reset_selective -f b |
|
1053 | 1059 | |
|
1054 | 1060 | In [11]: who_ls |
|
1055 | 1061 | Out[11]: ['a'] |
|
1056 | 1062 | """ |
|
1057 | 1063 | |
|
1058 | 1064 | opts, regex = self.parse_options(parameter_s,'f') |
|
1059 | 1065 | |
|
1060 | 1066 | if opts.has_key('f'): |
|
1061 | 1067 | ans = True |
|
1062 | 1068 | else: |
|
1063 | 1069 | ans = self.shell.ask_yes_no( |
|
1064 | 1070 | "Once deleted, variables cannot be recovered. Proceed (y/[n])? ") |
|
1065 | 1071 | if not ans: |
|
1066 | 1072 | print 'Nothing done.' |
|
1067 | 1073 | return |
|
1068 | 1074 | user_ns = self.shell.user_ns |
|
1069 | 1075 | if not regex: |
|
1070 | 1076 | print 'No regex pattern specified. Nothing done.' |
|
1071 | 1077 | return |
|
1072 | 1078 | else: |
|
1073 | 1079 | try: |
|
1074 | 1080 | m = re.compile(regex) |
|
1075 | 1081 | except TypeError: |
|
1076 | 1082 | raise TypeError('regex must be a string or compiled pattern') |
|
1077 | 1083 | for i in self.magic_who_ls(): |
|
1078 | 1084 | if m.search(i): |
|
1079 | 1085 | del(user_ns[i]) |
|
1080 | 1086 | |
|
1081 | 1087 | def magic_logstart(self,parameter_s=''): |
|
1082 | 1088 | """Start logging anywhere in a session. |
|
1083 | 1089 | |
|
1084 | 1090 | %logstart [-o|-r|-t] [log_name [log_mode]] |
|
1085 | 1091 | |
|
1086 | 1092 | If no name is given, it defaults to a file named 'ipython_log.py' in your |
|
1087 | 1093 | current directory, in 'rotate' mode (see below). |
|
1088 | 1094 | |
|
1089 | 1095 | '%logstart name' saves to file 'name' in 'backup' mode. It saves your |
|
1090 | 1096 | history up to that point and then continues logging. |
|
1091 | 1097 | |
|
1092 | 1098 | %logstart takes a second optional parameter: logging mode. This can be one |
|
1093 | 1099 | of (note that the modes are given unquoted):\\ |
|
1094 | 1100 | append: well, that says it.\\ |
|
1095 | 1101 | backup: rename (if exists) to name~ and start name.\\ |
|
1096 | 1102 | global: single logfile in your home dir, appended to.\\ |
|
1097 | 1103 | over : overwrite existing log.\\ |
|
1098 | 1104 | rotate: create rotating logs name.1~, name.2~, etc. |
|
1099 | 1105 | |
|
1100 | 1106 | Options: |
|
1101 | 1107 | |
|
1102 | 1108 | -o: log also IPython's output. In this mode, all commands which |
|
1103 | 1109 | generate an Out[NN] prompt are recorded to the logfile, right after |
|
1104 | 1110 | their corresponding input line. The output lines are always |
|
1105 | 1111 | prepended with a '#[Out]# ' marker, so that the log remains valid |
|
1106 | 1112 | Python code. |
|
1107 | 1113 | |
|
1108 | 1114 | Since this marker is always the same, filtering only the output from |
|
1109 | 1115 | a log is very easy, using for example a simple awk call: |
|
1110 | 1116 | |
|
1111 | 1117 | awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py |
|
1112 | 1118 | |
|
1113 | 1119 | -r: log 'raw' input. Normally, IPython's logs contain the processed |
|
1114 | 1120 | input, so that user lines are logged in their final form, converted |
|
1115 | 1121 | into valid Python. For example, %Exit is logged as |
|
1116 | 1122 | '_ip.magic("Exit"). If the -r flag is given, all input is logged |
|
1117 | 1123 | exactly as typed, with no transformations applied. |
|
1118 | 1124 | |
|
1119 | 1125 | -t: put timestamps before each input line logged (these are put in |
|
1120 | 1126 | comments).""" |
|
1121 | 1127 | |
|
1122 | 1128 | opts,par = self.parse_options(parameter_s,'ort') |
|
1123 | 1129 | log_output = 'o' in opts |
|
1124 | 1130 | log_raw_input = 'r' in opts |
|
1125 | 1131 | timestamp = 't' in opts |
|
1126 | 1132 | |
|
1127 | 1133 | logger = self.shell.logger |
|
1128 | 1134 | |
|
1129 | 1135 | # if no args are given, the defaults set in the logger constructor by |
|
1130 | 1136 | # ipytohn remain valid |
|
1131 | 1137 | if par: |
|
1132 | 1138 | try: |
|
1133 | 1139 | logfname,logmode = par.split() |
|
1134 | 1140 | except: |
|
1135 | 1141 | logfname = par |
|
1136 | 1142 | logmode = 'backup' |
|
1137 | 1143 | else: |
|
1138 | 1144 | logfname = logger.logfname |
|
1139 | 1145 | logmode = logger.logmode |
|
1140 | 1146 | # put logfname into rc struct as if it had been called on the command |
|
1141 | 1147 | # line, so it ends up saved in the log header Save it in case we need |
|
1142 | 1148 | # to restore it... |
|
1143 | 1149 | old_logfile = self.shell.logfile |
|
1144 | 1150 | if logfname: |
|
1145 | 1151 | logfname = os.path.expanduser(logfname) |
|
1146 | 1152 | self.shell.logfile = logfname |
|
1147 | 1153 | |
|
1148 | 1154 | loghead = '# IPython log file\n\n' |
|
1149 | 1155 | try: |
|
1150 | 1156 | started = logger.logstart(logfname,loghead,logmode, |
|
1151 | 1157 | log_output,timestamp,log_raw_input) |
|
1152 | 1158 | except: |
|
1153 | 1159 | self.shell.logfile = old_logfile |
|
1154 | 1160 | warn("Couldn't start log: %s" % sys.exc_info()[1]) |
|
1155 | 1161 | else: |
|
1156 | 1162 | # log input history up to this point, optionally interleaving |
|
1157 | 1163 | # output if requested |
|
1158 | 1164 | |
|
1159 | 1165 | if timestamp: |
|
1160 | 1166 | # disable timestamping for the previous history, since we've |
|
1161 | 1167 | # lost those already (no time machine here). |
|
1162 | 1168 | logger.timestamp = False |
|
1163 | 1169 | |
|
1164 | 1170 | if log_raw_input: |
|
1165 | 1171 | input_hist = self.shell.history_manager.input_hist_raw |
|
1166 | 1172 | else: |
|
1167 | 1173 | input_hist = self.shell.history_manager.input_hist_parsed |
|
1168 | 1174 | |
|
1169 | 1175 | if log_output: |
|
1170 | 1176 | log_write = logger.log_write |
|
1171 | 1177 | output_hist = self.shell.history_manager.output_hist |
|
1172 | 1178 | for n in range(1,len(input_hist)-1): |
|
1173 | 1179 | log_write(input_hist[n].rstrip()) |
|
1174 | 1180 | if n in output_hist: |
|
1175 | 1181 | log_write(repr(output_hist[n]),'output') |
|
1176 | 1182 | else: |
|
1177 | 1183 | logger.log_write(''.join(input_hist[1:])) |
|
1178 | 1184 | if timestamp: |
|
1179 | 1185 | # re-enable timestamping |
|
1180 | 1186 | logger.timestamp = True |
|
1181 | 1187 | |
|
1182 | 1188 | print ('Activating auto-logging. ' |
|
1183 | 1189 | 'Current session state plus future input saved.') |
|
1184 | 1190 | logger.logstate() |
|
1185 | 1191 | |
|
1186 | 1192 | def magic_logstop(self,parameter_s=''): |
|
1187 | 1193 | """Fully stop logging and close log file. |
|
1188 | 1194 | |
|
1189 | 1195 | In order to start logging again, a new %logstart call needs to be made, |
|
1190 | 1196 | possibly (though not necessarily) with a new filename, mode and other |
|
1191 | 1197 | options.""" |
|
1192 | 1198 | self.logger.logstop() |
|
1193 | 1199 | |
|
1194 | 1200 | def magic_logoff(self,parameter_s=''): |
|
1195 | 1201 | """Temporarily stop logging. |
|
1196 | 1202 | |
|
1197 | 1203 | You must have previously started logging.""" |
|
1198 | 1204 | self.shell.logger.switch_log(0) |
|
1199 | 1205 | |
|
1200 | 1206 | def magic_logon(self,parameter_s=''): |
|
1201 | 1207 | """Restart logging. |
|
1202 | 1208 | |
|
1203 | 1209 | This function is for restarting logging which you've temporarily |
|
1204 | 1210 | stopped with %logoff. For starting logging for the first time, you |
|
1205 | 1211 | must use the %logstart function, which allows you to specify an |
|
1206 | 1212 | optional log filename.""" |
|
1207 | 1213 | |
|
1208 | 1214 | self.shell.logger.switch_log(1) |
|
1209 | 1215 | |
|
1210 | 1216 | def magic_logstate(self,parameter_s=''): |
|
1211 | 1217 | """Print the status of the logging system.""" |
|
1212 | 1218 | |
|
1213 | 1219 | self.shell.logger.logstate() |
|
1214 | 1220 | |
|
1215 | 1221 | def magic_pdb(self, parameter_s=''): |
|
1216 | 1222 | """Control the automatic calling of the pdb interactive debugger. |
|
1217 | 1223 | |
|
1218 | 1224 | Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without |
|
1219 | 1225 | argument it works as a toggle. |
|
1220 | 1226 | |
|
1221 | 1227 | When an exception is triggered, IPython can optionally call the |
|
1222 | 1228 | interactive pdb debugger after the traceback printout. %pdb toggles |
|
1223 | 1229 | this feature on and off. |
|
1224 | 1230 | |
|
1225 | 1231 | The initial state of this feature is set in your ipythonrc |
|
1226 | 1232 | configuration file (the variable is called 'pdb'). |
|
1227 | 1233 | |
|
1228 | 1234 | If you want to just activate the debugger AFTER an exception has fired, |
|
1229 | 1235 | without having to type '%pdb on' and rerunning your code, you can use |
|
1230 | 1236 | the %debug magic.""" |
|
1231 | 1237 | |
|
1232 | 1238 | par = parameter_s.strip().lower() |
|
1233 | 1239 | |
|
1234 | 1240 | if par: |
|
1235 | 1241 | try: |
|
1236 | 1242 | new_pdb = {'off':0,'0':0,'on':1,'1':1}[par] |
|
1237 | 1243 | except KeyError: |
|
1238 | 1244 | print ('Incorrect argument. Use on/1, off/0, ' |
|
1239 | 1245 | 'or nothing for a toggle.') |
|
1240 | 1246 | return |
|
1241 | 1247 | else: |
|
1242 | 1248 | # toggle |
|
1243 | 1249 | new_pdb = not self.shell.call_pdb |
|
1244 | 1250 | |
|
1245 | 1251 | # set on the shell |
|
1246 | 1252 | self.shell.call_pdb = new_pdb |
|
1247 | 1253 | print 'Automatic pdb calling has been turned',on_off(new_pdb) |
|
1248 | 1254 | |
|
1249 | 1255 | def magic_debug(self, parameter_s=''): |
|
1250 | 1256 | """Activate the interactive debugger in post-mortem mode. |
|
1251 | 1257 | |
|
1252 | 1258 | If an exception has just occurred, this lets you inspect its stack |
|
1253 | 1259 | frames interactively. Note that this will always work only on the last |
|
1254 | 1260 | traceback that occurred, so you must call this quickly after an |
|
1255 | 1261 | exception that you wish to inspect has fired, because if another one |
|
1256 | 1262 | occurs, it clobbers the previous one. |
|
1257 | 1263 | |
|
1258 | 1264 | If you want IPython to automatically do this on every exception, see |
|
1259 | 1265 | the %pdb magic for more details. |
|
1260 | 1266 | """ |
|
1261 | 1267 | self.shell.debugger(force=True) |
|
1262 | 1268 | |
|
1263 | 1269 | @testdec.skip_doctest |
|
1264 | 1270 | def magic_prun(self, parameter_s ='',user_mode=1, |
|
1265 | 1271 | opts=None,arg_lst=None,prog_ns=None): |
|
1266 | 1272 | |
|
1267 | 1273 | """Run a statement through the python code profiler. |
|
1268 | 1274 | |
|
1269 | 1275 | Usage: |
|
1270 | 1276 | %prun [options] statement |
|
1271 | 1277 | |
|
1272 | 1278 | The given statement (which doesn't require quote marks) is run via the |
|
1273 | 1279 | python profiler in a manner similar to the profile.run() function. |
|
1274 | 1280 | Namespaces are internally managed to work correctly; profile.run |
|
1275 | 1281 | cannot be used in IPython because it makes certain assumptions about |
|
1276 | 1282 | namespaces which do not hold under IPython. |
|
1277 | 1283 | |
|
1278 | 1284 | Options: |
|
1279 | 1285 | |
|
1280 | 1286 | -l <limit>: you can place restrictions on what or how much of the |
|
1281 | 1287 | profile gets printed. The limit value can be: |
|
1282 | 1288 | |
|
1283 | 1289 | * A string: only information for function names containing this string |
|
1284 | 1290 | is printed. |
|
1285 | 1291 | |
|
1286 | 1292 | * An integer: only these many lines are printed. |
|
1287 | 1293 | |
|
1288 | 1294 | * A float (between 0 and 1): this fraction of the report is printed |
|
1289 | 1295 | (for example, use a limit of 0.4 to see the topmost 40% only). |
|
1290 | 1296 | |
|
1291 | 1297 | You can combine several limits with repeated use of the option. For |
|
1292 | 1298 | example, '-l __init__ -l 5' will print only the topmost 5 lines of |
|
1293 | 1299 | information about class constructors. |
|
1294 | 1300 | |
|
1295 | 1301 | -r: return the pstats.Stats object generated by the profiling. This |
|
1296 | 1302 | object has all the information about the profile in it, and you can |
|
1297 | 1303 | later use it for further analysis or in other functions. |
|
1298 | 1304 | |
|
1299 | 1305 | -s <key>: sort profile by given key. You can provide more than one key |
|
1300 | 1306 | by using the option several times: '-s key1 -s key2 -s key3...'. The |
|
1301 | 1307 | default sorting key is 'time'. |
|
1302 | 1308 | |
|
1303 | 1309 | The following is copied verbatim from the profile documentation |
|
1304 | 1310 | referenced below: |
|
1305 | 1311 | |
|
1306 | 1312 | When more than one key is provided, additional keys are used as |
|
1307 | 1313 | secondary criteria when the there is equality in all keys selected |
|
1308 | 1314 | before them. |
|
1309 | 1315 | |
|
1310 | 1316 | Abbreviations can be used for any key names, as long as the |
|
1311 | 1317 | abbreviation is unambiguous. The following are the keys currently |
|
1312 | 1318 | defined: |
|
1313 | 1319 | |
|
1314 | 1320 | Valid Arg Meaning |
|
1315 | 1321 | "calls" call count |
|
1316 | 1322 | "cumulative" cumulative time |
|
1317 | 1323 | "file" file name |
|
1318 | 1324 | "module" file name |
|
1319 | 1325 | "pcalls" primitive call count |
|
1320 | 1326 | "line" line number |
|
1321 | 1327 | "name" function name |
|
1322 | 1328 | "nfl" name/file/line |
|
1323 | 1329 | "stdname" standard name |
|
1324 | 1330 | "time" internal time |
|
1325 | 1331 | |
|
1326 | 1332 | Note that all sorts on statistics are in descending order (placing |
|
1327 | 1333 | most time consuming items first), where as name, file, and line number |
|
1328 | 1334 | searches are in ascending order (i.e., alphabetical). The subtle |
|
1329 | 1335 | distinction between "nfl" and "stdname" is that the standard name is a |
|
1330 | 1336 | sort of the name as printed, which means that the embedded line |
|
1331 | 1337 | numbers get compared in an odd way. For example, lines 3, 20, and 40 |
|
1332 | 1338 | would (if the file names were the same) appear in the string order |
|
1333 | 1339 | "20" "3" and "40". In contrast, "nfl" does a numeric compare of the |
|
1334 | 1340 | line numbers. In fact, sort_stats("nfl") is the same as |
|
1335 | 1341 | sort_stats("name", "file", "line"). |
|
1336 | 1342 | |
|
1337 | 1343 | -T <filename>: save profile results as shown on screen to a text |
|
1338 | 1344 | file. The profile is still shown on screen. |
|
1339 | 1345 | |
|
1340 | 1346 | -D <filename>: save (via dump_stats) profile statistics to given |
|
1341 | 1347 | filename. This data is in a format understod by the pstats module, and |
|
1342 | 1348 | is generated by a call to the dump_stats() method of profile |
|
1343 | 1349 | objects. The profile is still shown on screen. |
|
1344 | 1350 | |
|
1345 | 1351 | If you want to run complete programs under the profiler's control, use |
|
1346 | 1352 | '%run -p [prof_opts] filename.py [args to program]' where prof_opts |
|
1347 | 1353 | contains profiler specific options as described here. |
|
1348 | 1354 | |
|
1349 | 1355 | You can read the complete documentation for the profile module with:: |
|
1350 | 1356 | |
|
1351 | 1357 | In [1]: import profile; profile.help() |
|
1352 | 1358 | """ |
|
1353 | 1359 | |
|
1354 | 1360 | opts_def = Struct(D=[''],l=[],s=['time'],T=['']) |
|
1355 | 1361 | # protect user quote marks |
|
1356 | 1362 | parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'") |
|
1357 | 1363 | |
|
1358 | 1364 | if user_mode: # regular user call |
|
1359 | 1365 | opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:', |
|
1360 | 1366 | list_all=1) |
|
1361 | 1367 | namespace = self.shell.user_ns |
|
1362 | 1368 | else: # called to run a program by %run -p |
|
1363 | 1369 | try: |
|
1364 | 1370 | filename = get_py_filename(arg_lst[0]) |
|
1365 | 1371 | except IOError,msg: |
|
1366 | 1372 | error(msg) |
|
1367 | 1373 | return |
|
1368 | 1374 | |
|
1369 | 1375 | arg_str = 'execfile(filename,prog_ns)' |
|
1370 | 1376 | namespace = locals() |
|
1371 | 1377 | |
|
1372 | 1378 | opts.merge(opts_def) |
|
1373 | 1379 | |
|
1374 | 1380 | prof = profile.Profile() |
|
1375 | 1381 | try: |
|
1376 | 1382 | prof = prof.runctx(arg_str,namespace,namespace) |
|
1377 | 1383 | sys_exit = '' |
|
1378 | 1384 | except SystemExit: |
|
1379 | 1385 | sys_exit = """*** SystemExit exception caught in code being profiled.""" |
|
1380 | 1386 | |
|
1381 | 1387 | stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s) |
|
1382 | 1388 | |
|
1383 | 1389 | lims = opts.l |
|
1384 | 1390 | if lims: |
|
1385 | 1391 | lims = [] # rebuild lims with ints/floats/strings |
|
1386 | 1392 | for lim in opts.l: |
|
1387 | 1393 | try: |
|
1388 | 1394 | lims.append(int(lim)) |
|
1389 | 1395 | except ValueError: |
|
1390 | 1396 | try: |
|
1391 | 1397 | lims.append(float(lim)) |
|
1392 | 1398 | except ValueError: |
|
1393 | 1399 | lims.append(lim) |
|
1394 | 1400 | |
|
1395 | 1401 | # Trap output. |
|
1396 | 1402 | stdout_trap = StringIO() |
|
1397 | 1403 | |
|
1398 | 1404 | if hasattr(stats,'stream'): |
|
1399 | 1405 | # In newer versions of python, the stats object has a 'stream' |
|
1400 | 1406 | # attribute to write into. |
|
1401 | 1407 | stats.stream = stdout_trap |
|
1402 | 1408 | stats.print_stats(*lims) |
|
1403 | 1409 | else: |
|
1404 | 1410 | # For older versions, we manually redirect stdout during printing |
|
1405 | 1411 | sys_stdout = sys.stdout |
|
1406 | 1412 | try: |
|
1407 | 1413 | sys.stdout = stdout_trap |
|
1408 | 1414 | stats.print_stats(*lims) |
|
1409 | 1415 | finally: |
|
1410 | 1416 | sys.stdout = sys_stdout |
|
1411 | 1417 | |
|
1412 | 1418 | output = stdout_trap.getvalue() |
|
1413 | 1419 | output = output.rstrip() |
|
1414 | 1420 | |
|
1415 | 1421 | page.page(output) |
|
1416 | 1422 | print sys_exit, |
|
1417 | 1423 | |
|
1418 | 1424 | dump_file = opts.D[0] |
|
1419 | 1425 | text_file = opts.T[0] |
|
1420 | 1426 | if dump_file: |
|
1421 | 1427 | prof.dump_stats(dump_file) |
|
1422 | 1428 | print '\n*** Profile stats marshalled to file',\ |
|
1423 | 1429 | `dump_file`+'.',sys_exit |
|
1424 | 1430 | if text_file: |
|
1425 | 1431 | pfile = file(text_file,'w') |
|
1426 | 1432 | pfile.write(output) |
|
1427 | 1433 | pfile.close() |
|
1428 | 1434 | print '\n*** Profile printout saved to text file',\ |
|
1429 | 1435 | `text_file`+'.',sys_exit |
|
1430 | 1436 | |
|
1431 | 1437 | if opts.has_key('r'): |
|
1432 | 1438 | return stats |
|
1433 | 1439 | else: |
|
1434 | 1440 | return None |
|
1435 | 1441 | |
|
1436 | 1442 | @testdec.skip_doctest |
|
1437 | 1443 | def magic_run(self, parameter_s ='',runner=None, |
|
1438 | 1444 | file_finder=get_py_filename): |
|
1439 | 1445 | """Run the named file inside IPython as a program. |
|
1440 | 1446 | |
|
1441 | 1447 | Usage:\\ |
|
1442 | 1448 | %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args] |
|
1443 | 1449 | |
|
1444 | 1450 | Parameters after the filename are passed as command-line arguments to |
|
1445 | 1451 | the program (put in sys.argv). Then, control returns to IPython's |
|
1446 | 1452 | prompt. |
|
1447 | 1453 | |
|
1448 | 1454 | This is similar to running at a system prompt:\\ |
|
1449 | 1455 | $ python file args\\ |
|
1450 | 1456 | but with the advantage of giving you IPython's tracebacks, and of |
|
1451 | 1457 | loading all variables into your interactive namespace for further use |
|
1452 | 1458 | (unless -p is used, see below). |
|
1453 | 1459 | |
|
1454 | 1460 | The file is executed in a namespace initially consisting only of |
|
1455 | 1461 | __name__=='__main__' and sys.argv constructed as indicated. It thus |
|
1456 | 1462 | sees its environment as if it were being run as a stand-alone program |
|
1457 | 1463 | (except for sharing global objects such as previously imported |
|
1458 | 1464 | modules). But after execution, the IPython interactive namespace gets |
|
1459 | 1465 | updated with all variables defined in the program (except for __name__ |
|
1460 | 1466 | and sys.argv). This allows for very convenient loading of code for |
|
1461 | 1467 | interactive work, while giving each program a 'clean sheet' to run in. |
|
1462 | 1468 | |
|
1463 | 1469 | Options: |
|
1464 | 1470 | |
|
1465 | 1471 | -n: __name__ is NOT set to '__main__', but to the running file's name |
|
1466 | 1472 | without extension (as python does under import). This allows running |
|
1467 | 1473 | scripts and reloading the definitions in them without calling code |
|
1468 | 1474 | protected by an ' if __name__ == "__main__" ' clause. |
|
1469 | 1475 | |
|
1470 | 1476 | -i: run the file in IPython's namespace instead of an empty one. This |
|
1471 | 1477 | is useful if you are experimenting with code written in a text editor |
|
1472 | 1478 | which depends on variables defined interactively. |
|
1473 | 1479 | |
|
1474 | 1480 | -e: ignore sys.exit() calls or SystemExit exceptions in the script |
|
1475 | 1481 | being run. This is particularly useful if IPython is being used to |
|
1476 | 1482 | run unittests, which always exit with a sys.exit() call. In such |
|
1477 | 1483 | cases you are interested in the output of the test results, not in |
|
1478 | 1484 | seeing a traceback of the unittest module. |
|
1479 | 1485 | |
|
1480 | 1486 | -t: print timing information at the end of the run. IPython will give |
|
1481 | 1487 | you an estimated CPU time consumption for your script, which under |
|
1482 | 1488 | Unix uses the resource module to avoid the wraparound problems of |
|
1483 | 1489 | time.clock(). Under Unix, an estimate of time spent on system tasks |
|
1484 | 1490 | is also given (for Windows platforms this is reported as 0.0). |
|
1485 | 1491 | |
|
1486 | 1492 | If -t is given, an additional -N<N> option can be given, where <N> |
|
1487 | 1493 | must be an integer indicating how many times you want the script to |
|
1488 | 1494 | run. The final timing report will include total and per run results. |
|
1489 | 1495 | |
|
1490 | 1496 | For example (testing the script uniq_stable.py): |
|
1491 | 1497 | |
|
1492 | 1498 | In [1]: run -t uniq_stable |
|
1493 | 1499 | |
|
1494 | 1500 | IPython CPU timings (estimated):\\ |
|
1495 | 1501 | User : 0.19597 s.\\ |
|
1496 | 1502 | System: 0.0 s.\\ |
|
1497 | 1503 | |
|
1498 | 1504 | In [2]: run -t -N5 uniq_stable |
|
1499 | 1505 | |
|
1500 | 1506 | IPython CPU timings (estimated):\\ |
|
1501 | 1507 | Total runs performed: 5\\ |
|
1502 | 1508 | Times : Total Per run\\ |
|
1503 | 1509 | User : 0.910862 s, 0.1821724 s.\\ |
|
1504 | 1510 | System: 0.0 s, 0.0 s. |
|
1505 | 1511 | |
|
1506 | 1512 | -d: run your program under the control of pdb, the Python debugger. |
|
1507 | 1513 | This allows you to execute your program step by step, watch variables, |
|
1508 | 1514 | etc. Internally, what IPython does is similar to calling: |
|
1509 | 1515 | |
|
1510 | 1516 | pdb.run('execfile("YOURFILENAME")') |
|
1511 | 1517 | |
|
1512 | 1518 | with a breakpoint set on line 1 of your file. You can change the line |
|
1513 | 1519 | number for this automatic breakpoint to be <N> by using the -bN option |
|
1514 | 1520 | (where N must be an integer). For example: |
|
1515 | 1521 | |
|
1516 | 1522 | %run -d -b40 myscript |
|
1517 | 1523 | |
|
1518 | 1524 | will set the first breakpoint at line 40 in myscript.py. Note that |
|
1519 | 1525 | the first breakpoint must be set on a line which actually does |
|
1520 | 1526 | something (not a comment or docstring) for it to stop execution. |
|
1521 | 1527 | |
|
1522 | 1528 | When the pdb debugger starts, you will see a (Pdb) prompt. You must |
|
1523 | 1529 | first enter 'c' (without qoutes) to start execution up to the first |
|
1524 | 1530 | breakpoint. |
|
1525 | 1531 | |
|
1526 | 1532 | Entering 'help' gives information about the use of the debugger. You |
|
1527 | 1533 | can easily see pdb's full documentation with "import pdb;pdb.help()" |
|
1528 | 1534 | at a prompt. |
|
1529 | 1535 | |
|
1530 | 1536 | -p: run program under the control of the Python profiler module (which |
|
1531 | 1537 | prints a detailed report of execution times, function calls, etc). |
|
1532 | 1538 | |
|
1533 | 1539 | You can pass other options after -p which affect the behavior of the |
|
1534 | 1540 | profiler itself. See the docs for %prun for details. |
|
1535 | 1541 | |
|
1536 | 1542 | In this mode, the program's variables do NOT propagate back to the |
|
1537 | 1543 | IPython interactive namespace (because they remain in the namespace |
|
1538 | 1544 | where the profiler executes them). |
|
1539 | 1545 | |
|
1540 | 1546 | Internally this triggers a call to %prun, see its documentation for |
|
1541 | 1547 | details on the options available specifically for profiling. |
|
1542 | 1548 | |
|
1543 | 1549 | There is one special usage for which the text above doesn't apply: |
|
1544 | 1550 | if the filename ends with .ipy, the file is run as ipython script, |
|
1545 | 1551 | just as if the commands were written on IPython prompt. |
|
1546 | 1552 | """ |
|
1547 | 1553 | |
|
1548 | 1554 | # get arguments and set sys.argv for program to be run. |
|
1549 | 1555 | opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e', |
|
1550 | 1556 | mode='list',list_all=1) |
|
1551 | 1557 | |
|
1552 | 1558 | try: |
|
1553 | 1559 | filename = file_finder(arg_lst[0]) |
|
1554 | 1560 | except IndexError: |
|
1555 | 1561 | warn('you must provide at least a filename.') |
|
1556 | 1562 | print '\n%run:\n',oinspect.getdoc(self.magic_run) |
|
1557 | 1563 | return |
|
1558 | 1564 | except IOError,msg: |
|
1559 | 1565 | error(msg) |
|
1560 | 1566 | return |
|
1561 | 1567 | |
|
1562 | 1568 | if filename.lower().endswith('.ipy'): |
|
1563 | 1569 | self.shell.safe_execfile_ipy(filename) |
|
1564 | 1570 | return |
|
1565 | 1571 | |
|
1566 | 1572 | # Control the response to exit() calls made by the script being run |
|
1567 | 1573 | exit_ignore = opts.has_key('e') |
|
1568 | 1574 | |
|
1569 | 1575 | # Make sure that the running script gets a proper sys.argv as if it |
|
1570 | 1576 | # were run from a system shell. |
|
1571 | 1577 | save_argv = sys.argv # save it for later restoring |
|
1572 | 1578 | sys.argv = [filename]+ arg_lst[1:] # put in the proper filename |
|
1573 | 1579 | |
|
1574 | 1580 | if opts.has_key('i'): |
|
1575 | 1581 | # Run in user's interactive namespace |
|
1576 | 1582 | prog_ns = self.shell.user_ns |
|
1577 | 1583 | __name__save = self.shell.user_ns['__name__'] |
|
1578 | 1584 | prog_ns['__name__'] = '__main__' |
|
1579 | 1585 | main_mod = self.shell.new_main_mod(prog_ns) |
|
1580 | 1586 | else: |
|
1581 | 1587 | # Run in a fresh, empty namespace |
|
1582 | 1588 | if opts.has_key('n'): |
|
1583 | 1589 | name = os.path.splitext(os.path.basename(filename))[0] |
|
1584 | 1590 | else: |
|
1585 | 1591 | name = '__main__' |
|
1586 | 1592 | |
|
1587 | 1593 | main_mod = self.shell.new_main_mod() |
|
1588 | 1594 | prog_ns = main_mod.__dict__ |
|
1589 | 1595 | prog_ns['__name__'] = name |
|
1590 | 1596 | |
|
1591 | 1597 | # Since '%run foo' emulates 'python foo.py' at the cmd line, we must |
|
1592 | 1598 | # set the __file__ global in the script's namespace |
|
1593 | 1599 | prog_ns['__file__'] = filename |
|
1594 | 1600 | |
|
1595 | 1601 | # pickle fix. See interactiveshell for an explanation. But we need to make sure |
|
1596 | 1602 | # that, if we overwrite __main__, we replace it at the end |
|
1597 | 1603 | main_mod_name = prog_ns['__name__'] |
|
1598 | 1604 | |
|
1599 | 1605 | if main_mod_name == '__main__': |
|
1600 | 1606 | restore_main = sys.modules['__main__'] |
|
1601 | 1607 | else: |
|
1602 | 1608 | restore_main = False |
|
1603 | 1609 | |
|
1604 | 1610 | # This needs to be undone at the end to prevent holding references to |
|
1605 | 1611 | # every single object ever created. |
|
1606 | 1612 | sys.modules[main_mod_name] = main_mod |
|
1607 | 1613 | |
|
1608 | 1614 | try: |
|
1609 | 1615 | stats = None |
|
1610 | 1616 | with self.readline_no_record: |
|
1611 | 1617 | if opts.has_key('p'): |
|
1612 | 1618 | stats = self.magic_prun('',0,opts,arg_lst,prog_ns) |
|
1613 | 1619 | else: |
|
1614 | 1620 | if opts.has_key('d'): |
|
1615 | 1621 | deb = debugger.Pdb(self.shell.colors) |
|
1616 | 1622 | # reset Breakpoint state, which is moronically kept |
|
1617 | 1623 | # in a class |
|
1618 | 1624 | bdb.Breakpoint.next = 1 |
|
1619 | 1625 | bdb.Breakpoint.bplist = {} |
|
1620 | 1626 | bdb.Breakpoint.bpbynumber = [None] |
|
1621 | 1627 | # Set an initial breakpoint to stop execution |
|
1622 | 1628 | maxtries = 10 |
|
1623 | 1629 | bp = int(opts.get('b',[1])[0]) |
|
1624 | 1630 | checkline = deb.checkline(filename,bp) |
|
1625 | 1631 | if not checkline: |
|
1626 | 1632 | for bp in range(bp+1,bp+maxtries+1): |
|
1627 | 1633 | if deb.checkline(filename,bp): |
|
1628 | 1634 | break |
|
1629 | 1635 | else: |
|
1630 | 1636 | msg = ("\nI failed to find a valid line to set " |
|
1631 | 1637 | "a breakpoint\n" |
|
1632 | 1638 | "after trying up to line: %s.\n" |
|
1633 | 1639 | "Please set a valid breakpoint manually " |
|
1634 | 1640 | "with the -b option." % bp) |
|
1635 | 1641 | error(msg) |
|
1636 | 1642 | return |
|
1637 | 1643 | # if we find a good linenumber, set the breakpoint |
|
1638 | 1644 | deb.do_break('%s:%s' % (filename,bp)) |
|
1639 | 1645 | # Start file run |
|
1640 | 1646 | print "NOTE: Enter 'c' at the", |
|
1641 | 1647 | print "%s prompt to start your script." % deb.prompt |
|
1642 | 1648 | try: |
|
1643 | 1649 | deb.run('execfile("%s")' % filename,prog_ns) |
|
1644 | 1650 | |
|
1645 | 1651 | except: |
|
1646 | 1652 | etype, value, tb = sys.exc_info() |
|
1647 | 1653 | # Skip three frames in the traceback: the %run one, |
|
1648 | 1654 | # one inside bdb.py, and the command-line typed by the |
|
1649 | 1655 | # user (run by exec in pdb itself). |
|
1650 | 1656 | self.shell.InteractiveTB(etype,value,tb,tb_offset=3) |
|
1651 | 1657 | else: |
|
1652 | 1658 | if runner is None: |
|
1653 | 1659 | runner = self.shell.safe_execfile |
|
1654 | 1660 | if opts.has_key('t'): |
|
1655 | 1661 | # timed execution |
|
1656 | 1662 | try: |
|
1657 | 1663 | nruns = int(opts['N'][0]) |
|
1658 | 1664 | if nruns < 1: |
|
1659 | 1665 | error('Number of runs must be >=1') |
|
1660 | 1666 | return |
|
1661 | 1667 | except (KeyError): |
|
1662 | 1668 | nruns = 1 |
|
1663 | 1669 | if nruns == 1: |
|
1664 | 1670 | t0 = clock2() |
|
1665 | 1671 | runner(filename,prog_ns,prog_ns, |
|
1666 | 1672 | exit_ignore=exit_ignore) |
|
1667 | 1673 | t1 = clock2() |
|
1668 | 1674 | t_usr = t1[0]-t0[0] |
|
1669 | 1675 | t_sys = t1[1]-t0[1] |
|
1670 | 1676 | print "\nIPython CPU timings (estimated):" |
|
1671 | 1677 | print " User : %10s s." % t_usr |
|
1672 | 1678 | print " System: %10s s." % t_sys |
|
1673 | 1679 | else: |
|
1674 | 1680 | runs = range(nruns) |
|
1675 | 1681 | t0 = clock2() |
|
1676 | 1682 | for nr in runs: |
|
1677 | 1683 | runner(filename,prog_ns,prog_ns, |
|
1678 | 1684 | exit_ignore=exit_ignore) |
|
1679 | 1685 | t1 = clock2() |
|
1680 | 1686 | t_usr = t1[0]-t0[0] |
|
1681 | 1687 | t_sys = t1[1]-t0[1] |
|
1682 | 1688 | print "\nIPython CPU timings (estimated):" |
|
1683 | 1689 | print "Total runs performed:",nruns |
|
1684 | 1690 | print " Times : %10s %10s" % ('Total','Per run') |
|
1685 | 1691 | print " User : %10s s, %10s s." % (t_usr,t_usr/nruns) |
|
1686 | 1692 | print " System: %10s s, %10s s." % (t_sys,t_sys/nruns) |
|
1687 | 1693 | |
|
1688 | 1694 | else: |
|
1689 | 1695 | # regular execution |
|
1690 | 1696 | runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore) |
|
1691 | 1697 | |
|
1692 | 1698 | if opts.has_key('i'): |
|
1693 | 1699 | self.shell.user_ns['__name__'] = __name__save |
|
1694 | 1700 | else: |
|
1695 | 1701 | # The shell MUST hold a reference to prog_ns so after %run |
|
1696 | 1702 | # exits, the python deletion mechanism doesn't zero it out |
|
1697 | 1703 | # (leaving dangling references). |
|
1698 | 1704 | self.shell.cache_main_mod(prog_ns,filename) |
|
1699 | 1705 | # update IPython interactive namespace |
|
1700 | 1706 | |
|
1701 | 1707 | # Some forms of read errors on the file may mean the |
|
1702 | 1708 | # __name__ key was never set; using pop we don't have to |
|
1703 | 1709 | # worry about a possible KeyError. |
|
1704 | 1710 | prog_ns.pop('__name__', None) |
|
1705 | 1711 | |
|
1706 | 1712 | self.shell.user_ns.update(prog_ns) |
|
1707 | 1713 | finally: |
|
1708 | 1714 | # It's a bit of a mystery why, but __builtins__ can change from |
|
1709 | 1715 | # being a module to becoming a dict missing some key data after |
|
1710 | 1716 | # %run. As best I can see, this is NOT something IPython is doing |
|
1711 | 1717 | # at all, and similar problems have been reported before: |
|
1712 | 1718 | # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html |
|
1713 | 1719 | # Since this seems to be done by the interpreter itself, the best |
|
1714 | 1720 | # we can do is to at least restore __builtins__ for the user on |
|
1715 | 1721 | # exit. |
|
1716 | 1722 | self.shell.user_ns['__builtins__'] = __builtin__ |
|
1717 | 1723 | |
|
1718 | 1724 | # Ensure key global structures are restored |
|
1719 | 1725 | sys.argv = save_argv |
|
1720 | 1726 | if restore_main: |
|
1721 | 1727 | sys.modules['__main__'] = restore_main |
|
1722 | 1728 | else: |
|
1723 | 1729 | # Remove from sys.modules the reference to main_mod we'd |
|
1724 | 1730 | # added. Otherwise it will trap references to objects |
|
1725 | 1731 | # contained therein. |
|
1726 | 1732 | del sys.modules[main_mod_name] |
|
1727 | 1733 | |
|
1728 | 1734 | return stats |
|
1729 | 1735 | |
|
1730 | 1736 | @testdec.skip_doctest |
|
1731 | 1737 | def magic_timeit(self, parameter_s =''): |
|
1732 | 1738 | """Time execution of a Python statement or expression |
|
1733 | 1739 | |
|
1734 | 1740 | Usage:\\ |
|
1735 | 1741 | %timeit [-n<N> -r<R> [-t|-c]] statement |
|
1736 | 1742 | |
|
1737 | 1743 | Time execution of a Python statement or expression using the timeit |
|
1738 | 1744 | module. |
|
1739 | 1745 | |
|
1740 | 1746 | Options: |
|
1741 | 1747 | -n<N>: execute the given statement <N> times in a loop. If this value |
|
1742 | 1748 | is not given, a fitting value is chosen. |
|
1743 | 1749 | |
|
1744 | 1750 | -r<R>: repeat the loop iteration <R> times and take the best result. |
|
1745 | 1751 | Default: 3 |
|
1746 | 1752 | |
|
1747 | 1753 | -t: use time.time to measure the time, which is the default on Unix. |
|
1748 | 1754 | This function measures wall time. |
|
1749 | 1755 | |
|
1750 | 1756 | -c: use time.clock to measure the time, which is the default on |
|
1751 | 1757 | Windows and measures wall time. On Unix, resource.getrusage is used |
|
1752 | 1758 | instead and returns the CPU user time. |
|
1753 | 1759 | |
|
1754 | 1760 | -p<P>: use a precision of <P> digits to display the timing result. |
|
1755 | 1761 | Default: 3 |
|
1756 | 1762 | |
|
1757 | 1763 | |
|
1758 | 1764 | Examples: |
|
1759 | 1765 | |
|
1760 | 1766 | In [1]: %timeit pass |
|
1761 | 1767 | 10000000 loops, best of 3: 53.3 ns per loop |
|
1762 | 1768 | |
|
1763 | 1769 | In [2]: u = None |
|
1764 | 1770 | |
|
1765 | 1771 | In [3]: %timeit u is None |
|
1766 | 1772 | 10000000 loops, best of 3: 184 ns per loop |
|
1767 | 1773 | |
|
1768 | 1774 | In [4]: %timeit -r 4 u == None |
|
1769 | 1775 | 1000000 loops, best of 4: 242 ns per loop |
|
1770 | 1776 | |
|
1771 | 1777 | In [5]: import time |
|
1772 | 1778 | |
|
1773 | 1779 | In [6]: %timeit -n1 time.sleep(2) |
|
1774 | 1780 | 1 loops, best of 3: 2 s per loop |
|
1775 | 1781 | |
|
1776 | 1782 | |
|
1777 | 1783 | The times reported by %timeit will be slightly higher than those |
|
1778 | 1784 | reported by the timeit.py script when variables are accessed. This is |
|
1779 | 1785 | due to the fact that %timeit executes the statement in the namespace |
|
1780 | 1786 | of the shell, compared with timeit.py, which uses a single setup |
|
1781 | 1787 | statement to import function or create variables. Generally, the bias |
|
1782 | 1788 | does not matter as long as results from timeit.py are not mixed with |
|
1783 | 1789 | those from %timeit.""" |
|
1784 | 1790 | |
|
1785 | 1791 | import timeit |
|
1786 | 1792 | import math |
|
1787 | 1793 | |
|
1788 | 1794 | # XXX: Unfortunately the unicode 'micro' symbol can cause problems in |
|
1789 | 1795 | # certain terminals. Until we figure out a robust way of |
|
1790 | 1796 | # auto-detecting if the terminal can deal with it, use plain 'us' for |
|
1791 | 1797 | # microseconds. I am really NOT happy about disabling the proper |
|
1792 | 1798 | # 'micro' prefix, but crashing is worse... If anyone knows what the |
|
1793 | 1799 | # right solution for this is, I'm all ears... |
|
1794 | 1800 | # |
|
1795 | 1801 | # Note: using |
|
1796 | 1802 | # |
|
1797 | 1803 | # s = u'\xb5' |
|
1798 | 1804 | # s.encode(sys.getdefaultencoding()) |
|
1799 | 1805 | # |
|
1800 | 1806 | # is not sufficient, as I've seen terminals where that fails but |
|
1801 | 1807 | # print s |
|
1802 | 1808 | # |
|
1803 | 1809 | # succeeds |
|
1804 | 1810 | # |
|
1805 | 1811 | # See bug: https://bugs.launchpad.net/ipython/+bug/348466 |
|
1806 | 1812 | |
|
1807 | 1813 | #units = [u"s", u"ms",u'\xb5',"ns"] |
|
1808 | 1814 | units = [u"s", u"ms",u'us',"ns"] |
|
1809 | 1815 | |
|
1810 | 1816 | scaling = [1, 1e3, 1e6, 1e9] |
|
1811 | 1817 | |
|
1812 | 1818 | opts, stmt = self.parse_options(parameter_s,'n:r:tcp:', |
|
1813 | 1819 | posix=False) |
|
1814 | 1820 | if stmt == "": |
|
1815 | 1821 | return |
|
1816 | 1822 | timefunc = timeit.default_timer |
|
1817 | 1823 | number = int(getattr(opts, "n", 0)) |
|
1818 | 1824 | repeat = int(getattr(opts, "r", timeit.default_repeat)) |
|
1819 | 1825 | precision = int(getattr(opts, "p", 3)) |
|
1820 | 1826 | if hasattr(opts, "t"): |
|
1821 | 1827 | timefunc = time.time |
|
1822 | 1828 | if hasattr(opts, "c"): |
|
1823 | 1829 | timefunc = clock |
|
1824 | 1830 | |
|
1825 | 1831 | timer = timeit.Timer(timer=timefunc) |
|
1826 | 1832 | # this code has tight coupling to the inner workings of timeit.Timer, |
|
1827 | 1833 | # but is there a better way to achieve that the code stmt has access |
|
1828 | 1834 | # to the shell namespace? |
|
1829 | 1835 | |
|
1830 | 1836 | src = timeit.template % {'stmt': timeit.reindent(stmt, 8), |
|
1831 | 1837 | 'setup': "pass"} |
|
1832 | 1838 | # Track compilation time so it can be reported if too long |
|
1833 | 1839 | # Minimum time above which compilation time will be reported |
|
1834 | 1840 | tc_min = 0.1 |
|
1835 | 1841 | |
|
1836 | 1842 | t0 = clock() |
|
1837 | 1843 | code = compile(src, "<magic-timeit>", "exec") |
|
1838 | 1844 | tc = clock()-t0 |
|
1839 | 1845 | |
|
1840 | 1846 | ns = {} |
|
1841 | 1847 | exec code in self.shell.user_ns, ns |
|
1842 | 1848 | timer.inner = ns["inner"] |
|
1843 | 1849 | |
|
1844 | 1850 | if number == 0: |
|
1845 | 1851 | # determine number so that 0.2 <= total time < 2.0 |
|
1846 | 1852 | number = 1 |
|
1847 | 1853 | for i in range(1, 10): |
|
1848 | 1854 | if timer.timeit(number) >= 0.2: |
|
1849 | 1855 | break |
|
1850 | 1856 | number *= 10 |
|
1851 | 1857 | |
|
1852 | 1858 | best = min(timer.repeat(repeat, number)) / number |
|
1853 | 1859 | |
|
1854 | 1860 | if best > 0.0 and best < 1000.0: |
|
1855 | 1861 | order = min(-int(math.floor(math.log10(best)) // 3), 3) |
|
1856 | 1862 | elif best >= 1000.0: |
|
1857 | 1863 | order = 0 |
|
1858 | 1864 | else: |
|
1859 | 1865 | order = 3 |
|
1860 | 1866 | print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat, |
|
1861 | 1867 | precision, |
|
1862 | 1868 | best * scaling[order], |
|
1863 | 1869 | units[order]) |
|
1864 | 1870 | if tc > tc_min: |
|
1865 | 1871 | print "Compiler time: %.2f s" % tc |
|
1866 | 1872 | |
|
1867 | 1873 | @testdec.skip_doctest |
|
1868 | 1874 | @needs_local_scope |
|
1869 | 1875 | def magic_time(self,parameter_s = ''): |
|
1870 | 1876 | """Time execution of a Python statement or expression. |
|
1871 | 1877 | |
|
1872 | 1878 | The CPU and wall clock times are printed, and the value of the |
|
1873 | 1879 | expression (if any) is returned. Note that under Win32, system time |
|
1874 | 1880 | is always reported as 0, since it can not be measured. |
|
1875 | 1881 | |
|
1876 | 1882 | This function provides very basic timing functionality. In Python |
|
1877 | 1883 | 2.3, the timeit module offers more control and sophistication, so this |
|
1878 | 1884 | could be rewritten to use it (patches welcome). |
|
1879 | 1885 | |
|
1880 | 1886 | Some examples: |
|
1881 | 1887 | |
|
1882 | 1888 | In [1]: time 2**128 |
|
1883 | 1889 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1884 | 1890 | Wall time: 0.00 |
|
1885 | 1891 | Out[1]: 340282366920938463463374607431768211456L |
|
1886 | 1892 | |
|
1887 | 1893 | In [2]: n = 1000000 |
|
1888 | 1894 | |
|
1889 | 1895 | In [3]: time sum(range(n)) |
|
1890 | 1896 | CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s |
|
1891 | 1897 | Wall time: 1.37 |
|
1892 | 1898 | Out[3]: 499999500000L |
|
1893 | 1899 | |
|
1894 | 1900 | In [4]: time print 'hello world' |
|
1895 | 1901 | hello world |
|
1896 | 1902 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1897 | 1903 | Wall time: 0.00 |
|
1898 | 1904 | |
|
1899 | 1905 | Note that the time needed by Python to compile the given expression |
|
1900 | 1906 | will be reported if it is more than 0.1s. In this example, the |
|
1901 | 1907 | actual exponentiation is done by Python at compilation time, so while |
|
1902 | 1908 | the expression can take a noticeable amount of time to compute, that |
|
1903 | 1909 | time is purely due to the compilation: |
|
1904 | 1910 | |
|
1905 | 1911 | In [5]: time 3**9999; |
|
1906 | 1912 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1907 | 1913 | Wall time: 0.00 s |
|
1908 | 1914 | |
|
1909 | 1915 | In [6]: time 3**999999; |
|
1910 | 1916 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1911 | 1917 | Wall time: 0.00 s |
|
1912 | 1918 | Compiler : 0.78 s |
|
1913 | 1919 | """ |
|
1914 | 1920 | |
|
1915 | 1921 | # fail immediately if the given expression can't be compiled |
|
1916 | 1922 | |
|
1917 | 1923 | expr = self.shell.prefilter(parameter_s,False) |
|
1918 | 1924 | |
|
1919 | 1925 | # Minimum time above which compilation time will be reported |
|
1920 | 1926 | tc_min = 0.1 |
|
1921 | 1927 | |
|
1922 | 1928 | try: |
|
1923 | 1929 | mode = 'eval' |
|
1924 | 1930 | t0 = clock() |
|
1925 | 1931 | code = compile(expr,'<timed eval>',mode) |
|
1926 | 1932 | tc = clock()-t0 |
|
1927 | 1933 | except SyntaxError: |
|
1928 | 1934 | mode = 'exec' |
|
1929 | 1935 | t0 = clock() |
|
1930 | 1936 | code = compile(expr,'<timed exec>',mode) |
|
1931 | 1937 | tc = clock()-t0 |
|
1932 | 1938 | # skew measurement as little as possible |
|
1933 | 1939 | glob = self.shell.user_ns |
|
1934 | 1940 | locs = self._magic_locals |
|
1935 | 1941 | clk = clock2 |
|
1936 | 1942 | wtime = time.time |
|
1937 | 1943 | # time execution |
|
1938 | 1944 | wall_st = wtime() |
|
1939 | 1945 | if mode=='eval': |
|
1940 | 1946 | st = clk() |
|
1941 | 1947 | out = eval(code, glob, locs) |
|
1942 | 1948 | end = clk() |
|
1943 | 1949 | else: |
|
1944 | 1950 | st = clk() |
|
1945 | 1951 | exec code in glob, locs |
|
1946 | 1952 | end = clk() |
|
1947 | 1953 | out = None |
|
1948 | 1954 | wall_end = wtime() |
|
1949 | 1955 | # Compute actual times and report |
|
1950 | 1956 | wall_time = wall_end-wall_st |
|
1951 | 1957 | cpu_user = end[0]-st[0] |
|
1952 | 1958 | cpu_sys = end[1]-st[1] |
|
1953 | 1959 | cpu_tot = cpu_user+cpu_sys |
|
1954 | 1960 | print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \ |
|
1955 | 1961 | (cpu_user,cpu_sys,cpu_tot) |
|
1956 | 1962 | print "Wall time: %.2f s" % wall_time |
|
1957 | 1963 | if tc > tc_min: |
|
1958 | 1964 | print "Compiler : %.2f s" % tc |
|
1959 | 1965 | return out |
|
1960 | 1966 | |
|
1961 | 1967 | @testdec.skip_doctest |
|
1962 | 1968 | def magic_macro(self,parameter_s = ''): |
|
1963 | 1969 | """Define a macro for future re-execution. It accepts ranges of history, |
|
1964 | 1970 | filenames or string objects. |
|
1965 | 1971 | |
|
1966 | 1972 | Usage:\\ |
|
1967 | 1973 | %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ... |
|
1968 | 1974 | |
|
1969 | 1975 | Options: |
|
1970 | 1976 | |
|
1971 | 1977 | -r: use 'raw' input. By default, the 'processed' history is used, |
|
1972 | 1978 | so that magics are loaded in their transformed version to valid |
|
1973 | 1979 | Python. If this option is given, the raw input as typed as the |
|
1974 | 1980 | command line is used instead. |
|
1975 | 1981 | |
|
1976 | 1982 | This will define a global variable called `name` which is a string |
|
1977 | 1983 | made of joining the slices and lines you specify (n1,n2,... numbers |
|
1978 | 1984 | above) from your input history into a single string. This variable |
|
1979 | 1985 | acts like an automatic function which re-executes those lines as if |
|
1980 | 1986 | you had typed them. You just type 'name' at the prompt and the code |
|
1981 | 1987 | executes. |
|
1982 | 1988 | |
|
1983 | 1989 | The syntax for indicating input ranges is described in %history. |
|
1984 | 1990 | |
|
1985 | 1991 | Note: as a 'hidden' feature, you can also use traditional python slice |
|
1986 | 1992 | notation, where N:M means numbers N through M-1. |
|
1987 | 1993 | |
|
1988 | 1994 | For example, if your history contains (%hist prints it): |
|
1989 | 1995 | |
|
1990 | 1996 | 44: x=1 |
|
1991 | 1997 | 45: y=3 |
|
1992 | 1998 | 46: z=x+y |
|
1993 | 1999 | 47: print x |
|
1994 | 2000 | 48: a=5 |
|
1995 | 2001 | 49: print 'x',x,'y',y |
|
1996 | 2002 | |
|
1997 | 2003 | you can create a macro with lines 44 through 47 (included) and line 49 |
|
1998 | 2004 | called my_macro with: |
|
1999 | 2005 | |
|
2000 | 2006 | In [55]: %macro my_macro 44-47 49 |
|
2001 | 2007 | |
|
2002 | 2008 | Now, typing `my_macro` (without quotes) will re-execute all this code |
|
2003 | 2009 | in one pass. |
|
2004 | 2010 | |
|
2005 | 2011 | You don't need to give the line-numbers in order, and any given line |
|
2006 | 2012 | number can appear multiple times. You can assemble macros with any |
|
2007 | 2013 | lines from your input history in any order. |
|
2008 | 2014 | |
|
2009 | 2015 | The macro is a simple object which holds its value in an attribute, |
|
2010 | 2016 | but IPython's display system checks for macros and executes them as |
|
2011 | 2017 | code instead of printing them when you type their name. |
|
2012 | 2018 | |
|
2013 | 2019 | You can view a macro's contents by explicitly printing it with: |
|
2014 | 2020 | |
|
2015 | 2021 | 'print macro_name'. |
|
2016 | 2022 | |
|
2017 | 2023 | """ |
|
2018 | 2024 | |
|
2019 | 2025 | opts,args = self.parse_options(parameter_s,'r',mode='list') |
|
2020 | 2026 | if not args: # List existing macros |
|
2021 | 2027 | return sorted(k for k,v in self.shell.user_ns.iteritems() if\ |
|
2022 | 2028 | isinstance(v, Macro)) |
|
2023 | 2029 | if len(args) == 1: |
|
2024 | 2030 | raise UsageError( |
|
2025 | 2031 | "%macro insufficient args; usage '%macro name n1-n2 n3-4...") |
|
2026 | 2032 | name, codefrom = args[0], " ".join(args[1:]) |
|
2027 | 2033 | |
|
2028 | 2034 | #print 'rng',ranges # dbg |
|
2029 | 2035 | try: |
|
2030 | 2036 | lines = self.shell.find_user_code(codefrom, 'r' in opts) |
|
2031 | 2037 | except (ValueError, TypeError) as e: |
|
2032 | 2038 | print e.args[0] |
|
2033 | 2039 | return |
|
2034 | 2040 | macro = Macro(lines) |
|
2035 | 2041 | self.shell.define_macro(name, macro) |
|
2036 | 2042 | print 'Macro `%s` created. To execute, type its name (without quotes).' % name |
|
2037 | 2043 | print '=== Macro contents: ===' |
|
2038 | 2044 | print macro, |
|
2039 | 2045 | |
|
2040 | 2046 | def magic_save(self,parameter_s = ''): |
|
2041 | 2047 | """Save a set of lines or a macro to a given filename. |
|
2042 | 2048 | |
|
2043 | 2049 | Usage:\\ |
|
2044 | 2050 | %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ... |
|
2045 | 2051 | |
|
2046 | 2052 | Options: |
|
2047 | 2053 | |
|
2048 | 2054 | -r: use 'raw' input. By default, the 'processed' history is used, |
|
2049 | 2055 | so that magics are loaded in their transformed version to valid |
|
2050 | 2056 | Python. If this option is given, the raw input as typed as the |
|
2051 | 2057 | command line is used instead. |
|
2052 | 2058 | |
|
2053 | 2059 | This function uses the same syntax as %history for input ranges, |
|
2054 | 2060 | then saves the lines to the filename you specify. |
|
2055 | 2061 | |
|
2056 | 2062 | It adds a '.py' extension to the file if you don't do so yourself, and |
|
2057 | 2063 | it asks for confirmation before overwriting existing files.""" |
|
2058 | 2064 | |
|
2059 | 2065 | opts,args = self.parse_options(parameter_s,'r',mode='list') |
|
2060 | 2066 | fname, codefrom = args[0], " ".join(args[1:]) |
|
2061 | 2067 | if not fname.endswith('.py'): |
|
2062 | 2068 | fname += '.py' |
|
2063 | 2069 | if os.path.isfile(fname): |
|
2064 | 2070 | ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname) |
|
2065 | 2071 | if ans.lower() not in ['y','yes']: |
|
2066 | 2072 | print 'Operation cancelled.' |
|
2067 | 2073 | return |
|
2068 | 2074 | try: |
|
2069 | 2075 | cmds = self.shell.find_user_code(codefrom, 'r' in opts) |
|
2070 | 2076 | except (TypeError, ValueError) as e: |
|
2071 | 2077 | print e.args[0] |
|
2072 | 2078 | return |
|
2073 | 2079 | if isinstance(cmds, unicode): |
|
2074 | 2080 | cmds = cmds.encode("utf-8") |
|
2075 | 2081 | with open(fname,'w') as f: |
|
2076 | 2082 | f.write("# coding: utf-8\n") |
|
2077 | 2083 | f.write(cmds) |
|
2078 | 2084 | print 'The following commands were written to file `%s`:' % fname |
|
2079 | 2085 | print cmds |
|
2080 | 2086 | |
|
2081 | 2087 | def magic_pastebin(self, parameter_s = ''): |
|
2082 | 2088 | """Upload code to the 'Lodge it' paste bin, returning the URL.""" |
|
2083 | 2089 | try: |
|
2084 | 2090 | code = self.shell.find_user_code(parameter_s) |
|
2085 | 2091 | except (ValueError, TypeError) as e: |
|
2086 | 2092 | print e.args[0] |
|
2087 | 2093 | return |
|
2088 | 2094 | pbserver = ServerProxy('http://paste.pocoo.org/xmlrpc/') |
|
2089 | 2095 | id = pbserver.pastes.newPaste("python", code) |
|
2090 | 2096 | return "http://paste.pocoo.org/show/" + id |
|
2091 | 2097 | |
|
2092 | 2098 | def _edit_macro(self,mname,macro): |
|
2093 | 2099 | """open an editor with the macro data in a file""" |
|
2094 | 2100 | filename = self.shell.mktempfile(macro.value) |
|
2095 | 2101 | self.shell.hooks.editor(filename) |
|
2096 | 2102 | |
|
2097 | 2103 | # and make a new macro object, to replace the old one |
|
2098 | 2104 | mfile = open(filename) |
|
2099 | 2105 | mvalue = mfile.read() |
|
2100 | 2106 | mfile.close() |
|
2101 | 2107 | self.shell.user_ns[mname] = Macro(mvalue) |
|
2102 | 2108 | |
|
2103 | 2109 | def magic_ed(self,parameter_s=''): |
|
2104 | 2110 | """Alias to %edit.""" |
|
2105 | 2111 | return self.magic_edit(parameter_s) |
|
2106 | 2112 | |
|
2107 | 2113 | @testdec.skip_doctest |
|
2108 | 2114 | def magic_edit(self,parameter_s='',last_call=['','']): |
|
2109 | 2115 | """Bring up an editor and execute the resulting code. |
|
2110 | 2116 | |
|
2111 | 2117 | Usage: |
|
2112 | 2118 | %edit [options] [args] |
|
2113 | 2119 | |
|
2114 | 2120 | %edit runs IPython's editor hook. The default version of this hook is |
|
2115 | 2121 | set to call the __IPYTHON__.rc.editor command. This is read from your |
|
2116 | 2122 | environment variable $EDITOR. If this isn't found, it will default to |
|
2117 | 2123 | vi under Linux/Unix and to notepad under Windows. See the end of this |
|
2118 | 2124 | docstring for how to change the editor hook. |
|
2119 | 2125 | |
|
2120 | 2126 | You can also set the value of this editor via the command line option |
|
2121 | 2127 | '-editor' or in your ipythonrc file. This is useful if you wish to use |
|
2122 | 2128 | specifically for IPython an editor different from your typical default |
|
2123 | 2129 | (and for Windows users who typically don't set environment variables). |
|
2124 | 2130 | |
|
2125 | 2131 | This command allows you to conveniently edit multi-line code right in |
|
2126 | 2132 | your IPython session. |
|
2127 | 2133 | |
|
2128 | 2134 | If called without arguments, %edit opens up an empty editor with a |
|
2129 | 2135 | temporary file and will execute the contents of this file when you |
|
2130 | 2136 | close it (don't forget to save it!). |
|
2131 | 2137 | |
|
2132 | 2138 | |
|
2133 | 2139 | Options: |
|
2134 | 2140 | |
|
2135 | 2141 | -n <number>: open the editor at a specified line number. By default, |
|
2136 | 2142 | the IPython editor hook uses the unix syntax 'editor +N filename', but |
|
2137 | 2143 | you can configure this by providing your own modified hook if your |
|
2138 | 2144 | favorite editor supports line-number specifications with a different |
|
2139 | 2145 | syntax. |
|
2140 | 2146 | |
|
2141 | 2147 | -p: this will call the editor with the same data as the previous time |
|
2142 | 2148 | it was used, regardless of how long ago (in your current session) it |
|
2143 | 2149 | was. |
|
2144 | 2150 | |
|
2145 | 2151 | -r: use 'raw' input. This option only applies to input taken from the |
|
2146 | 2152 | user's history. By default, the 'processed' history is used, so that |
|
2147 | 2153 | magics are loaded in their transformed version to valid Python. If |
|
2148 | 2154 | this option is given, the raw input as typed as the command line is |
|
2149 | 2155 | used instead. When you exit the editor, it will be executed by |
|
2150 | 2156 | IPython's own processor. |
|
2151 | 2157 | |
|
2152 | 2158 | -x: do not execute the edited code immediately upon exit. This is |
|
2153 | 2159 | mainly useful if you are editing programs which need to be called with |
|
2154 | 2160 | command line arguments, which you can then do using %run. |
|
2155 | 2161 | |
|
2156 | 2162 | |
|
2157 | 2163 | Arguments: |
|
2158 | 2164 | |
|
2159 | 2165 | If arguments are given, the following possibilites exist: |
|
2160 | 2166 | |
|
2161 | 2167 | - If the argument is a filename, IPython will load that into the |
|
2162 | 2168 | editor. It will execute its contents with execfile() when you exit, |
|
2163 | 2169 | loading any code in the file into your interactive namespace. |
|
2164 | 2170 | |
|
2165 | 2171 | - The arguments are ranges of input history, e.g. "7 ~1/4-6". |
|
2166 | 2172 | The syntax is the same as in the %history magic. |
|
2167 | 2173 | |
|
2168 | 2174 | - If the argument is a string variable, its contents are loaded |
|
2169 | 2175 | into the editor. You can thus edit any string which contains |
|
2170 | 2176 | python code (including the result of previous edits). |
|
2171 | 2177 | |
|
2172 | 2178 | - If the argument is the name of an object (other than a string), |
|
2173 | 2179 | IPython will try to locate the file where it was defined and open the |
|
2174 | 2180 | editor at the point where it is defined. You can use `%edit function` |
|
2175 | 2181 | to load an editor exactly at the point where 'function' is defined, |
|
2176 | 2182 | edit it and have the file be executed automatically. |
|
2177 | 2183 | |
|
2178 | 2184 | If the object is a macro (see %macro for details), this opens up your |
|
2179 | 2185 | specified editor with a temporary file containing the macro's data. |
|
2180 | 2186 | Upon exit, the macro is reloaded with the contents of the file. |
|
2181 | 2187 | |
|
2182 | 2188 | Note: opening at an exact line is only supported under Unix, and some |
|
2183 | 2189 | editors (like kedit and gedit up to Gnome 2.8) do not understand the |
|
2184 | 2190 | '+NUMBER' parameter necessary for this feature. Good editors like |
|
2185 | 2191 | (X)Emacs, vi, jed, pico and joe all do. |
|
2186 | 2192 | |
|
2187 | 2193 | After executing your code, %edit will return as output the code you |
|
2188 | 2194 | typed in the editor (except when it was an existing file). This way |
|
2189 | 2195 | you can reload the code in further invocations of %edit as a variable, |
|
2190 | 2196 | via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of |
|
2191 | 2197 | the output. |
|
2192 | 2198 | |
|
2193 | 2199 | Note that %edit is also available through the alias %ed. |
|
2194 | 2200 | |
|
2195 | 2201 | This is an example of creating a simple function inside the editor and |
|
2196 | 2202 | then modifying it. First, start up the editor: |
|
2197 | 2203 | |
|
2198 | 2204 | In [1]: ed |
|
2199 | 2205 | Editing... done. Executing edited code... |
|
2200 | 2206 | Out[1]: 'def foo():n print "foo() was defined in an editing session"n' |
|
2201 | 2207 | |
|
2202 | 2208 | We can then call the function foo(): |
|
2203 | 2209 | |
|
2204 | 2210 | In [2]: foo() |
|
2205 | 2211 | foo() was defined in an editing session |
|
2206 | 2212 | |
|
2207 | 2213 | Now we edit foo. IPython automatically loads the editor with the |
|
2208 | 2214 | (temporary) file where foo() was previously defined: |
|
2209 | 2215 | |
|
2210 | 2216 | In [3]: ed foo |
|
2211 | 2217 | Editing... done. Executing edited code... |
|
2212 | 2218 | |
|
2213 | 2219 | And if we call foo() again we get the modified version: |
|
2214 | 2220 | |
|
2215 | 2221 | In [4]: foo() |
|
2216 | 2222 | foo() has now been changed! |
|
2217 | 2223 | |
|
2218 | 2224 | Here is an example of how to edit a code snippet successive |
|
2219 | 2225 | times. First we call the editor: |
|
2220 | 2226 | |
|
2221 | 2227 | In [5]: ed |
|
2222 | 2228 | Editing... done. Executing edited code... |
|
2223 | 2229 | hello |
|
2224 | 2230 | Out[5]: "print 'hello'n" |
|
2225 | 2231 | |
|
2226 | 2232 | Now we call it again with the previous output (stored in _): |
|
2227 | 2233 | |
|
2228 | 2234 | In [6]: ed _ |
|
2229 | 2235 | Editing... done. Executing edited code... |
|
2230 | 2236 | hello world |
|
2231 | 2237 | Out[6]: "print 'hello world'n" |
|
2232 | 2238 | |
|
2233 | 2239 | Now we call it with the output #8 (stored in _8, also as Out[8]): |
|
2234 | 2240 | |
|
2235 | 2241 | In [7]: ed _8 |
|
2236 | 2242 | Editing... done. Executing edited code... |
|
2237 | 2243 | hello again |
|
2238 | 2244 | Out[7]: "print 'hello again'n" |
|
2239 | 2245 | |
|
2240 | 2246 | |
|
2241 | 2247 | Changing the default editor hook: |
|
2242 | 2248 | |
|
2243 | 2249 | If you wish to write your own editor hook, you can put it in a |
|
2244 | 2250 | configuration file which you load at startup time. The default hook |
|
2245 | 2251 | is defined in the IPython.core.hooks module, and you can use that as a |
|
2246 | 2252 | starting example for further modifications. That file also has |
|
2247 | 2253 | general instructions on how to set a new hook for use once you've |
|
2248 | 2254 | defined it.""" |
|
2249 | 2255 | |
|
2250 | 2256 | # FIXME: This function has become a convoluted mess. It needs a |
|
2251 | 2257 | # ground-up rewrite with clean, simple logic. |
|
2252 | 2258 | |
|
2253 | 2259 | def make_filename(arg): |
|
2254 | 2260 | "Make a filename from the given args" |
|
2255 | 2261 | try: |
|
2256 | 2262 | filename = get_py_filename(arg) |
|
2257 | 2263 | except IOError: |
|
2258 | 2264 | if args.endswith('.py'): |
|
2259 | 2265 | filename = arg |
|
2260 | 2266 | else: |
|
2261 | 2267 | filename = None |
|
2262 | 2268 | return filename |
|
2263 | 2269 | |
|
2264 | 2270 | # custom exceptions |
|
2265 | 2271 | class DataIsObject(Exception): pass |
|
2266 | 2272 | |
|
2267 | 2273 | opts,args = self.parse_options(parameter_s,'prxn:') |
|
2268 | 2274 | # Set a few locals from the options for convenience: |
|
2269 | 2275 | opts_prev = 'p' in opts |
|
2270 | 2276 | opts_raw = 'r' in opts |
|
2271 | 2277 | |
|
2272 | 2278 | # Default line number value |
|
2273 | 2279 | lineno = opts.get('n',None) |
|
2274 | 2280 | |
|
2275 | 2281 | if opts_prev: |
|
2276 | 2282 | args = '_%s' % last_call[0] |
|
2277 | 2283 | if not self.shell.user_ns.has_key(args): |
|
2278 | 2284 | args = last_call[1] |
|
2279 | 2285 | |
|
2280 | 2286 | # use last_call to remember the state of the previous call, but don't |
|
2281 | 2287 | # let it be clobbered by successive '-p' calls. |
|
2282 | 2288 | try: |
|
2283 | 2289 | last_call[0] = self.shell.displayhook.prompt_count |
|
2284 | 2290 | if not opts_prev: |
|
2285 | 2291 | last_call[1] = parameter_s |
|
2286 | 2292 | except: |
|
2287 | 2293 | pass |
|
2288 | 2294 | |
|
2289 | 2295 | # by default this is done with temp files, except when the given |
|
2290 | 2296 | # arg is a filename |
|
2291 | 2297 | use_temp = True |
|
2292 | 2298 | |
|
2293 | 2299 | data = '' |
|
2294 | 2300 | if args.endswith('.py'): |
|
2295 | 2301 | filename = make_filename(args) |
|
2296 | 2302 | use_temp = False |
|
2297 | 2303 | elif args: |
|
2298 | 2304 | # Mode where user specifies ranges of lines, like in %macro. |
|
2299 | 2305 | data = self.extract_input_lines(args, opts_raw) |
|
2300 | 2306 | if not data: |
|
2301 | 2307 | try: |
|
2302 | 2308 | # Load the parameter given as a variable. If not a string, |
|
2303 | 2309 | # process it as an object instead (below) |
|
2304 | 2310 | |
|
2305 | 2311 | #print '*** args',args,'type',type(args) # dbg |
|
2306 | 2312 | data = eval(args, self.shell.user_ns) |
|
2307 | 2313 | if not isinstance(data, basestring): |
|
2308 | 2314 | raise DataIsObject |
|
2309 | 2315 | |
|
2310 | 2316 | except (NameError,SyntaxError): |
|
2311 | 2317 | # given argument is not a variable, try as a filename |
|
2312 | 2318 | filename = make_filename(args) |
|
2313 | 2319 | if filename is None: |
|
2314 | 2320 | warn("Argument given (%s) can't be found as a variable " |
|
2315 | 2321 | "or as a filename." % args) |
|
2316 | 2322 | return |
|
2317 | 2323 | use_temp = False |
|
2318 | 2324 | |
|
2319 | 2325 | except DataIsObject: |
|
2320 | 2326 | # macros have a special edit function |
|
2321 | 2327 | if isinstance(data, Macro): |
|
2322 | 2328 | self._edit_macro(args,data) |
|
2323 | 2329 | return |
|
2324 | 2330 | |
|
2325 | 2331 | # For objects, try to edit the file where they are defined |
|
2326 | 2332 | try: |
|
2327 | 2333 | filename = inspect.getabsfile(data) |
|
2328 | 2334 | if 'fakemodule' in filename.lower() and inspect.isclass(data): |
|
2329 | 2335 | # class created by %edit? Try to find source |
|
2330 | 2336 | # by looking for method definitions instead, the |
|
2331 | 2337 | # __module__ in those classes is FakeModule. |
|
2332 | 2338 | attrs = [getattr(data, aname) for aname in dir(data)] |
|
2333 | 2339 | for attr in attrs: |
|
2334 | 2340 | if not inspect.ismethod(attr): |
|
2335 | 2341 | continue |
|
2336 | 2342 | filename = inspect.getabsfile(attr) |
|
2337 | 2343 | if filename and 'fakemodule' not in filename.lower(): |
|
2338 | 2344 | # change the attribute to be the edit target instead |
|
2339 | 2345 | data = attr |
|
2340 | 2346 | break |
|
2341 | 2347 | |
|
2342 | 2348 | datafile = 1 |
|
2343 | 2349 | except TypeError: |
|
2344 | 2350 | filename = make_filename(args) |
|
2345 | 2351 | datafile = 1 |
|
2346 | 2352 | warn('Could not find file where `%s` is defined.\n' |
|
2347 | 2353 | 'Opening a file named `%s`' % (args,filename)) |
|
2348 | 2354 | # Now, make sure we can actually read the source (if it was in |
|
2349 | 2355 | # a temp file it's gone by now). |
|
2350 | 2356 | if datafile: |
|
2351 | 2357 | try: |
|
2352 | 2358 | if lineno is None: |
|
2353 | 2359 | lineno = inspect.getsourcelines(data)[1] |
|
2354 | 2360 | except IOError: |
|
2355 | 2361 | filename = make_filename(args) |
|
2356 | 2362 | if filename is None: |
|
2357 | 2363 | warn('The file `%s` where `%s` was defined cannot ' |
|
2358 | 2364 | 'be read.' % (filename,data)) |
|
2359 | 2365 | return |
|
2360 | 2366 | use_temp = False |
|
2361 | 2367 | |
|
2362 | 2368 | if use_temp: |
|
2363 | 2369 | filename = self.shell.mktempfile(data) |
|
2364 | 2370 | print 'IPython will make a temporary file named:',filename |
|
2365 | 2371 | |
|
2366 | 2372 | # do actual editing here |
|
2367 | 2373 | print 'Editing...', |
|
2368 | 2374 | sys.stdout.flush() |
|
2369 | 2375 | try: |
|
2370 | 2376 | # Quote filenames that may have spaces in them |
|
2371 | 2377 | if ' ' in filename: |
|
2372 | 2378 | filename = "%s" % filename |
|
2373 | 2379 | self.shell.hooks.editor(filename,lineno) |
|
2374 | 2380 | except TryNext: |
|
2375 | 2381 | warn('Could not open editor') |
|
2376 | 2382 | return |
|
2377 | 2383 | |
|
2378 | 2384 | # XXX TODO: should this be generalized for all string vars? |
|
2379 | 2385 | # For now, this is special-cased to blocks created by cpaste |
|
2380 | 2386 | if args.strip() == 'pasted_block': |
|
2381 | 2387 | self.shell.user_ns['pasted_block'] = file_read(filename) |
|
2382 | 2388 | |
|
2383 | 2389 | if 'x' in opts: # -x prevents actual execution |
|
2384 | 2390 | |
|
2385 | 2391 | else: |
|
2386 | 2392 | print 'done. Executing edited code...' |
|
2387 | 2393 | if opts_raw: |
|
2388 | 2394 | self.shell.run_cell(file_read(filename), |
|
2389 | 2395 | store_history=False) |
|
2390 | 2396 | else: |
|
2391 | 2397 | self.shell.safe_execfile(filename,self.shell.user_ns, |
|
2392 | 2398 | self.shell.user_ns) |
|
2393 | 2399 | |
|
2394 | 2400 | |
|
2395 | 2401 | if use_temp: |
|
2396 | 2402 | try: |
|
2397 | 2403 | return open(filename).read() |
|
2398 | 2404 | except IOError,msg: |
|
2399 | 2405 | if msg.filename == filename: |
|
2400 | 2406 | warn('File not found. Did you forget to save?') |
|
2401 | 2407 | return |
|
2402 | 2408 | else: |
|
2403 | 2409 | self.shell.showtraceback() |
|
2404 | 2410 | |
|
2405 | 2411 | def magic_xmode(self,parameter_s = ''): |
|
2406 | 2412 | """Switch modes for the exception handlers. |
|
2407 | 2413 | |
|
2408 | 2414 | Valid modes: Plain, Context and Verbose. |
|
2409 | 2415 | |
|
2410 | 2416 | If called without arguments, acts as a toggle.""" |
|
2411 | 2417 | |
|
2412 | 2418 | def xmode_switch_err(name): |
|
2413 | 2419 | warn('Error changing %s exception modes.\n%s' % |
|
2414 | 2420 | (name,sys.exc_info()[1])) |
|
2415 | 2421 | |
|
2416 | 2422 | shell = self.shell |
|
2417 | 2423 | new_mode = parameter_s.strip().capitalize() |
|
2418 | 2424 | try: |
|
2419 | 2425 | shell.InteractiveTB.set_mode(mode=new_mode) |
|
2420 | 2426 | print 'Exception reporting mode:',shell.InteractiveTB.mode |
|
2421 | 2427 | except: |
|
2422 | 2428 | xmode_switch_err('user') |
|
2423 | 2429 | |
|
2424 | 2430 | def magic_colors(self,parameter_s = ''): |
|
2425 | 2431 | """Switch color scheme for prompts, info system and exception handlers. |
|
2426 | 2432 | |
|
2427 | 2433 | Currently implemented schemes: NoColor, Linux, LightBG. |
|
2428 | 2434 | |
|
2429 | 2435 | Color scheme names are not case-sensitive. |
|
2430 | 2436 | |
|
2431 | 2437 | Examples |
|
2432 | 2438 | -------- |
|
2433 | 2439 | To get a plain black and white terminal:: |
|
2434 | 2440 | |
|
2435 | 2441 | %colors nocolor |
|
2436 | 2442 | """ |
|
2437 | 2443 | |
|
2438 | 2444 | def color_switch_err(name): |
|
2439 | 2445 | warn('Error changing %s color schemes.\n%s' % |
|
2440 | 2446 | (name,sys.exc_info()[1])) |
|
2441 | 2447 | |
|
2442 | 2448 | |
|
2443 | 2449 | new_scheme = parameter_s.strip() |
|
2444 | 2450 | if not new_scheme: |
|
2445 | 2451 | raise UsageError( |
|
2446 | 2452 | "%colors: you must specify a color scheme. See '%colors?'") |
|
2447 | 2453 | return |
|
2448 | 2454 | # local shortcut |
|
2449 | 2455 | shell = self.shell |
|
2450 | 2456 | |
|
2451 | 2457 | import IPython.utils.rlineimpl as readline |
|
2452 | 2458 | |
|
2453 | 2459 | if not readline.have_readline and sys.platform == "win32": |
|
2454 | 2460 | msg = """\ |
|
2455 | 2461 | Proper color support under MS Windows requires the pyreadline library. |
|
2456 | 2462 | You can find it at: |
|
2457 | 2463 | http://ipython.scipy.org/moin/PyReadline/Intro |
|
2458 | 2464 | Gary's readline needs the ctypes module, from: |
|
2459 | 2465 | http://starship.python.net/crew/theller/ctypes |
|
2460 | 2466 | (Note that ctypes is already part of Python versions 2.5 and newer). |
|
2461 | 2467 | |
|
2462 | 2468 | Defaulting color scheme to 'NoColor'""" |
|
2463 | 2469 | new_scheme = 'NoColor' |
|
2464 | 2470 | warn(msg) |
|
2465 | 2471 | |
|
2466 | 2472 | # readline option is 0 |
|
2467 | 2473 | if not shell.has_readline: |
|
2468 | 2474 | new_scheme = 'NoColor' |
|
2469 | 2475 | |
|
2470 | 2476 | # Set prompt colors |
|
2471 | 2477 | try: |
|
2472 | 2478 | shell.displayhook.set_colors(new_scheme) |
|
2473 | 2479 | except: |
|
2474 | 2480 | color_switch_err('prompt') |
|
2475 | 2481 | else: |
|
2476 | 2482 | shell.colors = \ |
|
2477 | 2483 | shell.displayhook.color_table.active_scheme_name |
|
2478 | 2484 | # Set exception colors |
|
2479 | 2485 | try: |
|
2480 | 2486 | shell.InteractiveTB.set_colors(scheme = new_scheme) |
|
2481 | 2487 | shell.SyntaxTB.set_colors(scheme = new_scheme) |
|
2482 | 2488 | except: |
|
2483 | 2489 | color_switch_err('exception') |
|
2484 | 2490 | |
|
2485 | 2491 | # Set info (for 'object?') colors |
|
2486 | 2492 | if shell.color_info: |
|
2487 | 2493 | try: |
|
2488 | 2494 | shell.inspector.set_active_scheme(new_scheme) |
|
2489 | 2495 | except: |
|
2490 | 2496 | color_switch_err('object inspector') |
|
2491 | 2497 | else: |
|
2492 | 2498 | shell.inspector.set_active_scheme('NoColor') |
|
2493 | 2499 | |
|
2494 | 2500 | def magic_pprint(self, parameter_s=''): |
|
2495 | 2501 | """Toggle pretty printing on/off.""" |
|
2496 | 2502 | ptformatter = self.shell.display_formatter.formatters['text/plain'] |
|
2497 | 2503 | ptformatter.pprint = bool(1 - ptformatter.pprint) |
|
2498 | 2504 | print 'Pretty printing has been turned', \ |
|
2499 | 2505 | ['OFF','ON'][ptformatter.pprint] |
|
2500 | 2506 | |
|
2501 | 2507 | def magic_Exit(self, parameter_s=''): |
|
2502 | 2508 | """Exit IPython.""" |
|
2503 | 2509 | |
|
2504 | 2510 | self.shell.ask_exit() |
|
2505 | 2511 | |
|
2506 | 2512 | # Add aliases as magics so all common forms work: exit, quit, Exit, Quit. |
|
2507 | 2513 | magic_exit = magic_quit = magic_Quit = magic_Exit |
|
2508 | 2514 | |
|
2509 | 2515 | #...................................................................... |
|
2510 | 2516 | # Functions to implement unix shell-type things |
|
2511 | 2517 | |
|
2512 | 2518 | @testdec.skip_doctest |
|
2513 | 2519 | def magic_alias(self, parameter_s = ''): |
|
2514 | 2520 | """Define an alias for a system command. |
|
2515 | 2521 | |
|
2516 | 2522 | '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd' |
|
2517 | 2523 | |
|
2518 | 2524 | Then, typing 'alias_name params' will execute the system command 'cmd |
|
2519 | 2525 | params' (from your underlying operating system). |
|
2520 | 2526 | |
|
2521 | 2527 | Aliases have lower precedence than magic functions and Python normal |
|
2522 | 2528 | variables, so if 'foo' is both a Python variable and an alias, the |
|
2523 | 2529 | alias can not be executed until 'del foo' removes the Python variable. |
|
2524 | 2530 | |
|
2525 | 2531 | You can use the %l specifier in an alias definition to represent the |
|
2526 | 2532 | whole line when the alias is called. For example: |
|
2527 | 2533 | |
|
2528 | 2534 | In [2]: alias bracket echo "Input in brackets: <%l>" |
|
2529 | 2535 | In [3]: bracket hello world |
|
2530 | 2536 | Input in brackets: <hello world> |
|
2531 | 2537 | |
|
2532 | 2538 | You can also define aliases with parameters using %s specifiers (one |
|
2533 | 2539 | per parameter): |
|
2534 | 2540 | |
|
2535 | 2541 | In [1]: alias parts echo first %s second %s |
|
2536 | 2542 | In [2]: %parts A B |
|
2537 | 2543 | first A second B |
|
2538 | 2544 | In [3]: %parts A |
|
2539 | 2545 | Incorrect number of arguments: 2 expected. |
|
2540 | 2546 | parts is an alias to: 'echo first %s second %s' |
|
2541 | 2547 | |
|
2542 | 2548 | Note that %l and %s are mutually exclusive. You can only use one or |
|
2543 | 2549 | the other in your aliases. |
|
2544 | 2550 | |
|
2545 | 2551 | Aliases expand Python variables just like system calls using ! or !! |
|
2546 | 2552 | do: all expressions prefixed with '$' get expanded. For details of |
|
2547 | 2553 | the semantic rules, see PEP-215: |
|
2548 | 2554 | http://www.python.org/peps/pep-0215.html. This is the library used by |
|
2549 | 2555 | IPython for variable expansion. If you want to access a true shell |
|
2550 | 2556 | variable, an extra $ is necessary to prevent its expansion by IPython: |
|
2551 | 2557 | |
|
2552 | 2558 | In [6]: alias show echo |
|
2553 | 2559 | In [7]: PATH='A Python string' |
|
2554 | 2560 | In [8]: show $PATH |
|
2555 | 2561 | A Python string |
|
2556 | 2562 | In [9]: show $$PATH |
|
2557 | 2563 | /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:... |
|
2558 | 2564 | |
|
2559 | 2565 | You can use the alias facility to acess all of $PATH. See the %rehash |
|
2560 | 2566 | and %rehashx functions, which automatically create aliases for the |
|
2561 | 2567 | contents of your $PATH. |
|
2562 | 2568 | |
|
2563 | 2569 | If called with no parameters, %alias prints the current alias table.""" |
|
2564 | 2570 | |
|
2565 | 2571 | par = parameter_s.strip() |
|
2566 | 2572 | if not par: |
|
2567 | 2573 | stored = self.db.get('stored_aliases', {} ) |
|
2568 | 2574 | aliases = sorted(self.shell.alias_manager.aliases) |
|
2569 | 2575 | # for k, v in stored: |
|
2570 | 2576 | # atab.append(k, v[0]) |
|
2571 | 2577 | |
|
2572 | 2578 | print "Total number of aliases:", len(aliases) |
|
2573 | 2579 | sys.stdout.flush() |
|
2574 | 2580 | return aliases |
|
2575 | 2581 | |
|
2576 | 2582 | # Now try to define a new one |
|
2577 | 2583 | try: |
|
2578 | 2584 | alias,cmd = par.split(None, 1) |
|
2579 | 2585 | except: |
|
2580 | 2586 | print oinspect.getdoc(self.magic_alias) |
|
2581 | 2587 | else: |
|
2582 | 2588 | self.shell.alias_manager.soft_define_alias(alias, cmd) |
|
2583 | 2589 | # end magic_alias |
|
2584 | 2590 | |
|
2585 | 2591 | def magic_unalias(self, parameter_s = ''): |
|
2586 | 2592 | """Remove an alias""" |
|
2587 | 2593 | |
|
2588 | 2594 | aname = parameter_s.strip() |
|
2589 | 2595 | self.shell.alias_manager.undefine_alias(aname) |
|
2590 | 2596 | stored = self.db.get('stored_aliases', {} ) |
|
2591 | 2597 | if aname in stored: |
|
2592 | 2598 | print "Removing %stored alias",aname |
|
2593 | 2599 | del stored[aname] |
|
2594 | 2600 | self.db['stored_aliases'] = stored |
|
2595 | 2601 | |
|
2596 | 2602 | def magic_rehashx(self, parameter_s = ''): |
|
2597 | 2603 | """Update the alias table with all executable files in $PATH. |
|
2598 | 2604 | |
|
2599 | 2605 | This version explicitly checks that every entry in $PATH is a file |
|
2600 | 2606 | with execute access (os.X_OK), so it is much slower than %rehash. |
|
2601 | 2607 | |
|
2602 | 2608 | Under Windows, it checks executability as a match agains a |
|
2603 | 2609 | '|'-separated string of extensions, stored in the IPython config |
|
2604 | 2610 | variable win_exec_ext. This defaults to 'exe|com|bat'. |
|
2605 | 2611 | |
|
2606 | 2612 | This function also resets the root module cache of module completer, |
|
2607 | 2613 | used on slow filesystems. |
|
2608 | 2614 | """ |
|
2609 | 2615 | from IPython.core.alias import InvalidAliasError |
|
2610 | 2616 | |
|
2611 | 2617 | # for the benefit of module completer in ipy_completers.py |
|
2612 | 2618 | del self.db['rootmodules'] |
|
2613 | 2619 | |
|
2614 | 2620 | path = [os.path.abspath(os.path.expanduser(p)) for p in |
|
2615 | 2621 | os.environ.get('PATH','').split(os.pathsep)] |
|
2616 | 2622 | path = filter(os.path.isdir,path) |
|
2617 | 2623 | |
|
2618 | 2624 | syscmdlist = [] |
|
2619 | 2625 | # Now define isexec in a cross platform manner. |
|
2620 | 2626 | if os.name == 'posix': |
|
2621 | 2627 | isexec = lambda fname:os.path.isfile(fname) and \ |
|
2622 | 2628 | os.access(fname,os.X_OK) |
|
2623 | 2629 | else: |
|
2624 | 2630 | try: |
|
2625 | 2631 | winext = os.environ['pathext'].replace(';','|').replace('.','') |
|
2626 | 2632 | except KeyError: |
|
2627 | 2633 | winext = 'exe|com|bat|py' |
|
2628 | 2634 | if 'py' not in winext: |
|
2629 | 2635 | winext += '|py' |
|
2630 | 2636 | execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE) |
|
2631 | 2637 | isexec = lambda fname:os.path.isfile(fname) and execre.match(fname) |
|
2632 | 2638 | savedir = os.getcwd() |
|
2633 | 2639 | |
|
2634 | 2640 | # Now walk the paths looking for executables to alias. |
|
2635 | 2641 | try: |
|
2636 | 2642 | # write the whole loop for posix/Windows so we don't have an if in |
|
2637 | 2643 | # the innermost part |
|
2638 | 2644 | if os.name == 'posix': |
|
2639 | 2645 | for pdir in path: |
|
2640 | 2646 | os.chdir(pdir) |
|
2641 | 2647 | for ff in os.listdir(pdir): |
|
2642 | 2648 | if isexec(ff): |
|
2643 | 2649 | try: |
|
2644 | 2650 | # Removes dots from the name since ipython |
|
2645 | 2651 | # will assume names with dots to be python. |
|
2646 | 2652 | self.shell.alias_manager.define_alias( |
|
2647 | 2653 | ff.replace('.',''), ff) |
|
2648 | 2654 | except InvalidAliasError: |
|
2649 | 2655 | pass |
|
2650 | 2656 | else: |
|
2651 | 2657 | syscmdlist.append(ff) |
|
2652 | 2658 | else: |
|
2653 | 2659 | no_alias = self.shell.alias_manager.no_alias |
|
2654 | 2660 | for pdir in path: |
|
2655 | 2661 | os.chdir(pdir) |
|
2656 | 2662 | for ff in os.listdir(pdir): |
|
2657 | 2663 | base, ext = os.path.splitext(ff) |
|
2658 | 2664 | if isexec(ff) and base.lower() not in no_alias: |
|
2659 | 2665 | if ext.lower() == '.exe': |
|
2660 | 2666 | ff = base |
|
2661 | 2667 | try: |
|
2662 | 2668 | # Removes dots from the name since ipython |
|
2663 | 2669 | # will assume names with dots to be python. |
|
2664 | 2670 | self.shell.alias_manager.define_alias( |
|
2665 | 2671 | base.lower().replace('.',''), ff) |
|
2666 | 2672 | except InvalidAliasError: |
|
2667 | 2673 | pass |
|
2668 | 2674 | syscmdlist.append(ff) |
|
2669 | 2675 | db = self.db |
|
2670 | 2676 | db['syscmdlist'] = syscmdlist |
|
2671 | 2677 | finally: |
|
2672 | 2678 | os.chdir(savedir) |
|
2673 | 2679 | |
|
2674 | 2680 | @testdec.skip_doctest |
|
2675 | 2681 | def magic_pwd(self, parameter_s = ''): |
|
2676 | 2682 | """Return the current working directory path. |
|
2677 | 2683 | |
|
2678 | 2684 | Examples |
|
2679 | 2685 | -------- |
|
2680 | 2686 | :: |
|
2681 | 2687 | |
|
2682 | 2688 | In [9]: pwd |
|
2683 | 2689 | Out[9]: '/home/tsuser/sprint/ipython' |
|
2684 | 2690 | """ |
|
2685 | 2691 | return os.getcwd() |
|
2686 | 2692 | |
|
2687 | 2693 | @testdec.skip_doctest |
|
2688 | 2694 | def magic_cd(self, parameter_s=''): |
|
2689 | 2695 | """Change the current working directory. |
|
2690 | 2696 | |
|
2691 | 2697 | This command automatically maintains an internal list of directories |
|
2692 | 2698 | you visit during your IPython session, in the variable _dh. The |
|
2693 | 2699 | command %dhist shows this history nicely formatted. You can also |
|
2694 | 2700 | do 'cd -<tab>' to see directory history conveniently. |
|
2695 | 2701 | |
|
2696 | 2702 | Usage: |
|
2697 | 2703 | |
|
2698 | 2704 | cd 'dir': changes to directory 'dir'. |
|
2699 | 2705 | |
|
2700 | 2706 | cd -: changes to the last visited directory. |
|
2701 | 2707 | |
|
2702 | 2708 | cd -<n>: changes to the n-th directory in the directory history. |
|
2703 | 2709 | |
|
2704 | 2710 | cd --foo: change to directory that matches 'foo' in history |
|
2705 | 2711 | |
|
2706 | 2712 | cd -b <bookmark_name>: jump to a bookmark set by %bookmark |
|
2707 | 2713 | (note: cd <bookmark_name> is enough if there is no |
|
2708 | 2714 | directory <bookmark_name>, but a bookmark with the name exists.) |
|
2709 | 2715 | 'cd -b <tab>' allows you to tab-complete bookmark names. |
|
2710 | 2716 | |
|
2711 | 2717 | Options: |
|
2712 | 2718 | |
|
2713 | 2719 | -q: quiet. Do not print the working directory after the cd command is |
|
2714 | 2720 | executed. By default IPython's cd command does print this directory, |
|
2715 | 2721 | since the default prompts do not display path information. |
|
2716 | 2722 | |
|
2717 | 2723 | Note that !cd doesn't work for this purpose because the shell where |
|
2718 | 2724 | !command runs is immediately discarded after executing 'command'. |
|
2719 | 2725 | |
|
2720 | 2726 | Examples |
|
2721 | 2727 | -------- |
|
2722 | 2728 | :: |
|
2723 | 2729 | |
|
2724 | 2730 | In [10]: cd parent/child |
|
2725 | 2731 | /home/tsuser/parent/child |
|
2726 | 2732 | """ |
|
2727 | 2733 | |
|
2728 | 2734 | parameter_s = parameter_s.strip() |
|
2729 | 2735 | #bkms = self.shell.persist.get("bookmarks",{}) |
|
2730 | 2736 | |
|
2731 | 2737 | oldcwd = os.getcwd() |
|
2732 | 2738 | numcd = re.match(r'(-)(\d+)$',parameter_s) |
|
2733 | 2739 | # jump in directory history by number |
|
2734 | 2740 | if numcd: |
|
2735 | 2741 | nn = int(numcd.group(2)) |
|
2736 | 2742 | try: |
|
2737 | 2743 | ps = self.shell.user_ns['_dh'][nn] |
|
2738 | 2744 | except IndexError: |
|
2739 | 2745 | print 'The requested directory does not exist in history.' |
|
2740 | 2746 | return |
|
2741 | 2747 | else: |
|
2742 | 2748 | opts = {} |
|
2743 | 2749 | elif parameter_s.startswith('--'): |
|
2744 | 2750 | ps = None |
|
2745 | 2751 | fallback = None |
|
2746 | 2752 | pat = parameter_s[2:] |
|
2747 | 2753 | dh = self.shell.user_ns['_dh'] |
|
2748 | 2754 | # first search only by basename (last component) |
|
2749 | 2755 | for ent in reversed(dh): |
|
2750 | 2756 | if pat in os.path.basename(ent) and os.path.isdir(ent): |
|
2751 | 2757 | ps = ent |
|
2752 | 2758 | break |
|
2753 | 2759 | |
|
2754 | 2760 | if fallback is None and pat in ent and os.path.isdir(ent): |
|
2755 | 2761 | fallback = ent |
|
2756 | 2762 | |
|
2757 | 2763 | # if we have no last part match, pick the first full path match |
|
2758 | 2764 | if ps is None: |
|
2759 | 2765 | ps = fallback |
|
2760 | 2766 | |
|
2761 | 2767 | if ps is None: |
|
2762 | 2768 | print "No matching entry in directory history" |
|
2763 | 2769 | return |
|
2764 | 2770 | else: |
|
2765 | 2771 | opts = {} |
|
2766 | 2772 | |
|
2767 | 2773 | |
|
2768 | 2774 | else: |
|
2769 | 2775 | #turn all non-space-escaping backslashes to slashes, |
|
2770 | 2776 | # for c:\windows\directory\names\ |
|
2771 | 2777 | parameter_s = re.sub(r'\\(?! )','/', parameter_s) |
|
2772 | 2778 | opts,ps = self.parse_options(parameter_s,'qb',mode='string') |
|
2773 | 2779 | # jump to previous |
|
2774 | 2780 | if ps == '-': |
|
2775 | 2781 | try: |
|
2776 | 2782 | ps = self.shell.user_ns['_dh'][-2] |
|
2777 | 2783 | except IndexError: |
|
2778 | 2784 | raise UsageError('%cd -: No previous directory to change to.') |
|
2779 | 2785 | # jump to bookmark if needed |
|
2780 | 2786 | else: |
|
2781 | 2787 | if not os.path.isdir(ps) or opts.has_key('b'): |
|
2782 | 2788 | bkms = self.db.get('bookmarks', {}) |
|
2783 | 2789 | |
|
2784 | 2790 | if bkms.has_key(ps): |
|
2785 | 2791 | target = bkms[ps] |
|
2786 | 2792 | print '(bookmark:%s) -> %s' % (ps,target) |
|
2787 | 2793 | ps = target |
|
2788 | 2794 | else: |
|
2789 | 2795 | if opts.has_key('b'): |
|
2790 | 2796 | raise UsageError("Bookmark '%s' not found. " |
|
2791 | 2797 | "Use '%%bookmark -l' to see your bookmarks." % ps) |
|
2792 | 2798 | |
|
2793 | 2799 | # at this point ps should point to the target dir |
|
2794 | 2800 | if ps: |
|
2795 | 2801 | try: |
|
2796 | 2802 | os.chdir(os.path.expanduser(ps)) |
|
2797 | 2803 | if hasattr(self.shell, 'term_title') and self.shell.term_title: |
|
2798 | 2804 | set_term_title('IPython: ' + abbrev_cwd()) |
|
2799 | 2805 | except OSError: |
|
2800 | 2806 | print sys.exc_info()[1] |
|
2801 | 2807 | else: |
|
2802 | 2808 | cwd = os.getcwd() |
|
2803 | 2809 | dhist = self.shell.user_ns['_dh'] |
|
2804 | 2810 | if oldcwd != cwd: |
|
2805 | 2811 | dhist.append(cwd) |
|
2806 | 2812 | self.db['dhist'] = compress_dhist(dhist)[-100:] |
|
2807 | 2813 | |
|
2808 | 2814 | else: |
|
2809 | 2815 | os.chdir(self.shell.home_dir) |
|
2810 | 2816 | if hasattr(self.shell, 'term_title') and self.shell.term_title: |
|
2811 | 2817 | set_term_title('IPython: ' + '~') |
|
2812 | 2818 | cwd = os.getcwd() |
|
2813 | 2819 | dhist = self.shell.user_ns['_dh'] |
|
2814 | 2820 | |
|
2815 | 2821 | if oldcwd != cwd: |
|
2816 | 2822 | dhist.append(cwd) |
|
2817 | 2823 | self.db['dhist'] = compress_dhist(dhist)[-100:] |
|
2818 | 2824 | if not 'q' in opts and self.shell.user_ns['_dh']: |
|
2819 | 2825 | print self.shell.user_ns['_dh'][-1] |
|
2820 | 2826 | |
|
2821 | 2827 | |
|
2822 | 2828 | def magic_env(self, parameter_s=''): |
|
2823 | 2829 | """List environment variables.""" |
|
2824 | 2830 | |
|
2825 | 2831 | return os.environ.data |
|
2826 | 2832 | |
|
2827 | 2833 | def magic_pushd(self, parameter_s=''): |
|
2828 | 2834 | """Place the current dir on stack and change directory. |
|
2829 | 2835 | |
|
2830 | 2836 | Usage:\\ |
|
2831 | 2837 | %pushd ['dirname'] |
|
2832 | 2838 | """ |
|
2833 | 2839 | |
|
2834 | 2840 | dir_s = self.shell.dir_stack |
|
2835 | 2841 | tgt = os.path.expanduser(parameter_s) |
|
2836 | 2842 | cwd = os.getcwd().replace(self.home_dir,'~') |
|
2837 | 2843 | if tgt: |
|
2838 | 2844 | self.magic_cd(parameter_s) |
|
2839 | 2845 | dir_s.insert(0,cwd) |
|
2840 | 2846 | return self.magic_dirs() |
|
2841 | 2847 | |
|
2842 | 2848 | def magic_popd(self, parameter_s=''): |
|
2843 | 2849 | """Change to directory popped off the top of the stack. |
|
2844 | 2850 | """ |
|
2845 | 2851 | if not self.shell.dir_stack: |
|
2846 | 2852 | raise UsageError("%popd on empty stack") |
|
2847 | 2853 | top = self.shell.dir_stack.pop(0) |
|
2848 | 2854 | self.magic_cd(top) |
|
2849 | 2855 | print "popd ->",top |
|
2850 | 2856 | |
|
2851 | 2857 | def magic_dirs(self, parameter_s=''): |
|
2852 | 2858 | """Return the current directory stack.""" |
|
2853 | 2859 | |
|
2854 | 2860 | return self.shell.dir_stack |
|
2855 | 2861 | |
|
2856 | 2862 | def magic_dhist(self, parameter_s=''): |
|
2857 | 2863 | """Print your history of visited directories. |
|
2858 | 2864 | |
|
2859 | 2865 | %dhist -> print full history\\ |
|
2860 | 2866 | %dhist n -> print last n entries only\\ |
|
2861 | 2867 | %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\ |
|
2862 | 2868 | |
|
2863 | 2869 | This history is automatically maintained by the %cd command, and |
|
2864 | 2870 | always available as the global list variable _dh. You can use %cd -<n> |
|
2865 | 2871 | to go to directory number <n>. |
|
2866 | 2872 | |
|
2867 | 2873 | Note that most of time, you should view directory history by entering |
|
2868 | 2874 | cd -<TAB>. |
|
2869 | 2875 | |
|
2870 | 2876 | """ |
|
2871 | 2877 | |
|
2872 | 2878 | dh = self.shell.user_ns['_dh'] |
|
2873 | 2879 | if parameter_s: |
|
2874 | 2880 | try: |
|
2875 | 2881 | args = map(int,parameter_s.split()) |
|
2876 | 2882 | except: |
|
2877 | 2883 | self.arg_err(Magic.magic_dhist) |
|
2878 | 2884 | return |
|
2879 | 2885 | if len(args) == 1: |
|
2880 | 2886 | ini,fin = max(len(dh)-(args[0]),0),len(dh) |
|
2881 | 2887 | elif len(args) == 2: |
|
2882 | 2888 | ini,fin = args |
|
2883 | 2889 | else: |
|
2884 | 2890 | self.arg_err(Magic.magic_dhist) |
|
2885 | 2891 | return |
|
2886 | 2892 | else: |
|
2887 | 2893 | ini,fin = 0,len(dh) |
|
2888 | 2894 | nlprint(dh, |
|
2889 | 2895 | header = 'Directory history (kept in _dh)', |
|
2890 | 2896 | start=ini,stop=fin) |
|
2891 | 2897 | |
|
2892 | 2898 | @testdec.skip_doctest |
|
2893 | 2899 | def magic_sc(self, parameter_s=''): |
|
2894 | 2900 | """Shell capture - execute a shell command and capture its output. |
|
2895 | 2901 | |
|
2896 | 2902 | DEPRECATED. Suboptimal, retained for backwards compatibility. |
|
2897 | 2903 | |
|
2898 | 2904 | You should use the form 'var = !command' instead. Example: |
|
2899 | 2905 | |
|
2900 | 2906 | "%sc -l myfiles = ls ~" should now be written as |
|
2901 | 2907 | |
|
2902 | 2908 | "myfiles = !ls ~" |
|
2903 | 2909 | |
|
2904 | 2910 | myfiles.s, myfiles.l and myfiles.n still apply as documented |
|
2905 | 2911 | below. |
|
2906 | 2912 | |
|
2907 | 2913 | -- |
|
2908 | 2914 | %sc [options] varname=command |
|
2909 | 2915 | |
|
2910 | 2916 | IPython will run the given command using commands.getoutput(), and |
|
2911 | 2917 | will then update the user's interactive namespace with a variable |
|
2912 | 2918 | called varname, containing the value of the call. Your command can |
|
2913 | 2919 | contain shell wildcards, pipes, etc. |
|
2914 | 2920 | |
|
2915 | 2921 | The '=' sign in the syntax is mandatory, and the variable name you |
|
2916 | 2922 | supply must follow Python's standard conventions for valid names. |
|
2917 | 2923 | |
|
2918 | 2924 | (A special format without variable name exists for internal use) |
|
2919 | 2925 | |
|
2920 | 2926 | Options: |
|
2921 | 2927 | |
|
2922 | 2928 | -l: list output. Split the output on newlines into a list before |
|
2923 | 2929 | assigning it to the given variable. By default the output is stored |
|
2924 | 2930 | as a single string. |
|
2925 | 2931 | |
|
2926 | 2932 | -v: verbose. Print the contents of the variable. |
|
2927 | 2933 | |
|
2928 | 2934 | In most cases you should not need to split as a list, because the |
|
2929 | 2935 | returned value is a special type of string which can automatically |
|
2930 | 2936 | provide its contents either as a list (split on newlines) or as a |
|
2931 | 2937 | space-separated string. These are convenient, respectively, either |
|
2932 | 2938 | for sequential processing or to be passed to a shell command. |
|
2933 | 2939 | |
|
2934 | 2940 | For example: |
|
2935 | 2941 | |
|
2936 | 2942 | # all-random |
|
2937 | 2943 | |
|
2938 | 2944 | # Capture into variable a |
|
2939 | 2945 | In [1]: sc a=ls *py |
|
2940 | 2946 | |
|
2941 | 2947 | # a is a string with embedded newlines |
|
2942 | 2948 | In [2]: a |
|
2943 | 2949 | Out[2]: 'setup.py\\nwin32_manual_post_install.py' |
|
2944 | 2950 | |
|
2945 | 2951 | # which can be seen as a list: |
|
2946 | 2952 | In [3]: a.l |
|
2947 | 2953 | Out[3]: ['setup.py', 'win32_manual_post_install.py'] |
|
2948 | 2954 | |
|
2949 | 2955 | # or as a whitespace-separated string: |
|
2950 | 2956 | In [4]: a.s |
|
2951 | 2957 | Out[4]: 'setup.py win32_manual_post_install.py' |
|
2952 | 2958 | |
|
2953 | 2959 | # a.s is useful to pass as a single command line: |
|
2954 | 2960 | In [5]: !wc -l $a.s |
|
2955 | 2961 | 146 setup.py |
|
2956 | 2962 | 130 win32_manual_post_install.py |
|
2957 | 2963 | 276 total |
|
2958 | 2964 | |
|
2959 | 2965 | # while the list form is useful to loop over: |
|
2960 | 2966 | In [6]: for f in a.l: |
|
2961 | 2967 | ...: !wc -l $f |
|
2962 | 2968 | ...: |
|
2963 | 2969 | 146 setup.py |
|
2964 | 2970 | 130 win32_manual_post_install.py |
|
2965 | 2971 | |
|
2966 | 2972 | Similiarly, the lists returned by the -l option are also special, in |
|
2967 | 2973 | the sense that you can equally invoke the .s attribute on them to |
|
2968 | 2974 | automatically get a whitespace-separated string from their contents: |
|
2969 | 2975 | |
|
2970 | 2976 | In [7]: sc -l b=ls *py |
|
2971 | 2977 | |
|
2972 | 2978 | In [8]: b |
|
2973 | 2979 | Out[8]: ['setup.py', 'win32_manual_post_install.py'] |
|
2974 | 2980 | |
|
2975 | 2981 | In [9]: b.s |
|
2976 | 2982 | Out[9]: 'setup.py win32_manual_post_install.py' |
|
2977 | 2983 | |
|
2978 | 2984 | In summary, both the lists and strings used for ouptut capture have |
|
2979 | 2985 | the following special attributes: |
|
2980 | 2986 | |
|
2981 | 2987 | .l (or .list) : value as list. |
|
2982 | 2988 | .n (or .nlstr): value as newline-separated string. |
|
2983 | 2989 | .s (or .spstr): value as space-separated string. |
|
2984 | 2990 | """ |
|
2985 | 2991 | |
|
2986 | 2992 | opts,args = self.parse_options(parameter_s,'lv') |
|
2987 | 2993 | # Try to get a variable name and command to run |
|
2988 | 2994 | try: |
|
2989 | 2995 | # the variable name must be obtained from the parse_options |
|
2990 | 2996 | # output, which uses shlex.split to strip options out. |
|
2991 | 2997 | var,_ = args.split('=',1) |
|
2992 | 2998 | var = var.strip() |
|
2993 | 2999 | # But the the command has to be extracted from the original input |
|
2994 | 3000 | # parameter_s, not on what parse_options returns, to avoid the |
|
2995 | 3001 | # quote stripping which shlex.split performs on it. |
|
2996 | 3002 | _,cmd = parameter_s.split('=',1) |
|
2997 | 3003 | except ValueError: |
|
2998 | 3004 | var,cmd = '','' |
|
2999 | 3005 | # If all looks ok, proceed |
|
3000 | 3006 | split = 'l' in opts |
|
3001 | 3007 | out = self.shell.getoutput(cmd, split=split) |
|
3002 | 3008 | if opts.has_key('v'): |
|
3003 | 3009 | print '%s ==\n%s' % (var,pformat(out)) |
|
3004 | 3010 | if var: |
|
3005 | 3011 | self.shell.user_ns.update({var:out}) |
|
3006 | 3012 | else: |
|
3007 | 3013 | return out |
|
3008 | 3014 | |
|
3009 | 3015 | def magic_sx(self, parameter_s=''): |
|
3010 | 3016 | """Shell execute - run a shell command and capture its output. |
|
3011 | 3017 | |
|
3012 | 3018 | %sx command |
|
3013 | 3019 | |
|
3014 | 3020 | IPython will run the given command using commands.getoutput(), and |
|
3015 | 3021 | return the result formatted as a list (split on '\\n'). Since the |
|
3016 | 3022 | output is _returned_, it will be stored in ipython's regular output |
|
3017 | 3023 | cache Out[N] and in the '_N' automatic variables. |
|
3018 | 3024 | |
|
3019 | 3025 | Notes: |
|
3020 | 3026 | |
|
3021 | 3027 | 1) If an input line begins with '!!', then %sx is automatically |
|
3022 | 3028 | invoked. That is, while: |
|
3023 | 3029 | !ls |
|
3024 | 3030 | causes ipython to simply issue system('ls'), typing |
|
3025 | 3031 | !!ls |
|
3026 | 3032 | is a shorthand equivalent to: |
|
3027 | 3033 | %sx ls |
|
3028 | 3034 | |
|
3029 | 3035 | 2) %sx differs from %sc in that %sx automatically splits into a list, |
|
3030 | 3036 | like '%sc -l'. The reason for this is to make it as easy as possible |
|
3031 | 3037 | to process line-oriented shell output via further python commands. |
|
3032 | 3038 | %sc is meant to provide much finer control, but requires more |
|
3033 | 3039 | typing. |
|
3034 | 3040 | |
|
3035 | 3041 | 3) Just like %sc -l, this is a list with special attributes: |
|
3036 | 3042 | |
|
3037 | 3043 | .l (or .list) : value as list. |
|
3038 | 3044 | .n (or .nlstr): value as newline-separated string. |
|
3039 | 3045 | .s (or .spstr): value as whitespace-separated string. |
|
3040 | 3046 | |
|
3041 | 3047 | This is very useful when trying to use such lists as arguments to |
|
3042 | 3048 | system commands.""" |
|
3043 | 3049 | |
|
3044 | 3050 | if parameter_s: |
|
3045 | 3051 | return self.shell.getoutput(parameter_s) |
|
3046 | 3052 | |
|
3047 | 3053 | |
|
3048 | 3054 | def magic_bookmark(self, parameter_s=''): |
|
3049 | 3055 | """Manage IPython's bookmark system. |
|
3050 | 3056 | |
|
3051 | 3057 | %bookmark <name> - set bookmark to current dir |
|
3052 | 3058 | %bookmark <name> <dir> - set bookmark to <dir> |
|
3053 | 3059 | %bookmark -l - list all bookmarks |
|
3054 | 3060 | %bookmark -d <name> - remove bookmark |
|
3055 | 3061 | %bookmark -r - remove all bookmarks |
|
3056 | 3062 | |
|
3057 | 3063 | You can later on access a bookmarked folder with: |
|
3058 | 3064 | %cd -b <name> |
|
3059 | 3065 | or simply '%cd <name>' if there is no directory called <name> AND |
|
3060 | 3066 | there is such a bookmark defined. |
|
3061 | 3067 | |
|
3062 | 3068 | Your bookmarks persist through IPython sessions, but they are |
|
3063 | 3069 | associated with each profile.""" |
|
3064 | 3070 | |
|
3065 | 3071 | opts,args = self.parse_options(parameter_s,'drl',mode='list') |
|
3066 | 3072 | if len(args) > 2: |
|
3067 | 3073 | raise UsageError("%bookmark: too many arguments") |
|
3068 | 3074 | |
|
3069 | 3075 | bkms = self.db.get('bookmarks',{}) |
|
3070 | 3076 | |
|
3071 | 3077 | if opts.has_key('d'): |
|
3072 | 3078 | try: |
|
3073 | 3079 | todel = args[0] |
|
3074 | 3080 | except IndexError: |
|
3075 | 3081 | raise UsageError( |
|
3076 | 3082 | "%bookmark -d: must provide a bookmark to delete") |
|
3077 | 3083 | else: |
|
3078 | 3084 | try: |
|
3079 | 3085 | del bkms[todel] |
|
3080 | 3086 | except KeyError: |
|
3081 | 3087 | raise UsageError( |
|
3082 | 3088 | "%%bookmark -d: Can't delete bookmark '%s'" % todel) |
|
3083 | 3089 | |
|
3084 | 3090 | elif opts.has_key('r'): |
|
3085 | 3091 | bkms = {} |
|
3086 | 3092 | elif opts.has_key('l'): |
|
3087 | 3093 | bks = bkms.keys() |
|
3088 | 3094 | bks.sort() |
|
3089 | 3095 | if bks: |
|
3090 | 3096 | size = max(map(len,bks)) |
|
3091 | 3097 | else: |
|
3092 | 3098 | size = 0 |
|
3093 | 3099 | fmt = '%-'+str(size)+'s -> %s' |
|
3094 | 3100 | print 'Current bookmarks:' |
|
3095 | 3101 | for bk in bks: |
|
3096 | 3102 | print fmt % (bk,bkms[bk]) |
|
3097 | 3103 | else: |
|
3098 | 3104 | if not args: |
|
3099 | 3105 | raise UsageError("%bookmark: You must specify the bookmark name") |
|
3100 | 3106 | elif len(args)==1: |
|
3101 | 3107 | bkms[args[0]] = os.getcwd() |
|
3102 | 3108 | elif len(args)==2: |
|
3103 | 3109 | bkms[args[0]] = args[1] |
|
3104 | 3110 | self.db['bookmarks'] = bkms |
|
3105 | 3111 | |
|
3106 | 3112 | def magic_pycat(self, parameter_s=''): |
|
3107 | 3113 | """Show a syntax-highlighted file through a pager. |
|
3108 | 3114 | |
|
3109 | 3115 | This magic is similar to the cat utility, but it will assume the file |
|
3110 | 3116 | to be Python source and will show it with syntax highlighting. """ |
|
3111 | 3117 | |
|
3112 | 3118 | try: |
|
3113 | 3119 | filename = get_py_filename(parameter_s) |
|
3114 | 3120 | cont = file_read(filename) |
|
3115 | 3121 | except IOError: |
|
3116 | 3122 | try: |
|
3117 | 3123 | cont = eval(parameter_s,self.user_ns) |
|
3118 | 3124 | except NameError: |
|
3119 | 3125 | cont = None |
|
3120 | 3126 | if cont is None: |
|
3121 | 3127 | print "Error: no such file or variable" |
|
3122 | 3128 | return |
|
3123 | 3129 | |
|
3124 | 3130 | page.page(self.shell.pycolorize(cont)) |
|
3125 | 3131 | |
|
3126 | 3132 | def _rerun_pasted(self): |
|
3127 | 3133 | """ Rerun a previously pasted command. |
|
3128 | 3134 | """ |
|
3129 | 3135 | b = self.user_ns.get('pasted_block', None) |
|
3130 | 3136 | if b is None: |
|
3131 | 3137 | raise UsageError('No previous pasted block available') |
|
3132 | 3138 | print "Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b)) |
|
3133 | 3139 | exec b in self.user_ns |
|
3134 | 3140 | |
|
3135 | 3141 | def _get_pasted_lines(self, sentinel): |
|
3136 | 3142 | """ Yield pasted lines until the user enters the given sentinel value. |
|
3137 | 3143 | """ |
|
3138 | 3144 | from IPython.core import interactiveshell |
|
3139 | 3145 | print "Pasting code; enter '%s' alone on the line to stop." % sentinel |
|
3140 | 3146 | while True: |
|
3141 | 3147 | l = interactiveshell.raw_input_original(':') |
|
3142 | 3148 | if l == sentinel: |
|
3143 | 3149 | return |
|
3144 | 3150 | else: |
|
3145 | 3151 | yield l |
|
3146 | 3152 | |
|
3147 | 3153 | def _strip_pasted_lines_for_code(self, raw_lines): |
|
3148 | 3154 | """ Strip non-code parts of a sequence of lines to return a block of |
|
3149 | 3155 | code. |
|
3150 | 3156 | """ |
|
3151 | 3157 | # Regular expressions that declare text we strip from the input: |
|
3152 | 3158 | strip_re = [r'^\s*In \[\d+\]:', # IPython input prompt |
|
3153 | 3159 | r'^\s*(\s?>)+', # Python input prompt |
|
3154 | 3160 | r'^\s*\.{3,}', # Continuation prompts |
|
3155 | 3161 | r'^\++', |
|
3156 | 3162 | ] |
|
3157 | 3163 | |
|
3158 | 3164 | strip_from_start = map(re.compile,strip_re) |
|
3159 | 3165 | |
|
3160 | 3166 | lines = [] |
|
3161 | 3167 | for l in raw_lines: |
|
3162 | 3168 | for pat in strip_from_start: |
|
3163 | 3169 | l = pat.sub('',l) |
|
3164 | 3170 | lines.append(l) |
|
3165 | 3171 | |
|
3166 | 3172 | block = "\n".join(lines) + '\n' |
|
3167 | 3173 | #print "block:\n",block |
|
3168 | 3174 | return block |
|
3169 | 3175 | |
|
3170 | 3176 | def _execute_block(self, block, par): |
|
3171 | 3177 | """ Execute a block, or store it in a variable, per the user's request. |
|
3172 | 3178 | """ |
|
3173 | 3179 | if not par: |
|
3174 | 3180 | b = textwrap.dedent(block) |
|
3175 | 3181 | self.user_ns['pasted_block'] = b |
|
3176 | 3182 | exec b in self.user_ns |
|
3177 | 3183 | else: |
|
3178 | 3184 | self.user_ns[par] = SList(block.splitlines()) |
|
3179 | 3185 | print "Block assigned to '%s'" % par |
|
3180 | 3186 | |
|
3181 | 3187 | def magic_quickref(self,arg): |
|
3182 | 3188 | """ Show a quick reference sheet """ |
|
3183 | 3189 | import IPython.core.usage |
|
3184 | 3190 | qr = IPython.core.usage.quick_reference + self.magic_magic('-brief') |
|
3185 | 3191 | |
|
3186 | 3192 | page.page(qr) |
|
3187 | 3193 | |
|
3188 | 3194 | def magic_doctest_mode(self,parameter_s=''): |
|
3189 | 3195 | """Toggle doctest mode on and off. |
|
3190 | 3196 | |
|
3191 | 3197 | This mode is intended to make IPython behave as much as possible like a |
|
3192 | 3198 | plain Python shell, from the perspective of how its prompts, exceptions |
|
3193 | 3199 | and output look. This makes it easy to copy and paste parts of a |
|
3194 | 3200 | session into doctests. It does so by: |
|
3195 | 3201 | |
|
3196 | 3202 | - Changing the prompts to the classic ``>>>`` ones. |
|
3197 | 3203 | - Changing the exception reporting mode to 'Plain'. |
|
3198 | 3204 | - Disabling pretty-printing of output. |
|
3199 | 3205 | |
|
3200 | 3206 | Note that IPython also supports the pasting of code snippets that have |
|
3201 | 3207 | leading '>>>' and '...' prompts in them. This means that you can paste |
|
3202 | 3208 | doctests from files or docstrings (even if they have leading |
|
3203 | 3209 | whitespace), and the code will execute correctly. You can then use |
|
3204 | 3210 | '%history -t' to see the translated history; this will give you the |
|
3205 | 3211 | input after removal of all the leading prompts and whitespace, which |
|
3206 | 3212 | can be pasted back into an editor. |
|
3207 | 3213 | |
|
3208 | 3214 | With these features, you can switch into this mode easily whenever you |
|
3209 | 3215 | need to do testing and changes to doctests, without having to leave |
|
3210 | 3216 | your existing IPython session. |
|
3211 | 3217 | """ |
|
3212 | 3218 | |
|
3213 | 3219 | from IPython.utils.ipstruct import Struct |
|
3214 | 3220 | |
|
3215 | 3221 | # Shorthands |
|
3216 | 3222 | shell = self.shell |
|
3217 | 3223 | oc = shell.displayhook |
|
3218 | 3224 | meta = shell.meta |
|
3219 | 3225 | disp_formatter = self.shell.display_formatter |
|
3220 | 3226 | ptformatter = disp_formatter.formatters['text/plain'] |
|
3221 | 3227 | # dstore is a data store kept in the instance metadata bag to track any |
|
3222 | 3228 | # changes we make, so we can undo them later. |
|
3223 | 3229 | dstore = meta.setdefault('doctest_mode',Struct()) |
|
3224 | 3230 | save_dstore = dstore.setdefault |
|
3225 | 3231 | |
|
3226 | 3232 | # save a few values we'll need to recover later |
|
3227 | 3233 | mode = save_dstore('mode',False) |
|
3228 | 3234 | save_dstore('rc_pprint',ptformatter.pprint) |
|
3229 | 3235 | save_dstore('xmode',shell.InteractiveTB.mode) |
|
3230 | 3236 | save_dstore('rc_separate_out',shell.separate_out) |
|
3231 | 3237 | save_dstore('rc_separate_out2',shell.separate_out2) |
|
3232 | 3238 | save_dstore('rc_prompts_pad_left',shell.prompts_pad_left) |
|
3233 | 3239 | save_dstore('rc_separate_in',shell.separate_in) |
|
3234 | 3240 | save_dstore('rc_plain_text_only',disp_formatter.plain_text_only) |
|
3235 | 3241 | |
|
3236 | 3242 | if mode == False: |
|
3237 | 3243 | # turn on |
|
3238 | 3244 | oc.prompt1.p_template = '>>> ' |
|
3239 | 3245 | oc.prompt2.p_template = '... ' |
|
3240 | 3246 | oc.prompt_out.p_template = '' |
|
3241 | 3247 | |
|
3242 | 3248 | # Prompt separators like plain python |
|
3243 | 3249 | oc.input_sep = oc.prompt1.sep = '' |
|
3244 | 3250 | oc.output_sep = '' |
|
3245 | 3251 | oc.output_sep2 = '' |
|
3246 | 3252 | |
|
3247 | 3253 | oc.prompt1.pad_left = oc.prompt2.pad_left = \ |
|
3248 | 3254 | oc.prompt_out.pad_left = False |
|
3249 | 3255 | |
|
3250 | 3256 | ptformatter.pprint = False |
|
3251 | 3257 | disp_formatter.plain_text_only = True |
|
3252 | 3258 | |
|
3253 | 3259 | shell.magic_xmode('Plain') |
|
3254 | 3260 | else: |
|
3255 | 3261 | # turn off |
|
3256 | 3262 | oc.prompt1.p_template = shell.prompt_in1 |
|
3257 | 3263 | oc.prompt2.p_template = shell.prompt_in2 |
|
3258 | 3264 | oc.prompt_out.p_template = shell.prompt_out |
|
3259 | 3265 | |
|
3260 | 3266 | oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in |
|
3261 | 3267 | |
|
3262 | 3268 | oc.output_sep = dstore.rc_separate_out |
|
3263 | 3269 | oc.output_sep2 = dstore.rc_separate_out2 |
|
3264 | 3270 | |
|
3265 | 3271 | oc.prompt1.pad_left = oc.prompt2.pad_left = \ |
|
3266 | 3272 | oc.prompt_out.pad_left = dstore.rc_prompts_pad_left |
|
3267 | 3273 | |
|
3268 | 3274 | ptformatter.pprint = dstore.rc_pprint |
|
3269 | 3275 | disp_formatter.plain_text_only = dstore.rc_plain_text_only |
|
3270 | 3276 | |
|
3271 | 3277 | shell.magic_xmode(dstore.xmode) |
|
3272 | 3278 | |
|
3273 | 3279 | # Store new mode and inform |
|
3274 | 3280 | dstore.mode = bool(1-int(mode)) |
|
3275 | 3281 | mode_label = ['OFF','ON'][dstore.mode] |
|
3276 | 3282 | print 'Doctest mode is:', mode_label |
|
3277 | 3283 | |
|
3278 | 3284 | def magic_gui(self, parameter_s=''): |
|
3279 | 3285 | """Enable or disable IPython GUI event loop integration. |
|
3280 | 3286 | |
|
3281 | 3287 | %gui [GUINAME] |
|
3282 | 3288 | |
|
3283 | 3289 | This magic replaces IPython's threaded shells that were activated |
|
3284 | 3290 | using the (pylab/wthread/etc.) command line flags. GUI toolkits |
|
3285 | 3291 | can now be enabled, disabled and swtiched at runtime and keyboard |
|
3286 | 3292 | interrupts should work without any problems. The following toolkits |
|
3287 | 3293 | are supported: wxPython, PyQt4, PyGTK, and Tk:: |
|
3288 | 3294 | |
|
3289 | 3295 | %gui wx # enable wxPython event loop integration |
|
3290 | 3296 | %gui qt4|qt # enable PyQt4 event loop integration |
|
3291 | 3297 | %gui gtk # enable PyGTK event loop integration |
|
3292 | 3298 | %gui tk # enable Tk event loop integration |
|
3293 | 3299 | %gui # disable all event loop integration |
|
3294 | 3300 | |
|
3295 | 3301 | WARNING: after any of these has been called you can simply create |
|
3296 | 3302 | an application object, but DO NOT start the event loop yourself, as |
|
3297 | 3303 | we have already handled that. |
|
3298 | 3304 | """ |
|
3299 | 3305 | from IPython.lib.inputhook import enable_gui |
|
3300 | 3306 | opts, arg = self.parse_options(parameter_s, '') |
|
3301 | 3307 | if arg=='': arg = None |
|
3302 | 3308 | return enable_gui(arg) |
|
3303 | 3309 | |
|
3304 | 3310 | def magic_load_ext(self, module_str): |
|
3305 | 3311 | """Load an IPython extension by its module name.""" |
|
3306 | 3312 | return self.extension_manager.load_extension(module_str) |
|
3307 | 3313 | |
|
3308 | 3314 | def magic_unload_ext(self, module_str): |
|
3309 | 3315 | """Unload an IPython extension by its module name.""" |
|
3310 | 3316 | self.extension_manager.unload_extension(module_str) |
|
3311 | 3317 | |
|
3312 | 3318 | def magic_reload_ext(self, module_str): |
|
3313 | 3319 | """Reload an IPython extension by its module name.""" |
|
3314 | 3320 | self.extension_manager.reload_extension(module_str) |
|
3315 | 3321 | |
|
3316 | 3322 | @testdec.skip_doctest |
|
3317 | 3323 | def magic_install_profiles(self, s): |
|
3318 | 3324 | """Install the default IPython profiles into the .ipython dir. |
|
3319 | 3325 | |
|
3320 | 3326 | If the default profiles have already been installed, they will not |
|
3321 | 3327 | be overwritten. You can force overwriting them by using the ``-o`` |
|
3322 | 3328 | option:: |
|
3323 | 3329 | |
|
3324 | 3330 | In [1]: %install_profiles -o |
|
3325 | 3331 | """ |
|
3326 | 3332 | if '-o' in s: |
|
3327 | 3333 | overwrite = True |
|
3328 | 3334 | else: |
|
3329 | 3335 | overwrite = False |
|
3330 | 3336 | from IPython.config import profile |
|
3331 | 3337 | profile_dir = os.path.split(profile.__file__)[0] |
|
3332 | 3338 | ipython_dir = self.ipython_dir |
|
3333 | 3339 | files = os.listdir(profile_dir) |
|
3334 | 3340 | |
|
3335 | 3341 | to_install = [] |
|
3336 | 3342 | for f in files: |
|
3337 | 3343 | if f.startswith('ipython_config'): |
|
3338 | 3344 | src = os.path.join(profile_dir, f) |
|
3339 | 3345 | dst = os.path.join(ipython_dir, f) |
|
3340 | 3346 | if (not os.path.isfile(dst)) or overwrite: |
|
3341 | 3347 | to_install.append((f, src, dst)) |
|
3342 | 3348 | if len(to_install)>0: |
|
3343 | 3349 | print "Installing profiles to: ", ipython_dir |
|
3344 | 3350 | for (f, src, dst) in to_install: |
|
3345 | 3351 | shutil.copy(src, dst) |
|
3346 | 3352 | print " %s" % f |
|
3347 | 3353 | |
|
3348 | 3354 | def magic_install_default_config(self, s): |
|
3349 | 3355 | """Install IPython's default config file into the .ipython dir. |
|
3350 | 3356 | |
|
3351 | 3357 | If the default config file (:file:`ipython_config.py`) is already |
|
3352 | 3358 | installed, it will not be overwritten. You can force overwriting |
|
3353 | 3359 | by using the ``-o`` option:: |
|
3354 | 3360 | |
|
3355 | 3361 | In [1]: %install_default_config |
|
3356 | 3362 | """ |
|
3357 | 3363 | if '-o' in s: |
|
3358 | 3364 | overwrite = True |
|
3359 | 3365 | else: |
|
3360 | 3366 | overwrite = False |
|
3361 | 3367 | from IPython.config import default |
|
3362 | 3368 | config_dir = os.path.split(default.__file__)[0] |
|
3363 | 3369 | ipython_dir = self.ipython_dir |
|
3364 | 3370 | default_config_file_name = 'ipython_config.py' |
|
3365 | 3371 | src = os.path.join(config_dir, default_config_file_name) |
|
3366 | 3372 | dst = os.path.join(ipython_dir, default_config_file_name) |
|
3367 | 3373 | if (not os.path.isfile(dst)) or overwrite: |
|
3368 | 3374 | shutil.copy(src, dst) |
|
3369 | 3375 | print "Installing default config file: %s" % dst |
|
3370 | 3376 | |
|
3371 | 3377 | # Pylab support: simple wrappers that activate pylab, load gui input |
|
3372 | 3378 | # handling and modify slightly %run |
|
3373 | 3379 | |
|
3374 | 3380 | @testdec.skip_doctest |
|
3375 | 3381 | def _pylab_magic_run(self, parameter_s=''): |
|
3376 | 3382 | Magic.magic_run(self, parameter_s, |
|
3377 | 3383 | runner=mpl_runner(self.shell.safe_execfile)) |
|
3378 | 3384 | |
|
3379 | 3385 | _pylab_magic_run.__doc__ = magic_run.__doc__ |
|
3380 | 3386 | |
|
3381 | 3387 | @testdec.skip_doctest |
|
3382 | 3388 | def magic_pylab(self, s): |
|
3383 | 3389 | """Load numpy and matplotlib to work interactively. |
|
3384 | 3390 | |
|
3385 | 3391 | %pylab [GUINAME] |
|
3386 | 3392 | |
|
3387 | 3393 | This function lets you activate pylab (matplotlib, numpy and |
|
3388 | 3394 | interactive support) at any point during an IPython session. |
|
3389 | 3395 | |
|
3390 | 3396 | It will import at the top level numpy as np, pyplot as plt, matplotlib, |
|
3391 | 3397 | pylab and mlab, as well as all names from numpy and pylab. |
|
3392 | 3398 | |
|
3393 | 3399 | Parameters |
|
3394 | 3400 | ---------- |
|
3395 | 3401 | guiname : optional |
|
3396 | 3402 | One of the valid arguments to the %gui magic ('qt', 'wx', 'gtk', 'osx' or |
|
3397 | 3403 | 'tk'). If given, the corresponding Matplotlib backend is used, |
|
3398 | 3404 | otherwise matplotlib's default (which you can override in your |
|
3399 | 3405 | matplotlib config file) is used. |
|
3400 | 3406 | |
|
3401 | 3407 | Examples |
|
3402 | 3408 | -------- |
|
3403 | 3409 | In this case, where the MPL default is TkAgg: |
|
3404 | 3410 | In [2]: %pylab |
|
3405 | 3411 | |
|
3406 | 3412 | Welcome to pylab, a matplotlib-based Python environment. |
|
3407 | 3413 | Backend in use: TkAgg |
|
3408 | 3414 | For more information, type 'help(pylab)'. |
|
3409 | 3415 | |
|
3410 | 3416 | But you can explicitly request a different backend: |
|
3411 | 3417 | In [3]: %pylab qt |
|
3412 | 3418 | |
|
3413 | 3419 | Welcome to pylab, a matplotlib-based Python environment. |
|
3414 | 3420 | Backend in use: Qt4Agg |
|
3415 | 3421 | For more information, type 'help(pylab)'. |
|
3416 | 3422 | """ |
|
3417 | 3423 | self.shell.enable_pylab(s) |
|
3418 | 3424 | |
|
3419 | 3425 | def magic_tb(self, s): |
|
3420 | 3426 | """Print the last traceback with the currently active exception mode. |
|
3421 | 3427 | |
|
3422 | 3428 | See %xmode for changing exception reporting modes.""" |
|
3423 | 3429 | self.shell.showtraceback() |
|
3424 | 3430 | |
|
3425 | 3431 | @testdec.skip_doctest |
|
3426 | 3432 | def magic_precision(self, s=''): |
|
3427 | 3433 | """Set floating point precision for pretty printing. |
|
3428 | 3434 | |
|
3429 | 3435 | Can set either integer precision or a format string. |
|
3430 | 3436 | |
|
3431 | 3437 | If numpy has been imported and precision is an int, |
|
3432 | 3438 | numpy display precision will also be set, via ``numpy.set_printoptions``. |
|
3433 | 3439 | |
|
3434 | 3440 | If no argument is given, defaults will be restored. |
|
3435 | 3441 | |
|
3436 | 3442 | Examples |
|
3437 | 3443 | -------- |
|
3438 | 3444 | :: |
|
3439 | 3445 | |
|
3440 | 3446 | In [1]: from math import pi |
|
3441 | 3447 | |
|
3442 | 3448 | In [2]: %precision 3 |
|
3443 | 3449 | Out[2]: '%.3f' |
|
3444 | 3450 | |
|
3445 | 3451 | In [3]: pi |
|
3446 | 3452 | Out[3]: 3.142 |
|
3447 | 3453 | |
|
3448 | 3454 | In [4]: %precision %i |
|
3449 | 3455 | Out[4]: '%i' |
|
3450 | 3456 | |
|
3451 | 3457 | In [5]: pi |
|
3452 | 3458 | Out[5]: 3 |
|
3453 | 3459 | |
|
3454 | 3460 | In [6]: %precision %e |
|
3455 | 3461 | Out[6]: '%e' |
|
3456 | 3462 | |
|
3457 | 3463 | In [7]: pi**10 |
|
3458 | 3464 | Out[7]: 9.364805e+04 |
|
3459 | 3465 | |
|
3460 | 3466 | In [8]: %precision |
|
3461 | 3467 | Out[8]: '%r' |
|
3462 | 3468 | |
|
3463 | 3469 | In [9]: pi**10 |
|
3464 | 3470 | Out[9]: 93648.047476082982 |
|
3465 | 3471 | |
|
3466 | 3472 | """ |
|
3467 | 3473 | |
|
3468 | 3474 | ptformatter = self.shell.display_formatter.formatters['text/plain'] |
|
3469 | 3475 | ptformatter.float_precision = s |
|
3470 | 3476 | return ptformatter.float_format |
|
3471 | 3477 | |
|
3472 | 3478 | # end Magic |
@@ -1,425 +1,440 b'' | |||
|
1 | 1 | """Tests for various magic functions. |
|
2 | 2 | |
|
3 | 3 | Needs to be run by nose (to make ipython session available). |
|
4 | 4 | """ |
|
5 | 5 | from __future__ import absolute_import |
|
6 | 6 | |
|
7 | 7 | #----------------------------------------------------------------------------- |
|
8 | 8 | # Imports |
|
9 | 9 | #----------------------------------------------------------------------------- |
|
10 | 10 | |
|
11 | 11 | import os |
|
12 | 12 | import sys |
|
13 | 13 | import tempfile |
|
14 | 14 | import types |
|
15 | 15 | from cStringIO import StringIO |
|
16 | 16 | |
|
17 | 17 | import nose.tools as nt |
|
18 | 18 | |
|
19 | 19 | from IPython.utils.path import get_long_path_name |
|
20 | 20 | from IPython.testing import decorators as dec |
|
21 | 21 | from IPython.testing import tools as tt |
|
22 | 22 | |
|
23 | 23 | #----------------------------------------------------------------------------- |
|
24 | 24 | # Test functions begin |
|
25 | 25 | #----------------------------------------------------------------------------- |
|
26 | 26 | def test_rehashx(): |
|
27 | 27 | # clear up everything |
|
28 | 28 | _ip = get_ipython() |
|
29 | 29 | _ip.alias_manager.alias_table.clear() |
|
30 | 30 | del _ip.db['syscmdlist'] |
|
31 | 31 | |
|
32 | 32 | _ip.magic('rehashx') |
|
33 | 33 | # Practically ALL ipython development systems will have more than 10 aliases |
|
34 | 34 | |
|
35 | 35 | yield (nt.assert_true, len(_ip.alias_manager.alias_table) > 10) |
|
36 | 36 | for key, val in _ip.alias_manager.alias_table.iteritems(): |
|
37 | 37 | # we must strip dots from alias names |
|
38 | 38 | nt.assert_true('.' not in key) |
|
39 | 39 | |
|
40 | 40 | # rehashx must fill up syscmdlist |
|
41 | 41 | scoms = _ip.db['syscmdlist'] |
|
42 | 42 | yield (nt.assert_true, len(scoms) > 10) |
|
43 | 43 | |
|
44 | 44 | |
|
45 | 45 | def test_magic_parse_options(): |
|
46 | 46 | """Test that we don't mangle paths when parsing magic options.""" |
|
47 | 47 | ip = get_ipython() |
|
48 | 48 | path = 'c:\\x' |
|
49 | 49 | opts = ip.parse_options('-f %s' % path,'f:')[0] |
|
50 | 50 | # argv splitting is os-dependent |
|
51 | 51 | if os.name == 'posix': |
|
52 | 52 | expected = 'c:x' |
|
53 | 53 | else: |
|
54 | 54 | expected = path |
|
55 | 55 | nt.assert_equals(opts['f'], expected) |
|
56 | 56 | |
|
57 | 57 | |
|
58 | 58 | def doctest_hist_f(): |
|
59 | 59 | """Test %hist -f with temporary filename. |
|
60 | 60 | |
|
61 | 61 | In [9]: import tempfile |
|
62 | 62 | |
|
63 | 63 | In [10]: tfile = tempfile.mktemp('.py','tmp-ipython-') |
|
64 | 64 | |
|
65 | 65 | In [11]: %hist -nl -f $tfile 3 |
|
66 | 66 | |
|
67 | 67 | In [13]: import os; os.unlink(tfile) |
|
68 | 68 | """ |
|
69 | 69 | |
|
70 | 70 | |
|
71 | 71 | def doctest_hist_r(): |
|
72 | 72 | """Test %hist -r |
|
73 | 73 | |
|
74 | 74 | XXX - This test is not recording the output correctly. For some reason, in |
|
75 | 75 | testing mode the raw history isn't getting populated. No idea why. |
|
76 | 76 | Disabling the output checking for now, though at least we do run it. |
|
77 | 77 | |
|
78 | 78 | In [1]: 'hist' in _ip.lsmagic() |
|
79 | 79 | Out[1]: True |
|
80 | 80 | |
|
81 | 81 | In [2]: x=1 |
|
82 | 82 | |
|
83 | 83 | In [3]: %hist -rl 2 |
|
84 | 84 | x=1 # random |
|
85 | 85 | %hist -r 2 |
|
86 | 86 | """ |
|
87 | 87 | |
|
88 | 88 | def doctest_hist_op(): |
|
89 | 89 | """Test %hist -op |
|
90 | 90 | |
|
91 | 91 | In [1]: class b: |
|
92 | 92 | ...: pass |
|
93 | 93 | ...: |
|
94 | 94 | |
|
95 | 95 | In [2]: class s(b): |
|
96 | 96 | ...: def __str__(self): |
|
97 | 97 | ...: return 's' |
|
98 | 98 | ...: |
|
99 | 99 | |
|
100 | 100 | In [3]: |
|
101 | 101 | |
|
102 | 102 | In [4]: class r(b): |
|
103 | 103 | ...: def __repr__(self): |
|
104 | 104 | ...: return 'r' |
|
105 | 105 | ...: |
|
106 | 106 | |
|
107 | 107 | In [5]: class sr(s,r): pass |
|
108 | 108 | ...: |
|
109 | 109 | |
|
110 | 110 | In [6]: |
|
111 | 111 | |
|
112 | 112 | In [7]: bb=b() |
|
113 | 113 | |
|
114 | 114 | In [8]: ss=s() |
|
115 | 115 | |
|
116 | 116 | In [9]: rr=r() |
|
117 | 117 | |
|
118 | 118 | In [10]: ssrr=sr() |
|
119 | 119 | |
|
120 | 120 | In [11]: bb |
|
121 | 121 | Out[11]: <...b instance at ...> |
|
122 | 122 | |
|
123 | 123 | In [12]: ss |
|
124 | 124 | Out[12]: <...s instance at ...> |
|
125 | 125 | |
|
126 | 126 | In [13]: |
|
127 | 127 | |
|
128 | 128 | In [14]: %hist -op |
|
129 | 129 | >>> class b: |
|
130 | 130 | ... pass |
|
131 | 131 | ... |
|
132 | 132 | >>> class s(b): |
|
133 | 133 | ... def __str__(self): |
|
134 | 134 | ... return 's' |
|
135 | 135 | ... |
|
136 | 136 | >>> |
|
137 | 137 | >>> class r(b): |
|
138 | 138 | ... def __repr__(self): |
|
139 | 139 | ... return 'r' |
|
140 | 140 | ... |
|
141 | 141 | >>> class sr(s,r): pass |
|
142 | 142 | >>> |
|
143 | 143 | >>> bb=b() |
|
144 | 144 | >>> ss=s() |
|
145 | 145 | >>> rr=r() |
|
146 | 146 | >>> ssrr=sr() |
|
147 | 147 | >>> bb |
|
148 | 148 | <...b instance at ...> |
|
149 | 149 | >>> ss |
|
150 | 150 | <...s instance at ...> |
|
151 | 151 | >>> |
|
152 | 152 | """ |
|
153 | 153 | |
|
154 | 154 | def test_macro(): |
|
155 | 155 | ip = get_ipython() |
|
156 | 156 | ip.history_manager.reset() # Clear any existing history. |
|
157 | 157 | cmds = ["a=1", "def b():\n return a**2", "print(a,b())"] |
|
158 | 158 | for i, cmd in enumerate(cmds, start=1): |
|
159 | 159 | ip.history_manager.store_inputs(i, cmd) |
|
160 | 160 | ip.magic("macro test 1-3") |
|
161 | 161 | nt.assert_equal(ip.user_ns["test"].value, "\n".join(cmds)+"\n") |
|
162 | 162 | |
|
163 | 163 | # List macros. |
|
164 | 164 | assert "test" in ip.magic("macro") |
|
165 | 165 | |
|
166 | 166 | def test_macro_run(): |
|
167 | 167 | """Test that we can run a multi-line macro successfully.""" |
|
168 | 168 | ip = get_ipython() |
|
169 | 169 | ip.history_manager.reset() |
|
170 | 170 | cmds = ["a=10", "a+=1", "print a", "%macro test 2-3"] |
|
171 | 171 | for cmd in cmds: |
|
172 | 172 | ip.run_cell(cmd) |
|
173 | 173 | nt.assert_equal(ip.user_ns["test"].value, "a+=1\nprint a\n") |
|
174 | 174 | original_stdout = sys.stdout |
|
175 | 175 | new_stdout = StringIO() |
|
176 | 176 | sys.stdout = new_stdout |
|
177 | 177 | try: |
|
178 | 178 | ip.run_cell("test") |
|
179 | 179 | nt.assert_true("12" in new_stdout.getvalue()) |
|
180 | 180 | ip.run_cell("test") |
|
181 | 181 | nt.assert_true("13" in new_stdout.getvalue()) |
|
182 | 182 | finally: |
|
183 | 183 | sys.stdout = original_stdout |
|
184 | 184 | new_stdout.close() |
|
185 | 185 | |
|
186 | 186 | |
|
187 | 187 | # XXX failing for now, until we get clearcmd out of quarantine. But we should |
|
188 | 188 | # fix this and revert the skip to happen only if numpy is not around. |
|
189 | 189 | #@dec.skipif_not_numpy |
|
190 | 190 | @dec.skip_known_failure |
|
191 | 191 | def test_numpy_clear_array_undec(): |
|
192 | 192 | from IPython.extensions import clearcmd |
|
193 | 193 | |
|
194 | 194 | _ip.ex('import numpy as np') |
|
195 | 195 | _ip.ex('a = np.empty(2)') |
|
196 | 196 | yield (nt.assert_true, 'a' in _ip.user_ns) |
|
197 | 197 | _ip.magic('clear array') |
|
198 | 198 | yield (nt.assert_false, 'a' in _ip.user_ns) |
|
199 | 199 | |
|
200 | 200 | |
|
201 | 201 | # Multiple tests for clipboard pasting |
|
202 | 202 | @dec.parametric |
|
203 | 203 | def test_paste(): |
|
204 | 204 | _ip = get_ipython() |
|
205 | 205 | def paste(txt, flags='-q'): |
|
206 | 206 | """Paste input text, by default in quiet mode""" |
|
207 | 207 | hooks.clipboard_get = lambda : txt |
|
208 | 208 | _ip.magic('paste '+flags) |
|
209 | 209 | |
|
210 | 210 | # Inject fake clipboard hook but save original so we can restore it later |
|
211 | 211 | hooks = _ip.hooks |
|
212 | 212 | user_ns = _ip.user_ns |
|
213 | 213 | original_clip = hooks.clipboard_get |
|
214 | 214 | |
|
215 | 215 | try: |
|
216 | 216 | # This try/except with an emtpy except clause is here only because |
|
217 | 217 | # try/yield/finally is invalid syntax in Python 2.4. This will be |
|
218 | 218 | # removed when we drop 2.4-compatibility, and the emtpy except below |
|
219 | 219 | # will be changed to a finally. |
|
220 | 220 | |
|
221 | 221 | # Run tests with fake clipboard function |
|
222 | 222 | user_ns.pop('x', None) |
|
223 | 223 | paste('x=1') |
|
224 | 224 | yield nt.assert_equal(user_ns['x'], 1) |
|
225 | 225 | |
|
226 | 226 | user_ns.pop('x', None) |
|
227 | 227 | paste('>>> x=2') |
|
228 | 228 | yield nt.assert_equal(user_ns['x'], 2) |
|
229 | 229 | |
|
230 | 230 | paste(""" |
|
231 | 231 | >>> x = [1,2,3] |
|
232 | 232 | >>> y = [] |
|
233 | 233 | >>> for i in x: |
|
234 | 234 | ... y.append(i**2) |
|
235 | 235 | ... |
|
236 | 236 | """) |
|
237 | 237 | yield nt.assert_equal(user_ns['x'], [1,2,3]) |
|
238 | 238 | yield nt.assert_equal(user_ns['y'], [1,4,9]) |
|
239 | 239 | |
|
240 | 240 | # Now, test that paste -r works |
|
241 | 241 | user_ns.pop('x', None) |
|
242 | 242 | yield nt.assert_false('x' in user_ns) |
|
243 | 243 | _ip.magic('paste -r') |
|
244 | 244 | yield nt.assert_equal(user_ns['x'], [1,2,3]) |
|
245 | 245 | |
|
246 | 246 | # Also test paste echoing, by temporarily faking the writer |
|
247 | 247 | w = StringIO() |
|
248 | 248 | writer = _ip.write |
|
249 | 249 | _ip.write = w.write |
|
250 | 250 | code = """ |
|
251 | 251 | a = 100 |
|
252 | 252 | b = 200""" |
|
253 | 253 | try: |
|
254 | 254 | paste(code,'') |
|
255 | 255 | out = w.getvalue() |
|
256 | 256 | finally: |
|
257 | 257 | _ip.write = writer |
|
258 | 258 | yield nt.assert_equal(user_ns['a'], 100) |
|
259 | 259 | yield nt.assert_equal(user_ns['b'], 200) |
|
260 | 260 | yield nt.assert_equal(out, code+"\n## -- End pasted text --\n") |
|
261 | 261 | |
|
262 | 262 | finally: |
|
263 | 263 | # This should be in a finally clause, instead of the bare except above. |
|
264 | 264 | # Restore original hook |
|
265 | 265 | hooks.clipboard_get = original_clip |
|
266 | 266 | |
|
267 | 267 | |
|
268 | 268 | def test_time(): |
|
269 | 269 | _ip.magic('time None') |
|
270 | 270 | |
|
271 | 271 | |
|
272 | 272 | def doctest_time(): |
|
273 | 273 | """ |
|
274 | 274 | In [10]: %time None |
|
275 | 275 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
276 | 276 | Wall time: 0.00 s |
|
277 | 277 | |
|
278 | 278 | In [11]: def f(kmjy): |
|
279 | 279 | ....: %time print 2*kmjy |
|
280 | 280 | |
|
281 | 281 | In [12]: f(3) |
|
282 | 282 | 6 |
|
283 | 283 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
284 | 284 | Wall time: 0.00 s |
|
285 | 285 | """ |
|
286 | 286 | |
|
287 | 287 | |
|
288 | 288 | def test_doctest_mode(): |
|
289 | 289 | "Toggle doctest_mode twice, it should be a no-op and run without error" |
|
290 | 290 | _ip.magic('doctest_mode') |
|
291 | 291 | _ip.magic('doctest_mode') |
|
292 | 292 | |
|
293 | 293 | |
|
294 | 294 | def test_parse_options(): |
|
295 | 295 | """Tests for basic options parsing in magics.""" |
|
296 | 296 | # These are only the most minimal of tests, more should be added later. At |
|
297 | 297 | # the very least we check that basic text/unicode calls work OK. |
|
298 | 298 | nt.assert_equal(_ip.parse_options('foo', '')[1], 'foo') |
|
299 | 299 | nt.assert_equal(_ip.parse_options(u'foo', '')[1], u'foo') |
|
300 | 300 | |
|
301 | 301 | |
|
302 | 302 | def test_dirops(): |
|
303 | 303 | """Test various directory handling operations.""" |
|
304 | 304 | curpath = lambda :os.path.splitdrive(os.getcwdu())[1].replace('\\','/') |
|
305 | 305 | |
|
306 | 306 | startdir = os.getcwdu() |
|
307 | 307 | ipdir = _ip.ipython_dir |
|
308 | 308 | try: |
|
309 | 309 | _ip.magic('cd "%s"' % ipdir) |
|
310 | 310 | nt.assert_equal(curpath(), ipdir) |
|
311 | 311 | _ip.magic('cd -') |
|
312 | 312 | nt.assert_equal(curpath(), startdir) |
|
313 | 313 | _ip.magic('pushd "%s"' % ipdir) |
|
314 | 314 | nt.assert_equal(curpath(), ipdir) |
|
315 | 315 | _ip.magic('popd') |
|
316 | 316 | nt.assert_equal(curpath(), startdir) |
|
317 | 317 | finally: |
|
318 | 318 | os.chdir(startdir) |
|
319 | 319 | |
|
320 | 320 | |
|
321 | 321 | def check_cpaste(code, should_fail=False): |
|
322 | 322 | """Execute code via 'cpaste' and ensure it was executed, unless |
|
323 | 323 | should_fail is set. |
|
324 | 324 | """ |
|
325 | 325 | _ip.user_ns['code_ran'] = False |
|
326 | 326 | |
|
327 | 327 | src = StringIO() |
|
328 | 328 | src.write('\n') |
|
329 | 329 | src.write(code) |
|
330 | 330 | src.write('\n--\n') |
|
331 | 331 | src.seek(0) |
|
332 | 332 | |
|
333 | 333 | stdin_save = sys.stdin |
|
334 | 334 | sys.stdin = src |
|
335 | 335 | |
|
336 | 336 | try: |
|
337 | 337 | _ip.magic('cpaste') |
|
338 | 338 | except: |
|
339 | 339 | if not should_fail: |
|
340 | 340 | raise AssertionError("Failure not expected : '%s'" % |
|
341 | 341 | code) |
|
342 | 342 | else: |
|
343 | 343 | assert _ip.user_ns['code_ran'] |
|
344 | 344 | if should_fail: |
|
345 | 345 | raise AssertionError("Failure expected : '%s'" % code) |
|
346 | 346 | finally: |
|
347 | 347 | sys.stdin = stdin_save |
|
348 | 348 | |
|
349 | 349 | |
|
350 | 350 | def test_cpaste(): |
|
351 | 351 | """Test cpaste magic""" |
|
352 | 352 | |
|
353 | 353 | def run(): |
|
354 | 354 | """Marker function: sets a flag when executed. |
|
355 | 355 | """ |
|
356 | 356 | _ip.user_ns['code_ran'] = True |
|
357 | 357 | return 'run' # return string so '+ run()' doesn't result in success |
|
358 | 358 | |
|
359 | 359 | tests = {'pass': ["> > > run()", |
|
360 | 360 | ">>> > run()", |
|
361 | 361 | "+++ run()", |
|
362 | 362 | "++ run()", |
|
363 | 363 | " >>> run()"], |
|
364 | 364 | |
|
365 | 365 | 'fail': ["+ + run()", |
|
366 | 366 | " ++ run()"]} |
|
367 | 367 | |
|
368 | 368 | _ip.user_ns['run'] = run |
|
369 | 369 | |
|
370 | 370 | for code in tests['pass']: |
|
371 | 371 | check_cpaste(code) |
|
372 | 372 | |
|
373 | 373 | for code in tests['fail']: |
|
374 | 374 | check_cpaste(code, should_fail=True) |
|
375 | 375 | |
|
376 | 376 | def test_xmode(): |
|
377 | 377 | # Calling xmode three times should be a no-op |
|
378 | 378 | xmode = _ip.InteractiveTB.mode |
|
379 | 379 | for i in range(3): |
|
380 | 380 | _ip.magic("xmode") |
|
381 | 381 | nt.assert_equal(_ip.InteractiveTB.mode, xmode) |
|
382 | ||
|
383 | def test_reset_hard(): | |
|
384 | monitor = [] | |
|
385 | class A(object): | |
|
386 | def __del__(self): | |
|
387 | monitor.append(1) | |
|
388 | def __repr__(self): | |
|
389 | return "<A instance>" | |
|
390 | ||
|
391 | _ip.user_ns["a"] = A() | |
|
392 | _ip.run_cell("a") | |
|
393 | ||
|
394 | nt.assert_equal(monitor, []) | |
|
395 | _ip.magic_reset("-f") | |
|
396 | nt.assert_equal(monitor, [1]) | |
|
382 | 397 | |
|
383 | 398 | def doctest_who(): |
|
384 | 399 | """doctest for %who |
|
385 | 400 | |
|
386 | 401 | In [1]: %reset -f |
|
387 | 402 | |
|
388 | 403 | In [2]: alpha = 123 |
|
389 | 404 | |
|
390 | 405 | In [3]: beta = 'beta' |
|
391 | 406 | |
|
392 | 407 | In [4]: %who int |
|
393 | 408 | alpha |
|
394 | 409 | |
|
395 | 410 | In [5]: %who str |
|
396 | 411 | beta |
|
397 | 412 | |
|
398 | 413 | In [6]: %whos |
|
399 | 414 | Variable Type Data/Info |
|
400 | 415 | ---------------------------- |
|
401 | 416 | alpha int 123 |
|
402 | 417 | beta str beta |
|
403 | 418 | |
|
404 | 419 | In [7]: %who_ls |
|
405 | 420 | Out[7]: ['alpha', 'beta'] |
|
406 | 421 | """ |
|
407 | 422 | |
|
408 | 423 | def doctest_precision(): |
|
409 | 424 | """doctest for %precision |
|
410 | 425 | |
|
411 | 426 | In [1]: f = get_ipython().shell.display_formatter.formatters['text/plain'] |
|
412 | 427 | |
|
413 | 428 | In [2]: %precision 5 |
|
414 | 429 | Out[2]: '%.5f' |
|
415 | 430 | |
|
416 | 431 | In [3]: f.float_format |
|
417 | 432 | Out[3]: '%.5f' |
|
418 | 433 | |
|
419 | 434 | In [4]: %precision %e |
|
420 | 435 | Out[4]: '%e' |
|
421 | 436 | |
|
422 | 437 | In [5]: f(3.1415927) |
|
423 | 438 | Out[5]: '3.141593e+00' |
|
424 | 439 | """ |
|
425 | 440 |
General Comments 0
You need to be logged in to leave comments.
Login now