Show More
@@ -1,2707 +1,2741 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__ as builtin_mod |
|
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 | |
|
33 | 33 | try: |
|
34 | 34 | from contextlib import nested |
|
35 | 35 | except: |
|
36 | 36 | from IPython.utils.nested_context import nested |
|
37 | 37 | |
|
38 | 38 | from IPython.config.configurable import SingletonConfigurable |
|
39 | 39 | from IPython.core import debugger, oinspect |
|
40 | 40 | from IPython.core import history as ipcorehist |
|
41 | 41 | from IPython.core import page |
|
42 | 42 | from IPython.core import prefilter |
|
43 | 43 | from IPython.core import shadowns |
|
44 | 44 | from IPython.core import ultratb |
|
45 | 45 | from IPython.core.alias import AliasManager, AliasError |
|
46 | 46 | from IPython.core.autocall import ExitAutocall |
|
47 | 47 | from IPython.core.builtin_trap import BuiltinTrap |
|
48 | 48 | from IPython.core.compilerop import CachingCompiler |
|
49 | 49 | from IPython.core.display_trap import DisplayTrap |
|
50 | 50 | from IPython.core.displayhook import DisplayHook |
|
51 | 51 | from IPython.core.displaypub import DisplayPublisher |
|
52 | 52 | from IPython.core.error import TryNext, UsageError |
|
53 | 53 | from IPython.core.extensions import ExtensionManager |
|
54 | 54 | from IPython.core.fakemodule import FakeModule, init_fakemod_dict |
|
55 | 55 | from IPython.core.formatters import DisplayFormatter |
|
56 | 56 | from IPython.core.history import HistoryManager |
|
57 | 57 | from IPython.core.inputsplitter import IPythonInputSplitter |
|
58 | 58 | from IPython.core.logger import Logger |
|
59 | 59 | from IPython.core.macro import Macro |
|
60 | 60 | from IPython.core.magic import Magic |
|
61 | 61 | from IPython.core.payload import PayloadManager |
|
62 | 62 | from IPython.core.plugin import PluginManager |
|
63 | 63 | from IPython.core.prefilter import PrefilterManager, ESC_MAGIC |
|
64 | 64 | from IPython.core.profiledir import ProfileDir |
|
65 | 65 | from IPython.core.pylabtools import pylab_activate |
|
66 | 66 | from IPython.core.prompts import PromptManager |
|
67 | 67 | from IPython.external.Itpl import ItplNS |
|
68 | 68 | from IPython.utils import PyColorize |
|
69 | 69 | from IPython.utils import io |
|
70 | 70 | from IPython.utils import py3compat |
|
71 | 71 | from IPython.utils.doctestreload import doctest_reload |
|
72 | 72 | from IPython.utils.io import ask_yes_no, rprint |
|
73 | 73 | from IPython.utils.ipstruct import Struct |
|
74 | 74 | from IPython.utils.path import get_home_dir, get_ipython_dir, HomeDirError |
|
75 | 75 | from IPython.utils.pickleshare import PickleShareDB |
|
76 | 76 | from IPython.utils.process import system, getoutput |
|
77 | 77 | from IPython.utils.strdispatch import StrDispatch |
|
78 | 78 | from IPython.utils.syspathcontext import prepended_to_syspath |
|
79 | 79 | from IPython.utils.text import (num_ini_spaces, format_screen, LSString, SList, |
|
80 | 80 | DollarFormatter) |
|
81 | 81 | from IPython.utils.traitlets import (Integer, CBool, CaselessStrEnum, Enum, |
|
82 | 82 | List, Unicode, Instance, Type) |
|
83 | 83 | from IPython.utils.warn import warn, error, fatal |
|
84 | 84 | import IPython.core.hooks |
|
85 | 85 | |
|
86 | 86 | #----------------------------------------------------------------------------- |
|
87 | 87 | # Globals |
|
88 | 88 | #----------------------------------------------------------------------------- |
|
89 | 89 | |
|
90 | 90 | # compiled regexps for autoindent management |
|
91 | 91 | dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass') |
|
92 | 92 | |
|
93 | 93 | #----------------------------------------------------------------------------- |
|
94 | 94 | # Utilities |
|
95 | 95 | #----------------------------------------------------------------------------- |
|
96 | 96 | |
|
97 | 97 | def softspace(file, newvalue): |
|
98 | 98 | """Copied from code.py, to remove the dependency""" |
|
99 | 99 | |
|
100 | 100 | oldvalue = 0 |
|
101 | 101 | try: |
|
102 | 102 | oldvalue = file.softspace |
|
103 | 103 | except AttributeError: |
|
104 | 104 | pass |
|
105 | 105 | try: |
|
106 | 106 | file.softspace = newvalue |
|
107 | 107 | except (AttributeError, TypeError): |
|
108 | 108 | # "attribute-less object" or "read-only attributes" |
|
109 | 109 | pass |
|
110 | 110 | return oldvalue |
|
111 | 111 | |
|
112 | 112 | |
|
113 | 113 | def no_op(*a, **kw): pass |
|
114 | 114 | |
|
115 | 115 | class NoOpContext(object): |
|
116 | 116 | def __enter__(self): pass |
|
117 | 117 | def __exit__(self, type, value, traceback): pass |
|
118 | 118 | no_op_context = NoOpContext() |
|
119 | 119 | |
|
120 | 120 | class SpaceInInput(Exception): pass |
|
121 | 121 | |
|
122 | 122 | class Bunch: pass |
|
123 | 123 | |
|
124 | 124 | |
|
125 | 125 | def get_default_colors(): |
|
126 | 126 | if sys.platform=='darwin': |
|
127 | 127 | return "LightBG" |
|
128 | 128 | elif os.name=='nt': |
|
129 | 129 | return 'Linux' |
|
130 | 130 | else: |
|
131 | 131 | return 'Linux' |
|
132 | 132 | |
|
133 | 133 | |
|
134 | 134 | class SeparateUnicode(Unicode): |
|
135 | 135 | """A Unicode subclass to validate separate_in, separate_out, etc. |
|
136 | 136 | |
|
137 | 137 | This is a Unicode based trait that converts '0'->'' and '\\n'->'\n'. |
|
138 | 138 | """ |
|
139 | 139 | |
|
140 | 140 | def validate(self, obj, value): |
|
141 | 141 | if value == '0': value = '' |
|
142 | 142 | value = value.replace('\\n','\n') |
|
143 | 143 | return super(SeparateUnicode, self).validate(obj, value) |
|
144 | 144 | |
|
145 | 145 | |
|
146 | 146 | class ReadlineNoRecord(object): |
|
147 | 147 | """Context manager to execute some code, then reload readline history |
|
148 | 148 | so that interactive input to the code doesn't appear when pressing up.""" |
|
149 | 149 | def __init__(self, shell): |
|
150 | 150 | self.shell = shell |
|
151 | 151 | self._nested_level = 0 |
|
152 | 152 | |
|
153 | 153 | def __enter__(self): |
|
154 | 154 | if self._nested_level == 0: |
|
155 | 155 | try: |
|
156 | 156 | self.orig_length = self.current_length() |
|
157 | 157 | self.readline_tail = self.get_readline_tail() |
|
158 | 158 | except (AttributeError, IndexError): # Can fail with pyreadline |
|
159 | 159 | self.orig_length, self.readline_tail = 999999, [] |
|
160 | 160 | self._nested_level += 1 |
|
161 | 161 | |
|
162 | 162 | def __exit__(self, type, value, traceback): |
|
163 | 163 | self._nested_level -= 1 |
|
164 | 164 | if self._nested_level == 0: |
|
165 | 165 | # Try clipping the end if it's got longer |
|
166 | 166 | try: |
|
167 | 167 | e = self.current_length() - self.orig_length |
|
168 | 168 | if e > 0: |
|
169 | 169 | for _ in range(e): |
|
170 | 170 | self.shell.readline.remove_history_item(self.orig_length) |
|
171 | 171 | |
|
172 | 172 | # If it still doesn't match, just reload readline history. |
|
173 | 173 | if self.current_length() != self.orig_length \ |
|
174 | 174 | or self.get_readline_tail() != self.readline_tail: |
|
175 | 175 | self.shell.refill_readline_hist() |
|
176 | 176 | except (AttributeError, IndexError): |
|
177 | 177 | pass |
|
178 | 178 | # Returning False will cause exceptions to propagate |
|
179 | 179 | return False |
|
180 | 180 | |
|
181 | 181 | def current_length(self): |
|
182 | 182 | return self.shell.readline.get_current_history_length() |
|
183 | 183 | |
|
184 | 184 | def get_readline_tail(self, n=10): |
|
185 | 185 | """Get the last n items in readline history.""" |
|
186 | 186 | end = self.shell.readline.get_current_history_length() + 1 |
|
187 | 187 | start = max(end-n, 1) |
|
188 | 188 | ghi = self.shell.readline.get_history_item |
|
189 | 189 | return [ghi(x) for x in range(start, end)] |
|
190 | 190 | |
|
191 | 191 | |
|
192 | 192 | _autocall_help = """ |
|
193 | 193 | Make IPython automatically call any callable object even if |
|
194 | 194 | you didn't type explicit parentheses. For example, 'str 43' becomes 'str(43)' |
|
195 | 195 | automatically. The value can be '0' to disable the feature, '1' for 'smart' |
|
196 | 196 | autocall, where it is not applied if there are no more arguments on the line, |
|
197 | 197 | and '2' for 'full' autocall, where all callable objects are automatically |
|
198 | 198 | called (even if no arguments are present). The default is '1'. |
|
199 | 199 | """ |
|
200 | 200 | |
|
201 | 201 | #----------------------------------------------------------------------------- |
|
202 | 202 | # Main IPython class |
|
203 | 203 | #----------------------------------------------------------------------------- |
|
204 | 204 | |
|
205 | 205 | class InteractiveShell(SingletonConfigurable, Magic): |
|
206 | 206 | """An enhanced, interactive shell for Python.""" |
|
207 | 207 | |
|
208 | 208 | _instance = None |
|
209 | 209 | |
|
210 | 210 | autocall = Enum((0,1,2), default_value=1, config=True, help= |
|
211 | 211 | """ |
|
212 | 212 | Make IPython automatically call any callable object even if you didn't |
|
213 | 213 | type explicit parentheses. For example, 'str 43' becomes 'str(43)' |
|
214 | 214 | automatically. The value can be '0' to disable the feature, '1' for |
|
215 | 215 | 'smart' autocall, where it is not applied if there are no more |
|
216 | 216 | arguments on the line, and '2' for 'full' autocall, where all callable |
|
217 | 217 | objects are automatically called (even if no arguments are present). |
|
218 | 218 | The default is '1'. |
|
219 | 219 | """ |
|
220 | 220 | ) |
|
221 | 221 | # TODO: remove all autoindent logic and put into frontends. |
|
222 | 222 | # We can't do this yet because even runlines uses the autoindent. |
|
223 | 223 | autoindent = CBool(True, config=True, help= |
|
224 | 224 | """ |
|
225 | 225 | Autoindent IPython code entered interactively. |
|
226 | 226 | """ |
|
227 | 227 | ) |
|
228 | 228 | automagic = CBool(True, config=True, help= |
|
229 | 229 | """ |
|
230 | 230 | Enable magic commands to be called without the leading %. |
|
231 | 231 | """ |
|
232 | 232 | ) |
|
233 | 233 | cache_size = Integer(1000, config=True, help= |
|
234 | 234 | """ |
|
235 | 235 | Set the size of the output cache. The default is 1000, you can |
|
236 | 236 | change it permanently in your config file. Setting it to 0 completely |
|
237 | 237 | disables the caching system, and the minimum value accepted is 20 (if |
|
238 | 238 | you provide a value less than 20, it is reset to 0 and a warning is |
|
239 | 239 | issued). This limit is defined because otherwise you'll spend more |
|
240 | 240 | time re-flushing a too small cache than working |
|
241 | 241 | """ |
|
242 | 242 | ) |
|
243 | 243 | color_info = CBool(True, config=True, help= |
|
244 | 244 | """ |
|
245 | 245 | Use colors for displaying information about objects. Because this |
|
246 | 246 | information is passed through a pager (like 'less'), and some pagers |
|
247 | 247 | get confused with color codes, this capability can be turned off. |
|
248 | 248 | """ |
|
249 | 249 | ) |
|
250 | 250 | colors = CaselessStrEnum(('NoColor','LightBG','Linux'), |
|
251 | 251 | default_value=get_default_colors(), config=True, |
|
252 | 252 | help="Set the color scheme (NoColor, Linux, or LightBG)." |
|
253 | 253 | ) |
|
254 | 254 | colors_force = CBool(False, help= |
|
255 | 255 | """ |
|
256 | 256 | Force use of ANSI color codes, regardless of OS and readline |
|
257 | 257 | availability. |
|
258 | 258 | """ |
|
259 | 259 | # FIXME: This is essentially a hack to allow ZMQShell to show colors |
|
260 | 260 | # without readline on Win32. When the ZMQ formatting system is |
|
261 | 261 | # refactored, this should be removed. |
|
262 | 262 | ) |
|
263 | 263 | debug = CBool(False, config=True) |
|
264 | 264 | deep_reload = CBool(False, config=True, help= |
|
265 | 265 | """ |
|
266 | 266 | Enable deep (recursive) reloading by default. IPython can use the |
|
267 | 267 | deep_reload module which reloads changes in modules recursively (it |
|
268 | 268 | replaces the reload() function, so you don't need to change anything to |
|
269 | 269 | use it). deep_reload() forces a full reload of modules whose code may |
|
270 | 270 | have changed, which the default reload() function does not. When |
|
271 | 271 | deep_reload is off, IPython will use the normal reload(), but |
|
272 | 272 | deep_reload will still be available as dreload(). |
|
273 | 273 | """ |
|
274 | 274 | ) |
|
275 | 275 | display_formatter = Instance(DisplayFormatter) |
|
276 | 276 | displayhook_class = Type(DisplayHook) |
|
277 | 277 | display_pub_class = Type(DisplayPublisher) |
|
278 | 278 | |
|
279 | 279 | exit_now = CBool(False) |
|
280 | 280 | exiter = Instance(ExitAutocall) |
|
281 | 281 | def _exiter_default(self): |
|
282 | 282 | return ExitAutocall(self) |
|
283 | 283 | # Monotonically increasing execution counter |
|
284 | 284 | execution_count = Integer(1) |
|
285 | 285 | filename = Unicode("<ipython console>") |
|
286 | 286 | ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__ |
|
287 | 287 | |
|
288 | 288 | # Input splitter, to split entire cells of input into either individual |
|
289 | 289 | # interactive statements or whole blocks. |
|
290 | 290 | input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter', |
|
291 | 291 | (), {}) |
|
292 | 292 | logstart = CBool(False, config=True, help= |
|
293 | 293 | """ |
|
294 | 294 | Start logging to the default log file. |
|
295 | 295 | """ |
|
296 | 296 | ) |
|
297 | 297 | logfile = Unicode('', config=True, help= |
|
298 | 298 | """ |
|
299 | 299 | The name of the logfile to use. |
|
300 | 300 | """ |
|
301 | 301 | ) |
|
302 | 302 | logappend = Unicode('', config=True, help= |
|
303 | 303 | """ |
|
304 | 304 | Start logging to the given file in append mode. |
|
305 | 305 | """ |
|
306 | 306 | ) |
|
307 | 307 | object_info_string_level = Enum((0,1,2), default_value=0, |
|
308 | 308 | config=True) |
|
309 | 309 | pdb = CBool(False, config=True, help= |
|
310 | 310 | """ |
|
311 | 311 | Automatically call the pdb debugger after every exception. |
|
312 | 312 | """ |
|
313 | 313 | ) |
|
314 | 314 | multiline_history = CBool(sys.platform != 'win32', config=True, |
|
315 | 315 | help="Save multi-line entries as one entry in readline history" |
|
316 | 316 | ) |
|
317 | 317 | |
|
318 | prompt_in1 = Unicode('In [\\#]: ', config=True) | |
|
319 | prompt_in2 = Unicode(' .\\D.: ', config=True) | |
|
320 |
prompt_ |
|
|
321 | prompts_pad_left = CBool(True, config=True) | |
|
318 | # deprecated prompt traits: | |
|
319 | ||
|
320 | prompt_in1 = Unicode('In [\\#]: ', config=True, | |
|
321 | help="Deprecated, use PromptManager.in_template") | |
|
322 | prompt_in2 = Unicode(' .\\D.: ', config=True, | |
|
323 | help="Deprecated, use PromptManager.in2_template") | |
|
324 | prompt_out = Unicode('Out[\\#]: ', config=True, | |
|
325 | help="Deprecated, use PromptManager.out_template") | |
|
326 | prompts_pad_left = CBool(True, config=True, | |
|
327 | help="Deprecated, use PromptManager.justify") | |
|
328 | ||
|
329 | def _prompt_trait_changed(self, name, old, new): | |
|
330 | table = { | |
|
331 | 'prompt_in1' : 'in_template', | |
|
332 | 'prompt_in2' : 'in2_template', | |
|
333 | 'prompt_out' : 'out_template', | |
|
334 | 'prompts_pad_left' : 'justify', | |
|
335 | } | |
|
336 | warn("InteractiveShell.{name} is deprecated, use PromptManager.{newname}\n".format( | |
|
337 | name=name, newname=table[name]) | |
|
338 | ) | |
|
339 | # protect against weird cases where self.config may not exist: | |
|
340 | if self.config is not None: | |
|
341 | # propagate to corresponding PromptManager trait | |
|
342 | setattr(self.config.PromptManager, table[name], new) | |
|
343 | ||
|
344 | _prompt_in1_changed = _prompt_trait_changed | |
|
345 | _prompt_in2_changed = _prompt_trait_changed | |
|
346 | _prompt_out_changed = _prompt_trait_changed | |
|
347 | _prompt_pad_left_changed = _prompt_trait_changed | |
|
348 | ||
|
349 | show_rewritten_input = CBool(True, config=True, | |
|
350 | help="Show rewritten input, e.g. for autocall." | |
|
351 | ) | |
|
352 | ||
|
322 | 353 | quiet = CBool(False, config=True) |
|
323 | 354 | |
|
324 | 355 | history_length = Integer(10000, config=True) |
|
325 | 356 | |
|
326 | 357 | # The readline stuff will eventually be moved to the terminal subclass |
|
327 | 358 | # but for now, we can't do that as readline is welded in everywhere. |
|
328 | 359 | readline_use = CBool(True, config=True) |
|
329 | 360 | readline_remove_delims = Unicode('-/~', config=True) |
|
330 | 361 | # don't use \M- bindings by default, because they |
|
331 | 362 | # conflict with 8-bit encodings. See gh-58,gh-88 |
|
332 | 363 | readline_parse_and_bind = List([ |
|
333 | 364 | 'tab: complete', |
|
334 | 365 | '"\C-l": clear-screen', |
|
335 | 366 | 'set show-all-if-ambiguous on', |
|
336 | 367 | '"\C-o": tab-insert', |
|
337 | 368 | '"\C-r": reverse-search-history', |
|
338 | 369 | '"\C-s": forward-search-history', |
|
339 | 370 | '"\C-p": history-search-backward', |
|
340 | 371 | '"\C-n": history-search-forward', |
|
341 | 372 | '"\e[A": history-search-backward', |
|
342 | 373 | '"\e[B": history-search-forward', |
|
343 | 374 | '"\C-k": kill-line', |
|
344 | 375 | '"\C-u": unix-line-discard', |
|
345 | 376 | ], allow_none=False, config=True) |
|
346 | 377 | |
|
347 | 378 | # TODO: this part of prompt management should be moved to the frontends. |
|
348 | 379 | # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n' |
|
349 | 380 | separate_in = SeparateUnicode('\n', config=True) |
|
350 | 381 | separate_out = SeparateUnicode('', config=True) |
|
351 | 382 | separate_out2 = SeparateUnicode('', config=True) |
|
352 | 383 | wildcards_case_sensitive = CBool(True, config=True) |
|
353 | 384 | xmode = CaselessStrEnum(('Context','Plain', 'Verbose'), |
|
354 | 385 | default_value='Context', config=True) |
|
355 | 386 | |
|
356 | 387 | # Subcomponents of InteractiveShell |
|
357 | 388 | alias_manager = Instance('IPython.core.alias.AliasManager') |
|
358 | 389 | prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager') |
|
359 | 390 | builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap') |
|
360 | 391 | display_trap = Instance('IPython.core.display_trap.DisplayTrap') |
|
361 | 392 | extension_manager = Instance('IPython.core.extensions.ExtensionManager') |
|
362 | 393 | plugin_manager = Instance('IPython.core.plugin.PluginManager') |
|
363 | 394 | payload_manager = Instance('IPython.core.payload.PayloadManager') |
|
364 | 395 | history_manager = Instance('IPython.core.history.HistoryManager') |
|
365 | 396 | |
|
366 | 397 | profile_dir = Instance('IPython.core.application.ProfileDir') |
|
367 | 398 | @property |
|
368 | 399 | def profile(self): |
|
369 | 400 | if self.profile_dir is not None: |
|
370 | 401 | name = os.path.basename(self.profile_dir.location) |
|
371 | 402 | return name.replace('profile_','') |
|
372 | 403 | |
|
373 | 404 | |
|
374 | 405 | # Private interface |
|
375 | 406 | _post_execute = Instance(dict) |
|
376 | 407 | |
|
377 | 408 | def __init__(self, config=None, ipython_dir=None, profile_dir=None, |
|
378 | 409 | user_module=None, user_ns=None, |
|
379 | 410 | custom_exceptions=((), None)): |
|
380 | 411 | |
|
381 | 412 | # This is where traits with a config_key argument are updated |
|
382 | 413 | # from the values on config. |
|
383 | 414 | super(InteractiveShell, self).__init__(config=config) |
|
384 | 415 | self.configurables = [self] |
|
385 | 416 | |
|
386 | 417 | # These are relatively independent and stateless |
|
387 | 418 | self.init_ipython_dir(ipython_dir) |
|
388 | 419 | self.init_profile_dir(profile_dir) |
|
389 | 420 | self.init_instance_attrs() |
|
390 | 421 | self.init_environment() |
|
391 | 422 | |
|
392 | 423 | # Create namespaces (user_ns, user_global_ns, etc.) |
|
393 | 424 | self.init_create_namespaces(user_module, user_ns) |
|
394 | 425 | # This has to be done after init_create_namespaces because it uses |
|
395 | 426 | # something in self.user_ns, but before init_sys_modules, which |
|
396 | 427 | # is the first thing to modify sys. |
|
397 | 428 | # TODO: When we override sys.stdout and sys.stderr before this class |
|
398 | 429 | # is created, we are saving the overridden ones here. Not sure if this |
|
399 | 430 | # is what we want to do. |
|
400 | 431 | self.save_sys_module_state() |
|
401 | 432 | self.init_sys_modules() |
|
402 | 433 | |
|
403 | 434 | # While we're trying to have each part of the code directly access what |
|
404 | 435 | # it needs without keeping redundant references to objects, we have too |
|
405 | 436 | # much legacy code that expects ip.db to exist. |
|
406 | 437 | self.db = PickleShareDB(os.path.join(self.profile_dir.location, 'db')) |
|
407 | 438 | |
|
408 | 439 | self.init_history() |
|
409 | 440 | self.init_encoding() |
|
410 | 441 | self.init_prefilter() |
|
411 | 442 | |
|
412 | 443 | Magic.__init__(self, self) |
|
413 | 444 | |
|
414 | 445 | self.init_syntax_highlighting() |
|
415 | 446 | self.init_hooks() |
|
416 | 447 | self.init_pushd_popd_magic() |
|
417 | 448 | # self.init_traceback_handlers use to be here, but we moved it below |
|
418 | 449 | # because it and init_io have to come after init_readline. |
|
419 | 450 | self.init_user_ns() |
|
420 | 451 | self.init_logger() |
|
421 | 452 | self.init_alias() |
|
422 | 453 | self.init_builtins() |
|
423 | 454 | |
|
424 | 455 | # pre_config_initialization |
|
425 | 456 | |
|
426 | 457 | # The next section should contain everything that was in ipmaker. |
|
427 | 458 | self.init_logstart() |
|
428 | 459 | |
|
429 | 460 | # The following was in post_config_initialization |
|
430 | 461 | self.init_inspector() |
|
431 | 462 | # init_readline() must come before init_io(), because init_io uses |
|
432 | 463 | # readline related things. |
|
433 | 464 | self.init_readline() |
|
434 | 465 | # We save this here in case user code replaces raw_input, but it needs |
|
435 | 466 | # to be after init_readline(), because PyPy's readline works by replacing |
|
436 | 467 | # raw_input. |
|
437 | 468 | if py3compat.PY3: |
|
438 | 469 | self.raw_input_original = input |
|
439 | 470 | else: |
|
440 | 471 | self.raw_input_original = raw_input |
|
441 | 472 | # init_completer must come after init_readline, because it needs to |
|
442 | 473 | # know whether readline is present or not system-wide to configure the |
|
443 | 474 | # completers, since the completion machinery can now operate |
|
444 | 475 | # independently of readline (e.g. over the network) |
|
445 | 476 | self.init_completer() |
|
446 | 477 | # TODO: init_io() needs to happen before init_traceback handlers |
|
447 | 478 | # because the traceback handlers hardcode the stdout/stderr streams. |
|
448 | 479 | # This logic in in debugger.Pdb and should eventually be changed. |
|
449 | 480 | self.init_io() |
|
450 | 481 | self.init_traceback_handlers(custom_exceptions) |
|
451 | 482 | self.init_prompts() |
|
452 | 483 | self.init_display_formatter() |
|
453 | 484 | self.init_display_pub() |
|
454 | 485 | self.init_displayhook() |
|
455 | 486 | self.init_reload_doctest() |
|
456 | 487 | self.init_magics() |
|
457 | 488 | self.init_pdb() |
|
458 | 489 | self.init_extension_manager() |
|
459 | 490 | self.init_plugin_manager() |
|
460 | 491 | self.init_payload() |
|
461 | 492 | self.hooks.late_startup_hook() |
|
462 | 493 | atexit.register(self.atexit_operations) |
|
463 | 494 | |
|
464 | 495 | def get_ipython(self): |
|
465 | 496 | """Return the currently running IPython instance.""" |
|
466 | 497 | return self |
|
467 | 498 | |
|
468 | 499 | #------------------------------------------------------------------------- |
|
469 | 500 | # Trait changed handlers |
|
470 | 501 | #------------------------------------------------------------------------- |
|
471 | 502 | |
|
472 | 503 | def _ipython_dir_changed(self, name, new): |
|
473 | 504 | if not os.path.isdir(new): |
|
474 | 505 | os.makedirs(new, mode = 0777) |
|
475 | 506 | |
|
476 | 507 | def set_autoindent(self,value=None): |
|
477 | 508 | """Set the autoindent flag, checking for readline support. |
|
478 | 509 | |
|
479 | 510 | If called with no arguments, it acts as a toggle.""" |
|
480 | 511 | |
|
481 | 512 | if value != 0 and not self.has_readline: |
|
482 | 513 | if os.name == 'posix': |
|
483 | 514 | warn("The auto-indent feature requires the readline library") |
|
484 | 515 | self.autoindent = 0 |
|
485 | 516 | return |
|
486 | 517 | if value is None: |
|
487 | 518 | self.autoindent = not self.autoindent |
|
488 | 519 | else: |
|
489 | 520 | self.autoindent = value |
|
490 | 521 | |
|
491 | 522 | #------------------------------------------------------------------------- |
|
492 | 523 | # init_* methods called by __init__ |
|
493 | 524 | #------------------------------------------------------------------------- |
|
494 | 525 | |
|
495 | 526 | def init_ipython_dir(self, ipython_dir): |
|
496 | 527 | if ipython_dir is not None: |
|
497 | 528 | self.ipython_dir = ipython_dir |
|
498 | 529 | return |
|
499 | 530 | |
|
500 | 531 | self.ipython_dir = get_ipython_dir() |
|
501 | 532 | |
|
502 | 533 | def init_profile_dir(self, profile_dir): |
|
503 | 534 | if profile_dir is not None: |
|
504 | 535 | self.profile_dir = profile_dir |
|
505 | 536 | return |
|
506 | 537 | self.profile_dir =\ |
|
507 | 538 | ProfileDir.create_profile_dir_by_name(self.ipython_dir, 'default') |
|
508 | 539 | |
|
509 | 540 | def init_instance_attrs(self): |
|
510 | 541 | self.more = False |
|
511 | 542 | |
|
512 | 543 | # command compiler |
|
513 | 544 | self.compile = CachingCompiler() |
|
514 | 545 | |
|
515 | 546 | # Make an empty namespace, which extension writers can rely on both |
|
516 | 547 | # existing and NEVER being used by ipython itself. This gives them a |
|
517 | 548 | # convenient location for storing additional information and state |
|
518 | 549 | # their extensions may require, without fear of collisions with other |
|
519 | 550 | # ipython names that may develop later. |
|
520 | 551 | self.meta = Struct() |
|
521 | 552 | |
|
522 | 553 | # Temporary files used for various purposes. Deleted at exit. |
|
523 | 554 | self.tempfiles = [] |
|
524 | 555 | |
|
525 | 556 | # Keep track of readline usage (later set by init_readline) |
|
526 | 557 | self.has_readline = False |
|
527 | 558 | |
|
528 | 559 | # keep track of where we started running (mainly for crash post-mortem) |
|
529 | 560 | # This is not being used anywhere currently. |
|
530 | 561 | self.starting_dir = os.getcwdu() |
|
531 | 562 | |
|
532 | 563 | # Indentation management |
|
533 | 564 | self.indent_current_nsp = 0 |
|
534 | 565 | |
|
535 | 566 | # Dict to track post-execution functions that have been registered |
|
536 | 567 | self._post_execute = {} |
|
537 | 568 | |
|
538 | 569 | def init_environment(self): |
|
539 | 570 | """Any changes we need to make to the user's environment.""" |
|
540 | 571 | pass |
|
541 | 572 | |
|
542 | 573 | def init_encoding(self): |
|
543 | 574 | # Get system encoding at startup time. Certain terminals (like Emacs |
|
544 | 575 | # under Win32 have it set to None, and we need to have a known valid |
|
545 | 576 | # encoding to use in the raw_input() method |
|
546 | 577 | try: |
|
547 | 578 | self.stdin_encoding = sys.stdin.encoding or 'ascii' |
|
548 | 579 | except AttributeError: |
|
549 | 580 | self.stdin_encoding = 'ascii' |
|
550 | 581 | |
|
551 | 582 | def init_syntax_highlighting(self): |
|
552 | 583 | # Python source parser/formatter for syntax highlighting |
|
553 | 584 | pyformat = PyColorize.Parser().format |
|
554 | 585 | self.pycolorize = lambda src: pyformat(src,'str',self.colors) |
|
555 | 586 | |
|
556 | 587 | def init_pushd_popd_magic(self): |
|
557 | 588 | # for pushd/popd management |
|
558 | 589 | self.home_dir = get_home_dir() |
|
559 | 590 | |
|
560 | 591 | self.dir_stack = [] |
|
561 | 592 | |
|
562 | 593 | def init_logger(self): |
|
563 | 594 | self.logger = Logger(self.home_dir, logfname='ipython_log.py', |
|
564 | 595 | logmode='rotate') |
|
565 | 596 | |
|
566 | 597 | def init_logstart(self): |
|
567 | 598 | """Initialize logging in case it was requested at the command line. |
|
568 | 599 | """ |
|
569 | 600 | if self.logappend: |
|
570 | 601 | self.magic_logstart(self.logappend + ' append') |
|
571 | 602 | elif self.logfile: |
|
572 | 603 | self.magic_logstart(self.logfile) |
|
573 | 604 | elif self.logstart: |
|
574 | 605 | self.magic_logstart() |
|
575 | 606 | |
|
576 | 607 | def init_builtins(self): |
|
577 | 608 | self.builtin_trap = BuiltinTrap(shell=self) |
|
578 | 609 | |
|
579 | 610 | def init_inspector(self): |
|
580 | 611 | # Object inspector |
|
581 | 612 | self.inspector = oinspect.Inspector(oinspect.InspectColors, |
|
582 | 613 | PyColorize.ANSICodeColors, |
|
583 | 614 | 'NoColor', |
|
584 | 615 | self.object_info_string_level) |
|
585 | 616 | |
|
586 | 617 | def init_io(self): |
|
587 | 618 | # This will just use sys.stdout and sys.stderr. If you want to |
|
588 | 619 | # override sys.stdout and sys.stderr themselves, you need to do that |
|
589 | 620 | # *before* instantiating this class, because io holds onto |
|
590 | 621 | # references to the underlying streams. |
|
591 | 622 | if sys.platform == 'win32' and self.has_readline: |
|
592 | 623 | io.stdout = io.stderr = io.IOStream(self.readline._outputfile) |
|
593 | 624 | else: |
|
594 | 625 | io.stdout = io.IOStream(sys.stdout) |
|
595 | 626 | io.stderr = io.IOStream(sys.stderr) |
|
596 | 627 | |
|
597 | 628 | def init_prompts(self): |
|
598 | 629 | self.prompt_manager = PromptManager(shell=self, config=self.config) |
|
599 | 630 | self.configurables.append(self.prompt_manager) |
|
600 | 631 | |
|
601 | 632 | def init_display_formatter(self): |
|
602 | 633 | self.display_formatter = DisplayFormatter(config=self.config) |
|
603 | 634 | self.configurables.append(self.display_formatter) |
|
604 | 635 | |
|
605 | 636 | def init_display_pub(self): |
|
606 | 637 | self.display_pub = self.display_pub_class(config=self.config) |
|
607 | 638 | self.configurables.append(self.display_pub) |
|
608 | 639 | |
|
609 | 640 | def init_displayhook(self): |
|
610 | 641 | # Initialize displayhook, set in/out prompts and printing system |
|
611 | 642 | self.displayhook = self.displayhook_class( |
|
612 | 643 | config=self.config, |
|
613 | 644 | shell=self, |
|
614 | 645 | cache_size=self.cache_size, |
|
615 | 646 | ) |
|
616 | 647 | self.configurables.append(self.displayhook) |
|
617 | 648 | # This is a context manager that installs/revmoes the displayhook at |
|
618 | 649 | # the appropriate time. |
|
619 | 650 | self.display_trap = DisplayTrap(hook=self.displayhook) |
|
620 | 651 | |
|
621 | 652 | def init_reload_doctest(self): |
|
622 | 653 | # Do a proper resetting of doctest, including the necessary displayhook |
|
623 | 654 | # monkeypatching |
|
624 | 655 | try: |
|
625 | 656 | doctest_reload() |
|
626 | 657 | except ImportError: |
|
627 | 658 | warn("doctest module does not exist.") |
|
628 | 659 | |
|
629 | 660 | #------------------------------------------------------------------------- |
|
630 | 661 | # Things related to injections into the sys module |
|
631 | 662 | #------------------------------------------------------------------------- |
|
632 | 663 | |
|
633 | 664 | def save_sys_module_state(self): |
|
634 | 665 | """Save the state of hooks in the sys module. |
|
635 | 666 | |
|
636 | 667 | This has to be called after self.user_module is created. |
|
637 | 668 | """ |
|
638 | 669 | self._orig_sys_module_state = {} |
|
639 | 670 | self._orig_sys_module_state['stdin'] = sys.stdin |
|
640 | 671 | self._orig_sys_module_state['stdout'] = sys.stdout |
|
641 | 672 | self._orig_sys_module_state['stderr'] = sys.stderr |
|
642 | 673 | self._orig_sys_module_state['excepthook'] = sys.excepthook |
|
643 | 674 | self._orig_sys_modules_main_name = self.user_module.__name__ |
|
644 | 675 | |
|
645 | 676 | def restore_sys_module_state(self): |
|
646 | 677 | """Restore the state of the sys module.""" |
|
647 | 678 | try: |
|
648 | 679 | for k, v in self._orig_sys_module_state.iteritems(): |
|
649 | 680 | setattr(sys, k, v) |
|
650 | 681 | except AttributeError: |
|
651 | 682 | pass |
|
652 | 683 | # Reset what what done in self.init_sys_modules |
|
653 | 684 | sys.modules[self.user_module.__name__] = self._orig_sys_modules_main_name |
|
654 | 685 | |
|
655 | 686 | #------------------------------------------------------------------------- |
|
656 | 687 | # Things related to hooks |
|
657 | 688 | #------------------------------------------------------------------------- |
|
658 | 689 | |
|
659 | 690 | def init_hooks(self): |
|
660 | 691 | # hooks holds pointers used for user-side customizations |
|
661 | 692 | self.hooks = Struct() |
|
662 | 693 | |
|
663 | 694 | self.strdispatchers = {} |
|
664 | 695 | |
|
665 | 696 | # Set all default hooks, defined in the IPython.hooks module. |
|
666 | 697 | hooks = IPython.core.hooks |
|
667 | 698 | for hook_name in hooks.__all__: |
|
668 | 699 | # default hooks have priority 100, i.e. low; user hooks should have |
|
669 | 700 | # 0-100 priority |
|
670 | 701 | self.set_hook(hook_name,getattr(hooks,hook_name), 100) |
|
671 | 702 | |
|
672 | 703 | def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None): |
|
673 | 704 | """set_hook(name,hook) -> sets an internal IPython hook. |
|
674 | 705 | |
|
675 | 706 | IPython exposes some of its internal API as user-modifiable hooks. By |
|
676 | 707 | adding your function to one of these hooks, you can modify IPython's |
|
677 | 708 | behavior to call at runtime your own routines.""" |
|
678 | 709 | |
|
679 | 710 | # At some point in the future, this should validate the hook before it |
|
680 | 711 | # accepts it. Probably at least check that the hook takes the number |
|
681 | 712 | # of args it's supposed to. |
|
682 | 713 | |
|
683 | 714 | f = types.MethodType(hook,self) |
|
684 | 715 | |
|
685 | 716 | # check if the hook is for strdispatcher first |
|
686 | 717 | if str_key is not None: |
|
687 | 718 | sdp = self.strdispatchers.get(name, StrDispatch()) |
|
688 | 719 | sdp.add_s(str_key, f, priority ) |
|
689 | 720 | self.strdispatchers[name] = sdp |
|
690 | 721 | return |
|
691 | 722 | if re_key is not None: |
|
692 | 723 | sdp = self.strdispatchers.get(name, StrDispatch()) |
|
693 | 724 | sdp.add_re(re.compile(re_key), f, priority ) |
|
694 | 725 | self.strdispatchers[name] = sdp |
|
695 | 726 | return |
|
696 | 727 | |
|
697 | 728 | dp = getattr(self.hooks, name, None) |
|
698 | 729 | if name not in IPython.core.hooks.__all__: |
|
699 | 730 | print "Warning! Hook '%s' is not one of %s" % \ |
|
700 | 731 | (name, IPython.core.hooks.__all__ ) |
|
701 | 732 | if not dp: |
|
702 | 733 | dp = IPython.core.hooks.CommandChainDispatcher() |
|
703 | 734 | |
|
704 | 735 | try: |
|
705 | 736 | dp.add(f,priority) |
|
706 | 737 | except AttributeError: |
|
707 | 738 | # it was not commandchain, plain old func - replace |
|
708 | 739 | dp = f |
|
709 | 740 | |
|
710 | 741 | setattr(self.hooks,name, dp) |
|
711 | 742 | |
|
712 | 743 | def register_post_execute(self, func): |
|
713 | 744 | """Register a function for calling after code execution. |
|
714 | 745 | """ |
|
715 | 746 | if not callable(func): |
|
716 | 747 | raise ValueError('argument %s must be callable' % func) |
|
717 | 748 | self._post_execute[func] = True |
|
718 | 749 | |
|
719 | 750 | #------------------------------------------------------------------------- |
|
720 | 751 | # Things related to the "main" module |
|
721 | 752 | #------------------------------------------------------------------------- |
|
722 | 753 | |
|
723 | 754 | def new_main_mod(self,ns=None): |
|
724 | 755 | """Return a new 'main' module object for user code execution. |
|
725 | 756 | """ |
|
726 | 757 | main_mod = self._user_main_module |
|
727 | 758 | init_fakemod_dict(main_mod,ns) |
|
728 | 759 | return main_mod |
|
729 | 760 | |
|
730 | 761 | def cache_main_mod(self,ns,fname): |
|
731 | 762 | """Cache a main module's namespace. |
|
732 | 763 | |
|
733 | 764 | When scripts are executed via %run, we must keep a reference to the |
|
734 | 765 | namespace of their __main__ module (a FakeModule instance) around so |
|
735 | 766 | that Python doesn't clear it, rendering objects defined therein |
|
736 | 767 | useless. |
|
737 | 768 | |
|
738 | 769 | This method keeps said reference in a private dict, keyed by the |
|
739 | 770 | absolute path of the module object (which corresponds to the script |
|
740 | 771 | path). This way, for multiple executions of the same script we only |
|
741 | 772 | keep one copy of the namespace (the last one), thus preventing memory |
|
742 | 773 | leaks from old references while allowing the objects from the last |
|
743 | 774 | execution to be accessible. |
|
744 | 775 | |
|
745 | 776 | Note: we can not allow the actual FakeModule instances to be deleted, |
|
746 | 777 | because of how Python tears down modules (it hard-sets all their |
|
747 | 778 | references to None without regard for reference counts). This method |
|
748 | 779 | must therefore make a *copy* of the given namespace, to allow the |
|
749 | 780 | original module's __dict__ to be cleared and reused. |
|
750 | 781 | |
|
751 | 782 | |
|
752 | 783 | Parameters |
|
753 | 784 | ---------- |
|
754 | 785 | ns : a namespace (a dict, typically) |
|
755 | 786 | |
|
756 | 787 | fname : str |
|
757 | 788 | Filename associated with the namespace. |
|
758 | 789 | |
|
759 | 790 | Examples |
|
760 | 791 | -------- |
|
761 | 792 | |
|
762 | 793 | In [10]: import IPython |
|
763 | 794 | |
|
764 | 795 | In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__) |
|
765 | 796 | |
|
766 | 797 | In [12]: IPython.__file__ in _ip._main_ns_cache |
|
767 | 798 | Out[12]: True |
|
768 | 799 | """ |
|
769 | 800 | self._main_ns_cache[os.path.abspath(fname)] = ns.copy() |
|
770 | 801 | |
|
771 | 802 | def clear_main_mod_cache(self): |
|
772 | 803 | """Clear the cache of main modules. |
|
773 | 804 | |
|
774 | 805 | Mainly for use by utilities like %reset. |
|
775 | 806 | |
|
776 | 807 | Examples |
|
777 | 808 | -------- |
|
778 | 809 | |
|
779 | 810 | In [15]: import IPython |
|
780 | 811 | |
|
781 | 812 | In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__) |
|
782 | 813 | |
|
783 | 814 | In [17]: len(_ip._main_ns_cache) > 0 |
|
784 | 815 | Out[17]: True |
|
785 | 816 | |
|
786 | 817 | In [18]: _ip.clear_main_mod_cache() |
|
787 | 818 | |
|
788 | 819 | In [19]: len(_ip._main_ns_cache) == 0 |
|
789 | 820 | Out[19]: True |
|
790 | 821 | """ |
|
791 | 822 | self._main_ns_cache.clear() |
|
792 | 823 | |
|
793 | 824 | #------------------------------------------------------------------------- |
|
794 | 825 | # Things related to debugging |
|
795 | 826 | #------------------------------------------------------------------------- |
|
796 | 827 | |
|
797 | 828 | def init_pdb(self): |
|
798 | 829 | # Set calling of pdb on exceptions |
|
799 | 830 | # self.call_pdb is a property |
|
800 | 831 | self.call_pdb = self.pdb |
|
801 | 832 | |
|
802 | 833 | def _get_call_pdb(self): |
|
803 | 834 | return self._call_pdb |
|
804 | 835 | |
|
805 | 836 | def _set_call_pdb(self,val): |
|
806 | 837 | |
|
807 | 838 | if val not in (0,1,False,True): |
|
808 | 839 | raise ValueError,'new call_pdb value must be boolean' |
|
809 | 840 | |
|
810 | 841 | # store value in instance |
|
811 | 842 | self._call_pdb = val |
|
812 | 843 | |
|
813 | 844 | # notify the actual exception handlers |
|
814 | 845 | self.InteractiveTB.call_pdb = val |
|
815 | 846 | |
|
816 | 847 | call_pdb = property(_get_call_pdb,_set_call_pdb,None, |
|
817 | 848 | 'Control auto-activation of pdb at exceptions') |
|
818 | 849 | |
|
819 | 850 | def debugger(self,force=False): |
|
820 | 851 | """Call the pydb/pdb debugger. |
|
821 | 852 | |
|
822 | 853 | Keywords: |
|
823 | 854 | |
|
824 | 855 | - force(False): by default, this routine checks the instance call_pdb |
|
825 | 856 | flag and does not actually invoke the debugger if the flag is false. |
|
826 | 857 | The 'force' option forces the debugger to activate even if the flag |
|
827 | 858 | is false. |
|
828 | 859 | """ |
|
829 | 860 | |
|
830 | 861 | if not (force or self.call_pdb): |
|
831 | 862 | return |
|
832 | 863 | |
|
833 | 864 | if not hasattr(sys,'last_traceback'): |
|
834 | 865 | error('No traceback has been produced, nothing to debug.') |
|
835 | 866 | return |
|
836 | 867 | |
|
837 | 868 | # use pydb if available |
|
838 | 869 | if debugger.has_pydb: |
|
839 | 870 | from pydb import pm |
|
840 | 871 | else: |
|
841 | 872 | # fallback to our internal debugger |
|
842 | 873 | pm = lambda : self.InteractiveTB.debugger(force=True) |
|
843 | 874 | |
|
844 | 875 | with self.readline_no_record: |
|
845 | 876 | pm() |
|
846 | 877 | |
|
847 | 878 | #------------------------------------------------------------------------- |
|
848 | 879 | # Things related to IPython's various namespaces |
|
849 | 880 | #------------------------------------------------------------------------- |
|
850 | 881 | |
|
851 | 882 | def init_create_namespaces(self, user_module=None, user_ns=None): |
|
852 | 883 | # Create the namespace where the user will operate. user_ns is |
|
853 | 884 | # normally the only one used, and it is passed to the exec calls as |
|
854 | 885 | # the locals argument. But we do carry a user_global_ns namespace |
|
855 | 886 | # given as the exec 'globals' argument, This is useful in embedding |
|
856 | 887 | # situations where the ipython shell opens in a context where the |
|
857 | 888 | # distinction between locals and globals is meaningful. For |
|
858 | 889 | # non-embedded contexts, it is just the same object as the user_ns dict. |
|
859 | 890 | |
|
860 | 891 | # FIXME. For some strange reason, __builtins__ is showing up at user |
|
861 | 892 | # level as a dict instead of a module. This is a manual fix, but I |
|
862 | 893 | # should really track down where the problem is coming from. Alex |
|
863 | 894 | # Schmolck reported this problem first. |
|
864 | 895 | |
|
865 | 896 | # A useful post by Alex Martelli on this topic: |
|
866 | 897 | # Re: inconsistent value from __builtins__ |
|
867 | 898 | # Von: Alex Martelli <aleaxit@yahoo.com> |
|
868 | 899 | # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends |
|
869 | 900 | # Gruppen: comp.lang.python |
|
870 | 901 | |
|
871 | 902 | # Michael Hohn <hohn@hooknose.lbl.gov> wrote: |
|
872 | 903 | # > >>> print type(builtin_check.get_global_binding('__builtins__')) |
|
873 | 904 | # > <type 'dict'> |
|
874 | 905 | # > >>> print type(__builtins__) |
|
875 | 906 | # > <type 'module'> |
|
876 | 907 | # > Is this difference in return value intentional? |
|
877 | 908 | |
|
878 | 909 | # Well, it's documented that '__builtins__' can be either a dictionary |
|
879 | 910 | # or a module, and it's been that way for a long time. Whether it's |
|
880 | 911 | # intentional (or sensible), I don't know. In any case, the idea is |
|
881 | 912 | # that if you need to access the built-in namespace directly, you |
|
882 | 913 | # should start with "import __builtin__" (note, no 's') which will |
|
883 | 914 | # definitely give you a module. Yeah, it's somewhat confusing:-(. |
|
884 | 915 | |
|
885 | 916 | # These routines return a properly built module and dict as needed by |
|
886 | 917 | # the rest of the code, and can also be used by extension writers to |
|
887 | 918 | # generate properly initialized namespaces. |
|
888 | 919 | self.user_module, self.user_ns = self.prepare_user_module(user_module, user_ns) |
|
889 | 920 | |
|
890 | 921 | # A record of hidden variables we have added to the user namespace, so |
|
891 | 922 | # we can list later only variables defined in actual interactive use. |
|
892 | 923 | self.user_ns_hidden = set() |
|
893 | 924 | |
|
894 | 925 | # Now that FakeModule produces a real module, we've run into a nasty |
|
895 | 926 | # problem: after script execution (via %run), the module where the user |
|
896 | 927 | # code ran is deleted. Now that this object is a true module (needed |
|
897 | 928 | # so docetst and other tools work correctly), the Python module |
|
898 | 929 | # teardown mechanism runs over it, and sets to None every variable |
|
899 | 930 | # present in that module. Top-level references to objects from the |
|
900 | 931 | # script survive, because the user_ns is updated with them. However, |
|
901 | 932 | # calling functions defined in the script that use other things from |
|
902 | 933 | # the script will fail, because the function's closure had references |
|
903 | 934 | # to the original objects, which are now all None. So we must protect |
|
904 | 935 | # these modules from deletion by keeping a cache. |
|
905 | 936 | # |
|
906 | 937 | # To avoid keeping stale modules around (we only need the one from the |
|
907 | 938 | # last run), we use a dict keyed with the full path to the script, so |
|
908 | 939 | # only the last version of the module is held in the cache. Note, |
|
909 | 940 | # however, that we must cache the module *namespace contents* (their |
|
910 | 941 | # __dict__). Because if we try to cache the actual modules, old ones |
|
911 | 942 | # (uncached) could be destroyed while still holding references (such as |
|
912 | 943 | # those held by GUI objects that tend to be long-lived)> |
|
913 | 944 | # |
|
914 | 945 | # The %reset command will flush this cache. See the cache_main_mod() |
|
915 | 946 | # and clear_main_mod_cache() methods for details on use. |
|
916 | 947 | |
|
917 | 948 | # This is the cache used for 'main' namespaces |
|
918 | 949 | self._main_ns_cache = {} |
|
919 | 950 | # And this is the single instance of FakeModule whose __dict__ we keep |
|
920 | 951 | # copying and clearing for reuse on each %run |
|
921 | 952 | self._user_main_module = FakeModule() |
|
922 | 953 | |
|
923 | 954 | # A table holding all the namespaces IPython deals with, so that |
|
924 | 955 | # introspection facilities can search easily. |
|
925 | 956 | self.ns_table = {'user_global':self.user_module.__dict__, |
|
926 | 957 | 'user_local':self.user_ns, |
|
927 | 958 | 'builtin':builtin_mod.__dict__ |
|
928 | 959 | } |
|
929 | 960 | |
|
930 | 961 | @property |
|
931 | 962 | def user_global_ns(self): |
|
932 | 963 | return self.user_module.__dict__ |
|
933 | 964 | |
|
934 | 965 | def prepare_user_module(self, user_module=None, user_ns=None): |
|
935 | 966 | """Prepare the module and namespace in which user code will be run. |
|
936 | 967 | |
|
937 | 968 | When IPython is started normally, both parameters are None: a new module |
|
938 | 969 | is created automatically, and its __dict__ used as the namespace. |
|
939 | 970 | |
|
940 | 971 | If only user_module is provided, its __dict__ is used as the namespace. |
|
941 | 972 | If only user_ns is provided, a dummy module is created, and user_ns |
|
942 | 973 | becomes the global namespace. If both are provided (as they may be |
|
943 | 974 | when embedding), user_ns is the local namespace, and user_module |
|
944 | 975 | provides the global namespace. |
|
945 | 976 | |
|
946 | 977 | Parameters |
|
947 | 978 | ---------- |
|
948 | 979 | user_module : module, optional |
|
949 | 980 | The current user module in which IPython is being run. If None, |
|
950 | 981 | a clean module will be created. |
|
951 | 982 | user_ns : dict, optional |
|
952 | 983 | A namespace in which to run interactive commands. |
|
953 | 984 | |
|
954 | 985 | Returns |
|
955 | 986 | ------- |
|
956 | 987 | A tuple of user_module and user_ns, each properly initialised. |
|
957 | 988 | """ |
|
958 | 989 | if user_module is None and user_ns is not None: |
|
959 | 990 | user_ns.setdefault("__name__", "__main__") |
|
960 | 991 | class DummyMod(object): |
|
961 | 992 | "A dummy module used for IPython's interactive namespace." |
|
962 | 993 | pass |
|
963 | 994 | user_module = DummyMod() |
|
964 | 995 | user_module.__dict__ = user_ns |
|
965 | 996 | |
|
966 | 997 | if user_module is None: |
|
967 | 998 | user_module = types.ModuleType("__main__", |
|
968 | 999 | doc="Automatically created module for IPython interactive environment") |
|
969 | 1000 | |
|
970 | 1001 | # We must ensure that __builtin__ (without the final 's') is always |
|
971 | 1002 | # available and pointing to the __builtin__ *module*. For more details: |
|
972 | 1003 | # http://mail.python.org/pipermail/python-dev/2001-April/014068.html |
|
973 | 1004 | user_module.__dict__.setdefault('__builtin__', builtin_mod) |
|
974 | 1005 | user_module.__dict__.setdefault('__builtins__', builtin_mod) |
|
975 | 1006 | |
|
976 | 1007 | if user_ns is None: |
|
977 | 1008 | user_ns = user_module.__dict__ |
|
978 | 1009 | |
|
979 | 1010 | return user_module, user_ns |
|
980 | 1011 | |
|
981 | 1012 | def init_sys_modules(self): |
|
982 | 1013 | # We need to insert into sys.modules something that looks like a |
|
983 | 1014 | # module but which accesses the IPython namespace, for shelve and |
|
984 | 1015 | # pickle to work interactively. Normally they rely on getting |
|
985 | 1016 | # everything out of __main__, but for embedding purposes each IPython |
|
986 | 1017 | # instance has its own private namespace, so we can't go shoving |
|
987 | 1018 | # everything into __main__. |
|
988 | 1019 | |
|
989 | 1020 | # note, however, that we should only do this for non-embedded |
|
990 | 1021 | # ipythons, which really mimic the __main__.__dict__ with their own |
|
991 | 1022 | # namespace. Embedded instances, on the other hand, should not do |
|
992 | 1023 | # this because they need to manage the user local/global namespaces |
|
993 | 1024 | # only, but they live within a 'normal' __main__ (meaning, they |
|
994 | 1025 | # shouldn't overtake the execution environment of the script they're |
|
995 | 1026 | # embedded in). |
|
996 | 1027 | |
|
997 | 1028 | # This is overridden in the InteractiveShellEmbed subclass to a no-op. |
|
998 | 1029 | main_name = self.user_module.__name__ |
|
999 | 1030 | sys.modules[main_name] = self.user_module |
|
1000 | 1031 | |
|
1001 | 1032 | def init_user_ns(self): |
|
1002 | 1033 | """Initialize all user-visible namespaces to their minimum defaults. |
|
1003 | 1034 | |
|
1004 | 1035 | Certain history lists are also initialized here, as they effectively |
|
1005 | 1036 | act as user namespaces. |
|
1006 | 1037 | |
|
1007 | 1038 | Notes |
|
1008 | 1039 | ----- |
|
1009 | 1040 | All data structures here are only filled in, they are NOT reset by this |
|
1010 | 1041 | method. If they were not empty before, data will simply be added to |
|
1011 | 1042 | therm. |
|
1012 | 1043 | """ |
|
1013 | 1044 | # This function works in two parts: first we put a few things in |
|
1014 | 1045 | # user_ns, and we sync that contents into user_ns_hidden so that these |
|
1015 | 1046 | # initial variables aren't shown by %who. After the sync, we add the |
|
1016 | 1047 | # rest of what we *do* want the user to see with %who even on a new |
|
1017 | 1048 | # session (probably nothing, so theye really only see their own stuff) |
|
1018 | 1049 | |
|
1019 | 1050 | # The user dict must *always* have a __builtin__ reference to the |
|
1020 | 1051 | # Python standard __builtin__ namespace, which must be imported. |
|
1021 | 1052 | # This is so that certain operations in prompt evaluation can be |
|
1022 | 1053 | # reliably executed with builtins. Note that we can NOT use |
|
1023 | 1054 | # __builtins__ (note the 's'), because that can either be a dict or a |
|
1024 | 1055 | # module, and can even mutate at runtime, depending on the context |
|
1025 | 1056 | # (Python makes no guarantees on it). In contrast, __builtin__ is |
|
1026 | 1057 | # always a module object, though it must be explicitly imported. |
|
1027 | 1058 | |
|
1028 | 1059 | # For more details: |
|
1029 | 1060 | # http://mail.python.org/pipermail/python-dev/2001-April/014068.html |
|
1030 | 1061 | ns = dict() |
|
1031 | 1062 | |
|
1032 | 1063 | # Put 'help' in the user namespace |
|
1033 | 1064 | try: |
|
1034 | 1065 | from site import _Helper |
|
1035 | 1066 | ns['help'] = _Helper() |
|
1036 | 1067 | except ImportError: |
|
1037 | 1068 | warn('help() not available - check site.py') |
|
1038 | 1069 | |
|
1039 | 1070 | # make global variables for user access to the histories |
|
1040 | 1071 | ns['_ih'] = self.history_manager.input_hist_parsed |
|
1041 | 1072 | ns['_oh'] = self.history_manager.output_hist |
|
1042 | 1073 | ns['_dh'] = self.history_manager.dir_hist |
|
1043 | 1074 | |
|
1044 | 1075 | ns['_sh'] = shadowns |
|
1045 | 1076 | |
|
1046 | 1077 | # user aliases to input and output histories. These shouldn't show up |
|
1047 | 1078 | # in %who, as they can have very large reprs. |
|
1048 | 1079 | ns['In'] = self.history_manager.input_hist_parsed |
|
1049 | 1080 | ns['Out'] = self.history_manager.output_hist |
|
1050 | 1081 | |
|
1051 | 1082 | # Store myself as the public api!!! |
|
1052 | 1083 | ns['get_ipython'] = self.get_ipython |
|
1053 | 1084 | |
|
1054 | 1085 | ns['exit'] = self.exiter |
|
1055 | 1086 | ns['quit'] = self.exiter |
|
1056 | 1087 | |
|
1057 | 1088 | # Sync what we've added so far to user_ns_hidden so these aren't seen |
|
1058 | 1089 | # by %who |
|
1059 | 1090 | self.user_ns_hidden.update(ns) |
|
1060 | 1091 | |
|
1061 | 1092 | # Anything put into ns now would show up in %who. Think twice before |
|
1062 | 1093 | # putting anything here, as we really want %who to show the user their |
|
1063 | 1094 | # stuff, not our variables. |
|
1064 | 1095 | |
|
1065 | 1096 | # Finally, update the real user's namespace |
|
1066 | 1097 | self.user_ns.update(ns) |
|
1067 | 1098 | |
|
1068 | 1099 | @property |
|
1069 | 1100 | def all_ns_refs(self): |
|
1070 | 1101 | """Get a list of references to all the namespace dictionaries in which |
|
1071 | 1102 | IPython might store a user-created object. |
|
1072 | 1103 | |
|
1073 | 1104 | Note that this does not include the displayhook, which also caches |
|
1074 | 1105 | objects from the output.""" |
|
1075 | 1106 | return [self.user_ns, self.user_global_ns, |
|
1076 | 1107 | self._user_main_module.__dict__] + self._main_ns_cache.values() |
|
1077 | 1108 | |
|
1078 | 1109 | def reset(self, new_session=True): |
|
1079 | 1110 | """Clear all internal namespaces, and attempt to release references to |
|
1080 | 1111 | user objects. |
|
1081 | 1112 | |
|
1082 | 1113 | If new_session is True, a new history session will be opened. |
|
1083 | 1114 | """ |
|
1084 | 1115 | # Clear histories |
|
1085 | 1116 | self.history_manager.reset(new_session) |
|
1086 | 1117 | # Reset counter used to index all histories |
|
1087 | 1118 | if new_session: |
|
1088 | 1119 | self.execution_count = 1 |
|
1089 | 1120 | |
|
1090 | 1121 | # Flush cached output items |
|
1091 | 1122 | if self.displayhook.do_full_cache: |
|
1092 | 1123 | self.displayhook.flush() |
|
1093 | 1124 | |
|
1094 | 1125 | # The main execution namespaces must be cleared very carefully, |
|
1095 | 1126 | # skipping the deletion of the builtin-related keys, because doing so |
|
1096 | 1127 | # would cause errors in many object's __del__ methods. |
|
1097 | 1128 | if self.user_ns is not self.user_global_ns: |
|
1098 | 1129 | self.user_ns.clear() |
|
1099 | 1130 | ns = self.user_global_ns |
|
1100 | 1131 | drop_keys = set(ns.keys()) |
|
1101 | 1132 | drop_keys.discard('__builtin__') |
|
1102 | 1133 | drop_keys.discard('__builtins__') |
|
1103 | 1134 | drop_keys.discard('__name__') |
|
1104 | 1135 | for k in drop_keys: |
|
1105 | 1136 | del ns[k] |
|
1106 | 1137 | |
|
1107 | 1138 | self.user_ns_hidden.clear() |
|
1108 | 1139 | |
|
1109 | 1140 | # Restore the user namespaces to minimal usability |
|
1110 | 1141 | self.init_user_ns() |
|
1111 | 1142 | |
|
1112 | 1143 | # Restore the default and user aliases |
|
1113 | 1144 | self.alias_manager.clear_aliases() |
|
1114 | 1145 | self.alias_manager.init_aliases() |
|
1115 | 1146 | |
|
1116 | 1147 | # Flush the private list of module references kept for script |
|
1117 | 1148 | # execution protection |
|
1118 | 1149 | self.clear_main_mod_cache() |
|
1119 | 1150 | |
|
1120 | 1151 | # Clear out the namespace from the last %run |
|
1121 | 1152 | self.new_main_mod() |
|
1122 | 1153 | |
|
1123 | 1154 | def del_var(self, varname, by_name=False): |
|
1124 | 1155 | """Delete a variable from the various namespaces, so that, as |
|
1125 | 1156 | far as possible, we're not keeping any hidden references to it. |
|
1126 | 1157 | |
|
1127 | 1158 | Parameters |
|
1128 | 1159 | ---------- |
|
1129 | 1160 | varname : str |
|
1130 | 1161 | The name of the variable to delete. |
|
1131 | 1162 | by_name : bool |
|
1132 | 1163 | If True, delete variables with the given name in each |
|
1133 | 1164 | namespace. If False (default), find the variable in the user |
|
1134 | 1165 | namespace, and delete references to it. |
|
1135 | 1166 | """ |
|
1136 | 1167 | if varname in ('__builtin__', '__builtins__'): |
|
1137 | 1168 | raise ValueError("Refusing to delete %s" % varname) |
|
1138 | 1169 | |
|
1139 | 1170 | ns_refs = self.all_ns_refs |
|
1140 | 1171 | |
|
1141 | 1172 | if by_name: # Delete by name |
|
1142 | 1173 | for ns in ns_refs: |
|
1143 | 1174 | try: |
|
1144 | 1175 | del ns[varname] |
|
1145 | 1176 | except KeyError: |
|
1146 | 1177 | pass |
|
1147 | 1178 | else: # Delete by object |
|
1148 | 1179 | try: |
|
1149 | 1180 | obj = self.user_ns[varname] |
|
1150 | 1181 | except KeyError: |
|
1151 | 1182 | raise NameError("name '%s' is not defined" % varname) |
|
1152 | 1183 | # Also check in output history |
|
1153 | 1184 | ns_refs.append(self.history_manager.output_hist) |
|
1154 | 1185 | for ns in ns_refs: |
|
1155 | 1186 | to_delete = [n for n, o in ns.iteritems() if o is obj] |
|
1156 | 1187 | for name in to_delete: |
|
1157 | 1188 | del ns[name] |
|
1158 | 1189 | |
|
1159 | 1190 | # displayhook keeps extra references, but not in a dictionary |
|
1160 | 1191 | for name in ('_', '__', '___'): |
|
1161 | 1192 | if getattr(self.displayhook, name) is obj: |
|
1162 | 1193 | setattr(self.displayhook, name, None) |
|
1163 | 1194 | |
|
1164 | 1195 | def reset_selective(self, regex=None): |
|
1165 | 1196 | """Clear selective variables from internal namespaces based on a |
|
1166 | 1197 | specified regular expression. |
|
1167 | 1198 | |
|
1168 | 1199 | Parameters |
|
1169 | 1200 | ---------- |
|
1170 | 1201 | regex : string or compiled pattern, optional |
|
1171 | 1202 | A regular expression pattern that will be used in searching |
|
1172 | 1203 | variable names in the users namespaces. |
|
1173 | 1204 | """ |
|
1174 | 1205 | if regex is not None: |
|
1175 | 1206 | try: |
|
1176 | 1207 | m = re.compile(regex) |
|
1177 | 1208 | except TypeError: |
|
1178 | 1209 | raise TypeError('regex must be a string or compiled pattern') |
|
1179 | 1210 | # Search for keys in each namespace that match the given regex |
|
1180 | 1211 | # If a match is found, delete the key/value pair. |
|
1181 | 1212 | for ns in self.all_ns_refs: |
|
1182 | 1213 | for var in ns: |
|
1183 | 1214 | if m.search(var): |
|
1184 | 1215 | del ns[var] |
|
1185 | 1216 | |
|
1186 | 1217 | def push(self, variables, interactive=True): |
|
1187 | 1218 | """Inject a group of variables into the IPython user namespace. |
|
1188 | 1219 | |
|
1189 | 1220 | Parameters |
|
1190 | 1221 | ---------- |
|
1191 | 1222 | variables : dict, str or list/tuple of str |
|
1192 | 1223 | The variables to inject into the user's namespace. If a dict, a |
|
1193 | 1224 | simple update is done. If a str, the string is assumed to have |
|
1194 | 1225 | variable names separated by spaces. A list/tuple of str can also |
|
1195 | 1226 | be used to give the variable names. If just the variable names are |
|
1196 | 1227 | give (list/tuple/str) then the variable values looked up in the |
|
1197 | 1228 | callers frame. |
|
1198 | 1229 | interactive : bool |
|
1199 | 1230 | If True (default), the variables will be listed with the ``who`` |
|
1200 | 1231 | magic. |
|
1201 | 1232 | """ |
|
1202 | 1233 | vdict = None |
|
1203 | 1234 | |
|
1204 | 1235 | # We need a dict of name/value pairs to do namespace updates. |
|
1205 | 1236 | if isinstance(variables, dict): |
|
1206 | 1237 | vdict = variables |
|
1207 | 1238 | elif isinstance(variables, (basestring, list, tuple)): |
|
1208 | 1239 | if isinstance(variables, basestring): |
|
1209 | 1240 | vlist = variables.split() |
|
1210 | 1241 | else: |
|
1211 | 1242 | vlist = variables |
|
1212 | 1243 | vdict = {} |
|
1213 | 1244 | cf = sys._getframe(1) |
|
1214 | 1245 | for name in vlist: |
|
1215 | 1246 | try: |
|
1216 | 1247 | vdict[name] = eval(name, cf.f_globals, cf.f_locals) |
|
1217 | 1248 | except: |
|
1218 | 1249 | print ('Could not get variable %s from %s' % |
|
1219 | 1250 | (name,cf.f_code.co_name)) |
|
1220 | 1251 | else: |
|
1221 | 1252 | raise ValueError('variables must be a dict/str/list/tuple') |
|
1222 | 1253 | |
|
1223 | 1254 | # Propagate variables to user namespace |
|
1224 | 1255 | self.user_ns.update(vdict) |
|
1225 | 1256 | |
|
1226 | 1257 | # And configure interactive visibility |
|
1227 | 1258 | user_ns_hidden = self.user_ns_hidden |
|
1228 | 1259 | if interactive: |
|
1229 | 1260 | user_ns_hidden.difference_update(vdict) |
|
1230 | 1261 | else: |
|
1231 | 1262 | user_ns_hidden.update(vdict) |
|
1232 | 1263 | |
|
1233 | 1264 | def drop_by_id(self, variables): |
|
1234 | 1265 | """Remove a dict of variables from the user namespace, if they are the |
|
1235 | 1266 | same as the values in the dictionary. |
|
1236 | 1267 | |
|
1237 | 1268 | This is intended for use by extensions: variables that they've added can |
|
1238 | 1269 | be taken back out if they are unloaded, without removing any that the |
|
1239 | 1270 | user has overwritten. |
|
1240 | 1271 | |
|
1241 | 1272 | Parameters |
|
1242 | 1273 | ---------- |
|
1243 | 1274 | variables : dict |
|
1244 | 1275 | A dictionary mapping object names (as strings) to the objects. |
|
1245 | 1276 | """ |
|
1246 | 1277 | for name, obj in variables.iteritems(): |
|
1247 | 1278 | if name in self.user_ns and self.user_ns[name] is obj: |
|
1248 | 1279 | del self.user_ns[name] |
|
1249 | 1280 | self.user_ns_hidden.discard(name) |
|
1250 | 1281 | |
|
1251 | 1282 | #------------------------------------------------------------------------- |
|
1252 | 1283 | # Things related to object introspection |
|
1253 | 1284 | #------------------------------------------------------------------------- |
|
1254 | 1285 | |
|
1255 | 1286 | def _ofind(self, oname, namespaces=None): |
|
1256 | 1287 | """Find an object in the available namespaces. |
|
1257 | 1288 | |
|
1258 | 1289 | self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic |
|
1259 | 1290 | |
|
1260 | 1291 | Has special code to detect magic functions. |
|
1261 | 1292 | """ |
|
1262 | 1293 | oname = oname.strip() |
|
1263 | 1294 | #print '1- oname: <%r>' % oname # dbg |
|
1264 | 1295 | if not py3compat.isidentifier(oname.lstrip(ESC_MAGIC), dotted=True): |
|
1265 | 1296 | return dict(found=False) |
|
1266 | 1297 | |
|
1267 | 1298 | alias_ns = None |
|
1268 | 1299 | if namespaces is None: |
|
1269 | 1300 | # Namespaces to search in: |
|
1270 | 1301 | # Put them in a list. The order is important so that we |
|
1271 | 1302 | # find things in the same order that Python finds them. |
|
1272 | 1303 | namespaces = [ ('Interactive', self.user_ns), |
|
1273 | 1304 | ('Interactive (global)', self.user_global_ns), |
|
1274 | 1305 | ('Python builtin', builtin_mod.__dict__), |
|
1275 | 1306 | ('Alias', self.alias_manager.alias_table), |
|
1276 | 1307 | ] |
|
1277 | 1308 | alias_ns = self.alias_manager.alias_table |
|
1278 | 1309 | |
|
1279 | 1310 | # initialize results to 'null' |
|
1280 | 1311 | found = False; obj = None; ospace = None; ds = None; |
|
1281 | 1312 | ismagic = False; isalias = False; parent = None |
|
1282 | 1313 | |
|
1283 | 1314 | # We need to special-case 'print', which as of python2.6 registers as a |
|
1284 | 1315 | # function but should only be treated as one if print_function was |
|
1285 | 1316 | # loaded with a future import. In this case, just bail. |
|
1286 | 1317 | if (oname == 'print' and not py3compat.PY3 and not \ |
|
1287 | 1318 | (self.compile.compiler_flags & __future__.CO_FUTURE_PRINT_FUNCTION)): |
|
1288 | 1319 | return {'found':found, 'obj':obj, 'namespace':ospace, |
|
1289 | 1320 | 'ismagic':ismagic, 'isalias':isalias, 'parent':parent} |
|
1290 | 1321 | |
|
1291 | 1322 | # Look for the given name by splitting it in parts. If the head is |
|
1292 | 1323 | # found, then we look for all the remaining parts as members, and only |
|
1293 | 1324 | # declare success if we can find them all. |
|
1294 | 1325 | oname_parts = oname.split('.') |
|
1295 | 1326 | oname_head, oname_rest = oname_parts[0],oname_parts[1:] |
|
1296 | 1327 | for nsname,ns in namespaces: |
|
1297 | 1328 | try: |
|
1298 | 1329 | obj = ns[oname_head] |
|
1299 | 1330 | except KeyError: |
|
1300 | 1331 | continue |
|
1301 | 1332 | else: |
|
1302 | 1333 | #print 'oname_rest:', oname_rest # dbg |
|
1303 | 1334 | for part in oname_rest: |
|
1304 | 1335 | try: |
|
1305 | 1336 | parent = obj |
|
1306 | 1337 | obj = getattr(obj,part) |
|
1307 | 1338 | except: |
|
1308 | 1339 | # Blanket except b/c some badly implemented objects |
|
1309 | 1340 | # allow __getattr__ to raise exceptions other than |
|
1310 | 1341 | # AttributeError, which then crashes IPython. |
|
1311 | 1342 | break |
|
1312 | 1343 | else: |
|
1313 | 1344 | # If we finish the for loop (no break), we got all members |
|
1314 | 1345 | found = True |
|
1315 | 1346 | ospace = nsname |
|
1316 | 1347 | if ns == alias_ns: |
|
1317 | 1348 | isalias = True |
|
1318 | 1349 | break # namespace loop |
|
1319 | 1350 | |
|
1320 | 1351 | # Try to see if it's magic |
|
1321 | 1352 | if not found: |
|
1322 | 1353 | if oname.startswith(ESC_MAGIC): |
|
1323 | 1354 | oname = oname[1:] |
|
1324 | 1355 | obj = getattr(self,'magic_'+oname,None) |
|
1325 | 1356 | if obj is not None: |
|
1326 | 1357 | found = True |
|
1327 | 1358 | ospace = 'IPython internal' |
|
1328 | 1359 | ismagic = True |
|
1329 | 1360 | |
|
1330 | 1361 | # Last try: special-case some literals like '', [], {}, etc: |
|
1331 | 1362 | if not found and oname_head in ["''",'""','[]','{}','()']: |
|
1332 | 1363 | obj = eval(oname_head) |
|
1333 | 1364 | found = True |
|
1334 | 1365 | ospace = 'Interactive' |
|
1335 | 1366 | |
|
1336 | 1367 | return {'found':found, 'obj':obj, 'namespace':ospace, |
|
1337 | 1368 | 'ismagic':ismagic, 'isalias':isalias, 'parent':parent} |
|
1338 | 1369 | |
|
1339 | 1370 | def _ofind_property(self, oname, info): |
|
1340 | 1371 | """Second part of object finding, to look for property details.""" |
|
1341 | 1372 | if info.found: |
|
1342 | 1373 | # Get the docstring of the class property if it exists. |
|
1343 | 1374 | path = oname.split('.') |
|
1344 | 1375 | root = '.'.join(path[:-1]) |
|
1345 | 1376 | if info.parent is not None: |
|
1346 | 1377 | try: |
|
1347 | 1378 | target = getattr(info.parent, '__class__') |
|
1348 | 1379 | # The object belongs to a class instance. |
|
1349 | 1380 | try: |
|
1350 | 1381 | target = getattr(target, path[-1]) |
|
1351 | 1382 | # The class defines the object. |
|
1352 | 1383 | if isinstance(target, property): |
|
1353 | 1384 | oname = root + '.__class__.' + path[-1] |
|
1354 | 1385 | info = Struct(self._ofind(oname)) |
|
1355 | 1386 | except AttributeError: pass |
|
1356 | 1387 | except AttributeError: pass |
|
1357 | 1388 | |
|
1358 | 1389 | # We return either the new info or the unmodified input if the object |
|
1359 | 1390 | # hadn't been found |
|
1360 | 1391 | return info |
|
1361 | 1392 | |
|
1362 | 1393 | def _object_find(self, oname, namespaces=None): |
|
1363 | 1394 | """Find an object and return a struct with info about it.""" |
|
1364 | 1395 | inf = Struct(self._ofind(oname, namespaces)) |
|
1365 | 1396 | return Struct(self._ofind_property(oname, inf)) |
|
1366 | 1397 | |
|
1367 | 1398 | def _inspect(self, meth, oname, namespaces=None, **kw): |
|
1368 | 1399 | """Generic interface to the inspector system. |
|
1369 | 1400 | |
|
1370 | 1401 | This function is meant to be called by pdef, pdoc & friends.""" |
|
1371 | 1402 | info = self._object_find(oname) |
|
1372 | 1403 | if info.found: |
|
1373 | 1404 | pmethod = getattr(self.inspector, meth) |
|
1374 | 1405 | formatter = format_screen if info.ismagic else None |
|
1375 | 1406 | if meth == 'pdoc': |
|
1376 | 1407 | pmethod(info.obj, oname, formatter) |
|
1377 | 1408 | elif meth == 'pinfo': |
|
1378 | 1409 | pmethod(info.obj, oname, formatter, info, **kw) |
|
1379 | 1410 | else: |
|
1380 | 1411 | pmethod(info.obj, oname) |
|
1381 | 1412 | else: |
|
1382 | 1413 | print 'Object `%s` not found.' % oname |
|
1383 | 1414 | return 'not found' # so callers can take other action |
|
1384 | 1415 | |
|
1385 | 1416 | def object_inspect(self, oname): |
|
1386 | 1417 | with self.builtin_trap: |
|
1387 | 1418 | info = self._object_find(oname) |
|
1388 | 1419 | if info.found: |
|
1389 | 1420 | return self.inspector.info(info.obj, oname, info=info) |
|
1390 | 1421 | else: |
|
1391 | 1422 | return oinspect.object_info(name=oname, found=False) |
|
1392 | 1423 | |
|
1393 | 1424 | #------------------------------------------------------------------------- |
|
1394 | 1425 | # Things related to history management |
|
1395 | 1426 | #------------------------------------------------------------------------- |
|
1396 | 1427 | |
|
1397 | 1428 | def init_history(self): |
|
1398 | 1429 | """Sets up the command history, and starts regular autosaves.""" |
|
1399 | 1430 | self.history_manager = HistoryManager(shell=self, config=self.config) |
|
1400 | 1431 | self.configurables.append(self.history_manager) |
|
1401 | 1432 | |
|
1402 | 1433 | #------------------------------------------------------------------------- |
|
1403 | 1434 | # Things related to exception handling and tracebacks (not debugging) |
|
1404 | 1435 | #------------------------------------------------------------------------- |
|
1405 | 1436 | |
|
1406 | 1437 | def init_traceback_handlers(self, custom_exceptions): |
|
1407 | 1438 | # Syntax error handler. |
|
1408 | 1439 | self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor') |
|
1409 | 1440 | |
|
1410 | 1441 | # The interactive one is initialized with an offset, meaning we always |
|
1411 | 1442 | # want to remove the topmost item in the traceback, which is our own |
|
1412 | 1443 | # internal code. Valid modes: ['Plain','Context','Verbose'] |
|
1413 | 1444 | self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain', |
|
1414 | 1445 | color_scheme='NoColor', |
|
1415 | 1446 | tb_offset = 1, |
|
1416 | 1447 | check_cache=self.compile.check_cache) |
|
1417 | 1448 | |
|
1418 | 1449 | # The instance will store a pointer to the system-wide exception hook, |
|
1419 | 1450 | # so that runtime code (such as magics) can access it. This is because |
|
1420 | 1451 | # during the read-eval loop, it may get temporarily overwritten. |
|
1421 | 1452 | self.sys_excepthook = sys.excepthook |
|
1422 | 1453 | |
|
1423 | 1454 | # and add any custom exception handlers the user may have specified |
|
1424 | 1455 | self.set_custom_exc(*custom_exceptions) |
|
1425 | 1456 | |
|
1426 | 1457 | # Set the exception mode |
|
1427 | 1458 | self.InteractiveTB.set_mode(mode=self.xmode) |
|
1428 | 1459 | |
|
1429 | 1460 | def set_custom_exc(self, exc_tuple, handler): |
|
1430 | 1461 | """set_custom_exc(exc_tuple,handler) |
|
1431 | 1462 | |
|
1432 | 1463 | Set a custom exception handler, which will be called if any of the |
|
1433 | 1464 | exceptions in exc_tuple occur in the mainloop (specifically, in the |
|
1434 | 1465 | run_code() method). |
|
1435 | 1466 | |
|
1436 | 1467 | Parameters |
|
1437 | 1468 | ---------- |
|
1438 | 1469 | |
|
1439 | 1470 | exc_tuple : tuple of exception classes |
|
1440 | 1471 | A *tuple* of exception classes, for which to call the defined |
|
1441 | 1472 | handler. It is very important that you use a tuple, and NOT A |
|
1442 | 1473 | LIST here, because of the way Python's except statement works. If |
|
1443 | 1474 | you only want to trap a single exception, use a singleton tuple:: |
|
1444 | 1475 | |
|
1445 | 1476 | exc_tuple == (MyCustomException,) |
|
1446 | 1477 | |
|
1447 | 1478 | handler : callable |
|
1448 | 1479 | handler must have the following signature:: |
|
1449 | 1480 | |
|
1450 | 1481 | def my_handler(self, etype, value, tb, tb_offset=None): |
|
1451 | 1482 | ... |
|
1452 | 1483 | return structured_traceback |
|
1453 | 1484 | |
|
1454 | 1485 | Your handler must return a structured traceback (a list of strings), |
|
1455 | 1486 | or None. |
|
1456 | 1487 | |
|
1457 | 1488 | This will be made into an instance method (via types.MethodType) |
|
1458 | 1489 | of IPython itself, and it will be called if any of the exceptions |
|
1459 | 1490 | listed in the exc_tuple are caught. If the handler is None, an |
|
1460 | 1491 | internal basic one is used, which just prints basic info. |
|
1461 | 1492 | |
|
1462 | 1493 | To protect IPython from crashes, if your handler ever raises an |
|
1463 | 1494 | exception or returns an invalid result, it will be immediately |
|
1464 | 1495 | disabled. |
|
1465 | 1496 | |
|
1466 | 1497 | WARNING: by putting in your own exception handler into IPython's main |
|
1467 | 1498 | execution loop, you run a very good chance of nasty crashes. This |
|
1468 | 1499 | facility should only be used if you really know what you are doing.""" |
|
1469 | 1500 | |
|
1470 | 1501 | assert type(exc_tuple)==type(()) , \ |
|
1471 | 1502 | "The custom exceptions must be given AS A TUPLE." |
|
1472 | 1503 | |
|
1473 | 1504 | def dummy_handler(self,etype,value,tb,tb_offset=None): |
|
1474 | 1505 | print '*** Simple custom exception handler ***' |
|
1475 | 1506 | print 'Exception type :',etype |
|
1476 | 1507 | print 'Exception value:',value |
|
1477 | 1508 | print 'Traceback :',tb |
|
1478 | 1509 | #print 'Source code :','\n'.join(self.buffer) |
|
1479 | 1510 | |
|
1480 | 1511 | def validate_stb(stb): |
|
1481 | 1512 | """validate structured traceback return type |
|
1482 | 1513 | |
|
1483 | 1514 | return type of CustomTB *should* be a list of strings, but allow |
|
1484 | 1515 | single strings or None, which are harmless. |
|
1485 | 1516 | |
|
1486 | 1517 | This function will *always* return a list of strings, |
|
1487 | 1518 | and will raise a TypeError if stb is inappropriate. |
|
1488 | 1519 | """ |
|
1489 | 1520 | msg = "CustomTB must return list of strings, not %r" % stb |
|
1490 | 1521 | if stb is None: |
|
1491 | 1522 | return [] |
|
1492 | 1523 | elif isinstance(stb, basestring): |
|
1493 | 1524 | return [stb] |
|
1494 | 1525 | elif not isinstance(stb, list): |
|
1495 | 1526 | raise TypeError(msg) |
|
1496 | 1527 | # it's a list |
|
1497 | 1528 | for line in stb: |
|
1498 | 1529 | # check every element |
|
1499 | 1530 | if not isinstance(line, basestring): |
|
1500 | 1531 | raise TypeError(msg) |
|
1501 | 1532 | return stb |
|
1502 | 1533 | |
|
1503 | 1534 | if handler is None: |
|
1504 | 1535 | wrapped = dummy_handler |
|
1505 | 1536 | else: |
|
1506 | 1537 | def wrapped(self,etype,value,tb,tb_offset=None): |
|
1507 | 1538 | """wrap CustomTB handler, to protect IPython from user code |
|
1508 | 1539 | |
|
1509 | 1540 | This makes it harder (but not impossible) for custom exception |
|
1510 | 1541 | handlers to crash IPython. |
|
1511 | 1542 | """ |
|
1512 | 1543 | try: |
|
1513 | 1544 | stb = handler(self,etype,value,tb,tb_offset=tb_offset) |
|
1514 | 1545 | return validate_stb(stb) |
|
1515 | 1546 | except: |
|
1516 | 1547 | # clear custom handler immediately |
|
1517 | 1548 | self.set_custom_exc((), None) |
|
1518 | 1549 | print >> io.stderr, "Custom TB Handler failed, unregistering" |
|
1519 | 1550 | # show the exception in handler first |
|
1520 | 1551 | stb = self.InteractiveTB.structured_traceback(*sys.exc_info()) |
|
1521 | 1552 | print >> io.stdout, self.InteractiveTB.stb2text(stb) |
|
1522 | 1553 | print >> io.stdout, "The original exception:" |
|
1523 | 1554 | stb = self.InteractiveTB.structured_traceback( |
|
1524 | 1555 | (etype,value,tb), tb_offset=tb_offset |
|
1525 | 1556 | ) |
|
1526 | 1557 | return stb |
|
1527 | 1558 | |
|
1528 | 1559 | self.CustomTB = types.MethodType(wrapped,self) |
|
1529 | 1560 | self.custom_exceptions = exc_tuple |
|
1530 | 1561 | |
|
1531 | 1562 | def excepthook(self, etype, value, tb): |
|
1532 | 1563 | """One more defense for GUI apps that call sys.excepthook. |
|
1533 | 1564 | |
|
1534 | 1565 | GUI frameworks like wxPython trap exceptions and call |
|
1535 | 1566 | sys.excepthook themselves. I guess this is a feature that |
|
1536 | 1567 | enables them to keep running after exceptions that would |
|
1537 | 1568 | otherwise kill their mainloop. This is a bother for IPython |
|
1538 | 1569 | which excepts to catch all of the program exceptions with a try: |
|
1539 | 1570 | except: statement. |
|
1540 | 1571 | |
|
1541 | 1572 | Normally, IPython sets sys.excepthook to a CrashHandler instance, so if |
|
1542 | 1573 | any app directly invokes sys.excepthook, it will look to the user like |
|
1543 | 1574 | IPython crashed. In order to work around this, we can disable the |
|
1544 | 1575 | CrashHandler and replace it with this excepthook instead, which prints a |
|
1545 | 1576 | regular traceback using our InteractiveTB. In this fashion, apps which |
|
1546 | 1577 | call sys.excepthook will generate a regular-looking exception from |
|
1547 | 1578 | IPython, and the CrashHandler will only be triggered by real IPython |
|
1548 | 1579 | crashes. |
|
1549 | 1580 | |
|
1550 | 1581 | This hook should be used sparingly, only in places which are not likely |
|
1551 | 1582 | to be true IPython errors. |
|
1552 | 1583 | """ |
|
1553 | 1584 | self.showtraceback((etype,value,tb),tb_offset=0) |
|
1554 | 1585 | |
|
1555 | 1586 | def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None, |
|
1556 | 1587 | exception_only=False): |
|
1557 | 1588 | """Display the exception that just occurred. |
|
1558 | 1589 | |
|
1559 | 1590 | If nothing is known about the exception, this is the method which |
|
1560 | 1591 | should be used throughout the code for presenting user tracebacks, |
|
1561 | 1592 | rather than directly invoking the InteractiveTB object. |
|
1562 | 1593 | |
|
1563 | 1594 | A specific showsyntaxerror() also exists, but this method can take |
|
1564 | 1595 | care of calling it if needed, so unless you are explicitly catching a |
|
1565 | 1596 | SyntaxError exception, don't try to analyze the stack manually and |
|
1566 | 1597 | simply call this method.""" |
|
1567 | 1598 | |
|
1568 | 1599 | try: |
|
1569 | 1600 | if exc_tuple is None: |
|
1570 | 1601 | etype, value, tb = sys.exc_info() |
|
1571 | 1602 | else: |
|
1572 | 1603 | etype, value, tb = exc_tuple |
|
1573 | 1604 | |
|
1574 | 1605 | if etype is None: |
|
1575 | 1606 | if hasattr(sys, 'last_type'): |
|
1576 | 1607 | etype, value, tb = sys.last_type, sys.last_value, \ |
|
1577 | 1608 | sys.last_traceback |
|
1578 | 1609 | else: |
|
1579 | 1610 | self.write_err('No traceback available to show.\n') |
|
1580 | 1611 | return |
|
1581 | 1612 | |
|
1582 | 1613 | if etype is SyntaxError: |
|
1583 | 1614 | # Though this won't be called by syntax errors in the input |
|
1584 | 1615 | # line, there may be SyntaxError cases with imported code. |
|
1585 | 1616 | self.showsyntaxerror(filename) |
|
1586 | 1617 | elif etype is UsageError: |
|
1587 | 1618 | self.write_err("UsageError: %s" % value) |
|
1588 | 1619 | else: |
|
1589 | 1620 | # WARNING: these variables are somewhat deprecated and not |
|
1590 | 1621 | # necessarily safe to use in a threaded environment, but tools |
|
1591 | 1622 | # like pdb depend on their existence, so let's set them. If we |
|
1592 | 1623 | # find problems in the field, we'll need to revisit their use. |
|
1593 | 1624 | sys.last_type = etype |
|
1594 | 1625 | sys.last_value = value |
|
1595 | 1626 | sys.last_traceback = tb |
|
1596 | 1627 | if etype in self.custom_exceptions: |
|
1597 | 1628 | stb = self.CustomTB(etype, value, tb, tb_offset) |
|
1598 | 1629 | else: |
|
1599 | 1630 | if exception_only: |
|
1600 | 1631 | stb = ['An exception has occurred, use %tb to see ' |
|
1601 | 1632 | 'the full traceback.\n'] |
|
1602 | 1633 | stb.extend(self.InteractiveTB.get_exception_only(etype, |
|
1603 | 1634 | value)) |
|
1604 | 1635 | else: |
|
1605 | 1636 | stb = self.InteractiveTB.structured_traceback(etype, |
|
1606 | 1637 | value, tb, tb_offset=tb_offset) |
|
1607 | 1638 | |
|
1608 | 1639 | self._showtraceback(etype, value, stb) |
|
1609 | 1640 | if self.call_pdb: |
|
1610 | 1641 | # drop into debugger |
|
1611 | 1642 | self.debugger(force=True) |
|
1612 | 1643 | return |
|
1613 | 1644 | |
|
1614 | 1645 | # Actually show the traceback |
|
1615 | 1646 | self._showtraceback(etype, value, stb) |
|
1616 | 1647 | |
|
1617 | 1648 | except KeyboardInterrupt: |
|
1618 | 1649 | self.write_err("\nKeyboardInterrupt\n") |
|
1619 | 1650 | |
|
1620 | 1651 | def _showtraceback(self, etype, evalue, stb): |
|
1621 | 1652 | """Actually show a traceback. |
|
1622 | 1653 | |
|
1623 | 1654 | Subclasses may override this method to put the traceback on a different |
|
1624 | 1655 | place, like a side channel. |
|
1625 | 1656 | """ |
|
1626 | 1657 | print >> io.stdout, self.InteractiveTB.stb2text(stb) |
|
1627 | 1658 | |
|
1628 | 1659 | def showsyntaxerror(self, filename=None): |
|
1629 | 1660 | """Display the syntax error that just occurred. |
|
1630 | 1661 | |
|
1631 | 1662 | This doesn't display a stack trace because there isn't one. |
|
1632 | 1663 | |
|
1633 | 1664 | If a filename is given, it is stuffed in the exception instead |
|
1634 | 1665 | of what was there before (because Python's parser always uses |
|
1635 | 1666 | "<string>" when reading from a string). |
|
1636 | 1667 | """ |
|
1637 | 1668 | etype, value, last_traceback = sys.exc_info() |
|
1638 | 1669 | |
|
1639 | 1670 | # See note about these variables in showtraceback() above |
|
1640 | 1671 | sys.last_type = etype |
|
1641 | 1672 | sys.last_value = value |
|
1642 | 1673 | sys.last_traceback = last_traceback |
|
1643 | 1674 | |
|
1644 | 1675 | if filename and etype is SyntaxError: |
|
1645 | 1676 | # Work hard to stuff the correct filename in the exception |
|
1646 | 1677 | try: |
|
1647 | 1678 | msg, (dummy_filename, lineno, offset, line) = value |
|
1648 | 1679 | except: |
|
1649 | 1680 | # Not the format we expect; leave it alone |
|
1650 | 1681 | pass |
|
1651 | 1682 | else: |
|
1652 | 1683 | # Stuff in the right filename |
|
1653 | 1684 | try: |
|
1654 | 1685 | # Assume SyntaxError is a class exception |
|
1655 | 1686 | value = SyntaxError(msg, (filename, lineno, offset, line)) |
|
1656 | 1687 | except: |
|
1657 | 1688 | # If that failed, assume SyntaxError is a string |
|
1658 | 1689 | value = msg, (filename, lineno, offset, line) |
|
1659 | 1690 | stb = self.SyntaxTB.structured_traceback(etype, value, []) |
|
1660 | 1691 | self._showtraceback(etype, value, stb) |
|
1661 | 1692 | |
|
1662 | 1693 | # This is overridden in TerminalInteractiveShell to show a message about |
|
1663 | 1694 | # the %paste magic. |
|
1664 | 1695 | def showindentationerror(self): |
|
1665 | 1696 | """Called by run_cell when there's an IndentationError in code entered |
|
1666 | 1697 | at the prompt. |
|
1667 | 1698 | |
|
1668 | 1699 | This is overridden in TerminalInteractiveShell to show a message about |
|
1669 | 1700 | the %paste magic.""" |
|
1670 | 1701 | self.showsyntaxerror() |
|
1671 | 1702 | |
|
1672 | 1703 | #------------------------------------------------------------------------- |
|
1673 | 1704 | # Things related to readline |
|
1674 | 1705 | #------------------------------------------------------------------------- |
|
1675 | 1706 | |
|
1676 | 1707 | def init_readline(self): |
|
1677 | 1708 | """Command history completion/saving/reloading.""" |
|
1678 | 1709 | |
|
1679 | 1710 | if self.readline_use: |
|
1680 | 1711 | import IPython.utils.rlineimpl as readline |
|
1681 | 1712 | |
|
1682 | 1713 | self.rl_next_input = None |
|
1683 | 1714 | self.rl_do_indent = False |
|
1684 | 1715 | |
|
1685 | 1716 | if not self.readline_use or not readline.have_readline: |
|
1686 | 1717 | self.has_readline = False |
|
1687 | 1718 | self.readline = None |
|
1688 | 1719 | # Set a number of methods that depend on readline to be no-op |
|
1689 | 1720 | self.readline_no_record = no_op_context |
|
1690 | 1721 | self.set_readline_completer = no_op |
|
1691 | 1722 | self.set_custom_completer = no_op |
|
1692 | 1723 | self.set_completer_frame = no_op |
|
1693 | 1724 | if self.readline_use: |
|
1694 | 1725 | warn('Readline services not available or not loaded.') |
|
1695 | 1726 | else: |
|
1696 | 1727 | self.has_readline = True |
|
1697 | 1728 | self.readline = readline |
|
1698 | 1729 | sys.modules['readline'] = readline |
|
1699 | 1730 | |
|
1700 | 1731 | # Platform-specific configuration |
|
1701 | 1732 | if os.name == 'nt': |
|
1702 | 1733 | # FIXME - check with Frederick to see if we can harmonize |
|
1703 | 1734 | # naming conventions with pyreadline to avoid this |
|
1704 | 1735 | # platform-dependent check |
|
1705 | 1736 | self.readline_startup_hook = readline.set_pre_input_hook |
|
1706 | 1737 | else: |
|
1707 | 1738 | self.readline_startup_hook = readline.set_startup_hook |
|
1708 | 1739 | |
|
1709 | 1740 | # Load user's initrc file (readline config) |
|
1710 | 1741 | # Or if libedit is used, load editrc. |
|
1711 | 1742 | inputrc_name = os.environ.get('INPUTRC') |
|
1712 | 1743 | if inputrc_name is None: |
|
1713 | 1744 | inputrc_name = '.inputrc' |
|
1714 | 1745 | if readline.uses_libedit: |
|
1715 | 1746 | inputrc_name = '.editrc' |
|
1716 | 1747 | inputrc_name = os.path.join(self.home_dir, inputrc_name) |
|
1717 | 1748 | if os.path.isfile(inputrc_name): |
|
1718 | 1749 | try: |
|
1719 | 1750 | readline.read_init_file(inputrc_name) |
|
1720 | 1751 | except: |
|
1721 | 1752 | warn('Problems reading readline initialization file <%s>' |
|
1722 | 1753 | % inputrc_name) |
|
1723 | 1754 | |
|
1724 | 1755 | # Configure readline according to user's prefs |
|
1725 | 1756 | # This is only done if GNU readline is being used. If libedit |
|
1726 | 1757 | # is being used (as on Leopard) the readline config is |
|
1727 | 1758 | # not run as the syntax for libedit is different. |
|
1728 | 1759 | if not readline.uses_libedit: |
|
1729 | 1760 | for rlcommand in self.readline_parse_and_bind: |
|
1730 | 1761 | #print "loading rl:",rlcommand # dbg |
|
1731 | 1762 | readline.parse_and_bind(rlcommand) |
|
1732 | 1763 | |
|
1733 | 1764 | # Remove some chars from the delimiters list. If we encounter |
|
1734 | 1765 | # unicode chars, discard them. |
|
1735 | 1766 | delims = readline.get_completer_delims() |
|
1736 | 1767 | if not py3compat.PY3: |
|
1737 | 1768 | delims = delims.encode("ascii", "ignore") |
|
1738 | 1769 | for d in self.readline_remove_delims: |
|
1739 | 1770 | delims = delims.replace(d, "") |
|
1740 | 1771 | delims = delims.replace(ESC_MAGIC, '') |
|
1741 | 1772 | readline.set_completer_delims(delims) |
|
1742 | 1773 | # otherwise we end up with a monster history after a while: |
|
1743 | 1774 | readline.set_history_length(self.history_length) |
|
1744 | 1775 | |
|
1745 | 1776 | self.refill_readline_hist() |
|
1746 | 1777 | self.readline_no_record = ReadlineNoRecord(self) |
|
1747 | 1778 | |
|
1748 | 1779 | # Configure auto-indent for all platforms |
|
1749 | 1780 | self.set_autoindent(self.autoindent) |
|
1750 | 1781 | |
|
1751 | 1782 | def refill_readline_hist(self): |
|
1752 | 1783 | # Load the last 1000 lines from history |
|
1753 | 1784 | self.readline.clear_history() |
|
1754 | 1785 | stdin_encoding = sys.stdin.encoding or "utf-8" |
|
1755 | 1786 | last_cell = u"" |
|
1756 | 1787 | for _, _, cell in self.history_manager.get_tail(1000, |
|
1757 | 1788 | include_latest=True): |
|
1758 | 1789 | # Ignore blank lines and consecutive duplicates |
|
1759 | 1790 | cell = cell.rstrip() |
|
1760 | 1791 | if cell and (cell != last_cell): |
|
1761 | 1792 | if self.multiline_history: |
|
1762 | 1793 | self.readline.add_history(py3compat.unicode_to_str(cell, |
|
1763 | 1794 | stdin_encoding)) |
|
1764 | 1795 | else: |
|
1765 | 1796 | for line in cell.splitlines(): |
|
1766 | 1797 | self.readline.add_history(py3compat.unicode_to_str(line, |
|
1767 | 1798 | stdin_encoding)) |
|
1768 | 1799 | last_cell = cell |
|
1769 | 1800 | |
|
1770 | 1801 | def set_next_input(self, s): |
|
1771 | 1802 | """ Sets the 'default' input string for the next command line. |
|
1772 | 1803 | |
|
1773 | 1804 | Requires readline. |
|
1774 | 1805 | |
|
1775 | 1806 | Example: |
|
1776 | 1807 | |
|
1777 | 1808 | [D:\ipython]|1> _ip.set_next_input("Hello Word") |
|
1778 | 1809 | [D:\ipython]|2> Hello Word_ # cursor is here |
|
1779 | 1810 | """ |
|
1780 | 1811 | self.rl_next_input = py3compat.cast_bytes_py2(s) |
|
1781 | 1812 | |
|
1782 | 1813 | # Maybe move this to the terminal subclass? |
|
1783 | 1814 | def pre_readline(self): |
|
1784 | 1815 | """readline hook to be used at the start of each line. |
|
1785 | 1816 | |
|
1786 | 1817 | Currently it handles auto-indent only.""" |
|
1787 | 1818 | |
|
1788 | 1819 | if self.rl_do_indent: |
|
1789 | 1820 | self.readline.insert_text(self._indent_current_str()) |
|
1790 | 1821 | if self.rl_next_input is not None: |
|
1791 | 1822 | self.readline.insert_text(self.rl_next_input) |
|
1792 | 1823 | self.rl_next_input = None |
|
1793 | 1824 | |
|
1794 | 1825 | def _indent_current_str(self): |
|
1795 | 1826 | """return the current level of indentation as a string""" |
|
1796 | 1827 | return self.input_splitter.indent_spaces * ' ' |
|
1797 | 1828 | |
|
1798 | 1829 | #------------------------------------------------------------------------- |
|
1799 | 1830 | # Things related to text completion |
|
1800 | 1831 | #------------------------------------------------------------------------- |
|
1801 | 1832 | |
|
1802 | 1833 | def init_completer(self): |
|
1803 | 1834 | """Initialize the completion machinery. |
|
1804 | 1835 | |
|
1805 | 1836 | This creates completion machinery that can be used by client code, |
|
1806 | 1837 | either interactively in-process (typically triggered by the readline |
|
1807 | 1838 | library), programatically (such as in test suites) or out-of-prcess |
|
1808 | 1839 | (typically over the network by remote frontends). |
|
1809 | 1840 | """ |
|
1810 | 1841 | from IPython.core.completer import IPCompleter |
|
1811 | 1842 | from IPython.core.completerlib import (module_completer, |
|
1812 | 1843 | magic_run_completer, cd_completer) |
|
1813 | 1844 | |
|
1814 | 1845 | self.Completer = IPCompleter(shell=self, |
|
1815 | 1846 | namespace=self.user_ns, |
|
1816 | 1847 | global_namespace=self.user_global_ns, |
|
1817 | 1848 | alias_table=self.alias_manager.alias_table, |
|
1818 | 1849 | use_readline=self.has_readline, |
|
1819 | 1850 | config=self.config, |
|
1820 | 1851 | ) |
|
1821 | 1852 | self.configurables.append(self.Completer) |
|
1822 | 1853 | |
|
1823 | 1854 | # Add custom completers to the basic ones built into IPCompleter |
|
1824 | 1855 | sdisp = self.strdispatchers.get('complete_command', StrDispatch()) |
|
1825 | 1856 | self.strdispatchers['complete_command'] = sdisp |
|
1826 | 1857 | self.Completer.custom_completers = sdisp |
|
1827 | 1858 | |
|
1828 | 1859 | self.set_hook('complete_command', module_completer, str_key = 'import') |
|
1829 | 1860 | self.set_hook('complete_command', module_completer, str_key = 'from') |
|
1830 | 1861 | self.set_hook('complete_command', magic_run_completer, str_key = '%run') |
|
1831 | 1862 | self.set_hook('complete_command', cd_completer, str_key = '%cd') |
|
1832 | 1863 | |
|
1833 | 1864 | # Only configure readline if we truly are using readline. IPython can |
|
1834 | 1865 | # do tab-completion over the network, in GUIs, etc, where readline |
|
1835 | 1866 | # itself may be absent |
|
1836 | 1867 | if self.has_readline: |
|
1837 | 1868 | self.set_readline_completer() |
|
1838 | 1869 | |
|
1839 | 1870 | def complete(self, text, line=None, cursor_pos=None): |
|
1840 | 1871 | """Return the completed text and a list of completions. |
|
1841 | 1872 | |
|
1842 | 1873 | Parameters |
|
1843 | 1874 | ---------- |
|
1844 | 1875 | |
|
1845 | 1876 | text : string |
|
1846 | 1877 | A string of text to be completed on. It can be given as empty and |
|
1847 | 1878 | instead a line/position pair are given. In this case, the |
|
1848 | 1879 | completer itself will split the line like readline does. |
|
1849 | 1880 | |
|
1850 | 1881 | line : string, optional |
|
1851 | 1882 | The complete line that text is part of. |
|
1852 | 1883 | |
|
1853 | 1884 | cursor_pos : int, optional |
|
1854 | 1885 | The position of the cursor on the input line. |
|
1855 | 1886 | |
|
1856 | 1887 | Returns |
|
1857 | 1888 | ------- |
|
1858 | 1889 | text : string |
|
1859 | 1890 | The actual text that was completed. |
|
1860 | 1891 | |
|
1861 | 1892 | matches : list |
|
1862 | 1893 | A sorted list with all possible completions. |
|
1863 | 1894 | |
|
1864 | 1895 | The optional arguments allow the completion to take more context into |
|
1865 | 1896 | account, and are part of the low-level completion API. |
|
1866 | 1897 | |
|
1867 | 1898 | This is a wrapper around the completion mechanism, similar to what |
|
1868 | 1899 | readline does at the command line when the TAB key is hit. By |
|
1869 | 1900 | exposing it as a method, it can be used by other non-readline |
|
1870 | 1901 | environments (such as GUIs) for text completion. |
|
1871 | 1902 | |
|
1872 | 1903 | Simple usage example: |
|
1873 | 1904 | |
|
1874 | 1905 | In [1]: x = 'hello' |
|
1875 | 1906 | |
|
1876 | 1907 | In [2]: _ip.complete('x.l') |
|
1877 | 1908 | Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip']) |
|
1878 | 1909 | """ |
|
1879 | 1910 | |
|
1880 | 1911 | # Inject names into __builtin__ so we can complete on the added names. |
|
1881 | 1912 | with self.builtin_trap: |
|
1882 | 1913 | return self.Completer.complete(text, line, cursor_pos) |
|
1883 | 1914 | |
|
1884 | 1915 | def set_custom_completer(self, completer, pos=0): |
|
1885 | 1916 | """Adds a new custom completer function. |
|
1886 | 1917 | |
|
1887 | 1918 | The position argument (defaults to 0) is the index in the completers |
|
1888 | 1919 | list where you want the completer to be inserted.""" |
|
1889 | 1920 | |
|
1890 | 1921 | newcomp = types.MethodType(completer,self.Completer) |
|
1891 | 1922 | self.Completer.matchers.insert(pos,newcomp) |
|
1892 | 1923 | |
|
1893 | 1924 | def set_readline_completer(self): |
|
1894 | 1925 | """Reset readline's completer to be our own.""" |
|
1895 | 1926 | self.readline.set_completer(self.Completer.rlcomplete) |
|
1896 | 1927 | |
|
1897 | 1928 | def set_completer_frame(self, frame=None): |
|
1898 | 1929 | """Set the frame of the completer.""" |
|
1899 | 1930 | if frame: |
|
1900 | 1931 | self.Completer.namespace = frame.f_locals |
|
1901 | 1932 | self.Completer.global_namespace = frame.f_globals |
|
1902 | 1933 | else: |
|
1903 | 1934 | self.Completer.namespace = self.user_ns |
|
1904 | 1935 | self.Completer.global_namespace = self.user_global_ns |
|
1905 | 1936 | |
|
1906 | 1937 | #------------------------------------------------------------------------- |
|
1907 | 1938 | # Things related to magics |
|
1908 | 1939 | #------------------------------------------------------------------------- |
|
1909 | 1940 | |
|
1910 | 1941 | def init_magics(self): |
|
1911 | 1942 | # FIXME: Move the color initialization to the DisplayHook, which |
|
1912 | 1943 | # should be split into a prompt manager and displayhook. We probably |
|
1913 | 1944 | # even need a centralize colors management object. |
|
1914 | 1945 | self.magic_colors(self.colors) |
|
1915 | 1946 | # History was moved to a separate module |
|
1916 | 1947 | from . import history |
|
1917 | 1948 | history.init_ipython(self) |
|
1918 | 1949 | |
|
1919 | 1950 | def magic(self, arg_s, next_input=None): |
|
1920 | 1951 | """Call a magic function by name. |
|
1921 | 1952 | |
|
1922 | 1953 | Input: a string containing the name of the magic function to call and |
|
1923 | 1954 | any additional arguments to be passed to the magic. |
|
1924 | 1955 | |
|
1925 | 1956 | magic('name -opt foo bar') is equivalent to typing at the ipython |
|
1926 | 1957 | prompt: |
|
1927 | 1958 | |
|
1928 | 1959 | In[1]: %name -opt foo bar |
|
1929 | 1960 | |
|
1930 | 1961 | To call a magic without arguments, simply use magic('name'). |
|
1931 | 1962 | |
|
1932 | 1963 | This provides a proper Python function to call IPython's magics in any |
|
1933 | 1964 | valid Python code you can type at the interpreter, including loops and |
|
1934 | 1965 | compound statements. |
|
1935 | 1966 | """ |
|
1936 | 1967 | # Allow setting the next input - this is used if the user does `a=abs?`. |
|
1937 | 1968 | # We do this first so that magic functions can override it. |
|
1938 | 1969 | if next_input: |
|
1939 | 1970 | self.set_next_input(next_input) |
|
1940 | 1971 | |
|
1941 | 1972 | args = arg_s.split(' ',1) |
|
1942 | 1973 | magic_name = args[0] |
|
1943 | 1974 | magic_name = magic_name.lstrip(prefilter.ESC_MAGIC) |
|
1944 | 1975 | |
|
1945 | 1976 | try: |
|
1946 | 1977 | magic_args = args[1] |
|
1947 | 1978 | except IndexError: |
|
1948 | 1979 | magic_args = '' |
|
1949 | 1980 | fn = getattr(self,'magic_'+magic_name,None) |
|
1950 | 1981 | if fn is None: |
|
1951 | 1982 | error("Magic function `%s` not found." % magic_name) |
|
1952 | 1983 | else: |
|
1953 | 1984 | magic_args = self.var_expand(magic_args,1) |
|
1954 | 1985 | # Grab local namespace if we need it: |
|
1955 | 1986 | if getattr(fn, "needs_local_scope", False): |
|
1956 | 1987 | self._magic_locals = sys._getframe(1).f_locals |
|
1957 | 1988 | with self.builtin_trap: |
|
1958 | 1989 | result = fn(magic_args) |
|
1959 | 1990 | # Ensure we're not keeping object references around: |
|
1960 | 1991 | self._magic_locals = {} |
|
1961 | 1992 | return result |
|
1962 | 1993 | |
|
1963 | 1994 | def define_magic(self, magicname, func): |
|
1964 | 1995 | """Expose own function as magic function for ipython |
|
1965 | 1996 | |
|
1966 | 1997 | Example:: |
|
1967 | 1998 | |
|
1968 | 1999 | def foo_impl(self,parameter_s=''): |
|
1969 | 2000 | 'My very own magic!. (Use docstrings, IPython reads them).' |
|
1970 | 2001 | print 'Magic function. Passed parameter is between < >:' |
|
1971 | 2002 | print '<%s>' % parameter_s |
|
1972 | 2003 | print 'The self object is:', self |
|
1973 | 2004 | |
|
1974 | 2005 | ip.define_magic('foo',foo_impl) |
|
1975 | 2006 | """ |
|
1976 | 2007 | im = types.MethodType(func,self) |
|
1977 | 2008 | old = getattr(self, "magic_" + magicname, None) |
|
1978 | 2009 | setattr(self, "magic_" + magicname, im) |
|
1979 | 2010 | return old |
|
1980 | 2011 | |
|
1981 | 2012 | #------------------------------------------------------------------------- |
|
1982 | 2013 | # Things related to macros |
|
1983 | 2014 | #------------------------------------------------------------------------- |
|
1984 | 2015 | |
|
1985 | 2016 | def define_macro(self, name, themacro): |
|
1986 | 2017 | """Define a new macro |
|
1987 | 2018 | |
|
1988 | 2019 | Parameters |
|
1989 | 2020 | ---------- |
|
1990 | 2021 | name : str |
|
1991 | 2022 | The name of the macro. |
|
1992 | 2023 | themacro : str or Macro |
|
1993 | 2024 | The action to do upon invoking the macro. If a string, a new |
|
1994 | 2025 | Macro object is created by passing the string to it. |
|
1995 | 2026 | """ |
|
1996 | 2027 | |
|
1997 | 2028 | from IPython.core import macro |
|
1998 | 2029 | |
|
1999 | 2030 | if isinstance(themacro, basestring): |
|
2000 | 2031 | themacro = macro.Macro(themacro) |
|
2001 | 2032 | if not isinstance(themacro, macro.Macro): |
|
2002 | 2033 | raise ValueError('A macro must be a string or a Macro instance.') |
|
2003 | 2034 | self.user_ns[name] = themacro |
|
2004 | 2035 | |
|
2005 | 2036 | #------------------------------------------------------------------------- |
|
2006 | 2037 | # Things related to the running of system commands |
|
2007 | 2038 | #------------------------------------------------------------------------- |
|
2008 | 2039 | |
|
2009 | 2040 | def system_piped(self, cmd): |
|
2010 | 2041 | """Call the given cmd in a subprocess, piping stdout/err |
|
2011 | 2042 | |
|
2012 | 2043 | Parameters |
|
2013 | 2044 | ---------- |
|
2014 | 2045 | cmd : str |
|
2015 | 2046 | Command to execute (can not end in '&', as background processes are |
|
2016 | 2047 | not supported. Should not be a command that expects input |
|
2017 | 2048 | other than simple text. |
|
2018 | 2049 | """ |
|
2019 | 2050 | if cmd.rstrip().endswith('&'): |
|
2020 | 2051 | # this is *far* from a rigorous test |
|
2021 | 2052 | # We do not support backgrounding processes because we either use |
|
2022 | 2053 | # pexpect or pipes to read from. Users can always just call |
|
2023 | 2054 | # os.system() or use ip.system=ip.system_raw |
|
2024 | 2055 | # if they really want a background process. |
|
2025 | 2056 | raise OSError("Background processes not supported.") |
|
2026 | 2057 | |
|
2027 | 2058 | # we explicitly do NOT return the subprocess status code, because |
|
2028 | 2059 | # a non-None value would trigger :func:`sys.displayhook` calls. |
|
2029 | 2060 | # Instead, we store the exit_code in user_ns. |
|
2030 | 2061 | self.user_ns['_exit_code'] = system(self.var_expand(cmd, depth=2)) |
|
2031 | 2062 | |
|
2032 | 2063 | def system_raw(self, cmd): |
|
2033 | 2064 | """Call the given cmd in a subprocess using os.system |
|
2034 | 2065 | |
|
2035 | 2066 | Parameters |
|
2036 | 2067 | ---------- |
|
2037 | 2068 | cmd : str |
|
2038 | 2069 | Command to execute. |
|
2039 | 2070 | """ |
|
2040 | 2071 | cmd = self.var_expand(cmd, depth=2) |
|
2041 | 2072 | # protect os.system from UNC paths on Windows, which it can't handle: |
|
2042 | 2073 | if sys.platform == 'win32': |
|
2043 | 2074 | from IPython.utils._process_win32 import AvoidUNCPath |
|
2044 | 2075 | with AvoidUNCPath() as path: |
|
2045 | 2076 | if path is not None: |
|
2046 | 2077 | cmd = '"pushd %s &&"%s' % (path, cmd) |
|
2047 | 2078 | cmd = py3compat.unicode_to_str(cmd) |
|
2048 | 2079 | ec = os.system(cmd) |
|
2049 | 2080 | else: |
|
2050 | 2081 | cmd = py3compat.unicode_to_str(cmd) |
|
2051 | 2082 | ec = os.system(cmd) |
|
2052 | 2083 | |
|
2053 | 2084 | # We explicitly do NOT return the subprocess status code, because |
|
2054 | 2085 | # a non-None value would trigger :func:`sys.displayhook` calls. |
|
2055 | 2086 | # Instead, we store the exit_code in user_ns. |
|
2056 | 2087 | self.user_ns['_exit_code'] = ec |
|
2057 | 2088 | |
|
2058 | 2089 | # use piped system by default, because it is better behaved |
|
2059 | 2090 | system = system_piped |
|
2060 | 2091 | |
|
2061 | 2092 | def getoutput(self, cmd, split=True): |
|
2062 | 2093 | """Get output (possibly including stderr) from a subprocess. |
|
2063 | 2094 | |
|
2064 | 2095 | Parameters |
|
2065 | 2096 | ---------- |
|
2066 | 2097 | cmd : str |
|
2067 | 2098 | Command to execute (can not end in '&', as background processes are |
|
2068 | 2099 | not supported. |
|
2069 | 2100 | split : bool, optional |
|
2070 | 2101 | |
|
2071 | 2102 | If True, split the output into an IPython SList. Otherwise, an |
|
2072 | 2103 | IPython LSString is returned. These are objects similar to normal |
|
2073 | 2104 | lists and strings, with a few convenience attributes for easier |
|
2074 | 2105 | manipulation of line-based output. You can use '?' on them for |
|
2075 | 2106 | details. |
|
2076 | 2107 | """ |
|
2077 | 2108 | if cmd.rstrip().endswith('&'): |
|
2078 | 2109 | # this is *far* from a rigorous test |
|
2079 | 2110 | raise OSError("Background processes not supported.") |
|
2080 | 2111 | out = getoutput(self.var_expand(cmd, depth=2)) |
|
2081 | 2112 | if split: |
|
2082 | 2113 | out = SList(out.splitlines()) |
|
2083 | 2114 | else: |
|
2084 | 2115 | out = LSString(out) |
|
2085 | 2116 | return out |
|
2086 | 2117 | |
|
2087 | 2118 | #------------------------------------------------------------------------- |
|
2088 | 2119 | # Things related to aliases |
|
2089 | 2120 | #------------------------------------------------------------------------- |
|
2090 | 2121 | |
|
2091 | 2122 | def init_alias(self): |
|
2092 | 2123 | self.alias_manager = AliasManager(shell=self, config=self.config) |
|
2093 | 2124 | self.configurables.append(self.alias_manager) |
|
2094 | 2125 | self.ns_table['alias'] = self.alias_manager.alias_table, |
|
2095 | 2126 | |
|
2096 | 2127 | #------------------------------------------------------------------------- |
|
2097 | 2128 | # Things related to extensions and plugins |
|
2098 | 2129 | #------------------------------------------------------------------------- |
|
2099 | 2130 | |
|
2100 | 2131 | def init_extension_manager(self): |
|
2101 | 2132 | self.extension_manager = ExtensionManager(shell=self, config=self.config) |
|
2102 | 2133 | self.configurables.append(self.extension_manager) |
|
2103 | 2134 | |
|
2104 | 2135 | def init_plugin_manager(self): |
|
2105 | 2136 | self.plugin_manager = PluginManager(config=self.config) |
|
2106 | 2137 | self.configurables.append(self.plugin_manager) |
|
2107 | 2138 | |
|
2108 | 2139 | |
|
2109 | 2140 | #------------------------------------------------------------------------- |
|
2110 | 2141 | # Things related to payloads |
|
2111 | 2142 | #------------------------------------------------------------------------- |
|
2112 | 2143 | |
|
2113 | 2144 | def init_payload(self): |
|
2114 | 2145 | self.payload_manager = PayloadManager(config=self.config) |
|
2115 | 2146 | self.configurables.append(self.payload_manager) |
|
2116 | 2147 | |
|
2117 | 2148 | #------------------------------------------------------------------------- |
|
2118 | 2149 | # Things related to the prefilter |
|
2119 | 2150 | #------------------------------------------------------------------------- |
|
2120 | 2151 | |
|
2121 | 2152 | def init_prefilter(self): |
|
2122 | 2153 | self.prefilter_manager = PrefilterManager(shell=self, config=self.config) |
|
2123 | 2154 | self.configurables.append(self.prefilter_manager) |
|
2124 | 2155 | # Ultimately this will be refactored in the new interpreter code, but |
|
2125 | 2156 | # for now, we should expose the main prefilter method (there's legacy |
|
2126 | 2157 | # code out there that may rely on this). |
|
2127 | 2158 | self.prefilter = self.prefilter_manager.prefilter_lines |
|
2128 | 2159 | |
|
2129 | 2160 | def auto_rewrite_input(self, cmd): |
|
2130 | 2161 | """Print to the screen the rewritten form of the user's command. |
|
2131 | 2162 | |
|
2132 | 2163 | This shows visual feedback by rewriting input lines that cause |
|
2133 | 2164 | automatic calling to kick in, like:: |
|
2134 | 2165 | |
|
2135 | 2166 | /f x |
|
2136 | 2167 | |
|
2137 | 2168 | into:: |
|
2138 | 2169 | |
|
2139 | 2170 | ------> f(x) |
|
2140 | 2171 | |
|
2141 | 2172 | after the user's input prompt. This helps the user understand that the |
|
2142 | 2173 | input line was transformed automatically by IPython. |
|
2143 | 2174 | """ |
|
2175 | if not self.show_rewritten_input: | |
|
2176 | return | |
|
2177 | ||
|
2144 | 2178 | rw = self.prompt_manager.render('rewrite') + cmd |
|
2145 | 2179 | |
|
2146 | 2180 | try: |
|
2147 | 2181 | # plain ascii works better w/ pyreadline, on some machines, so |
|
2148 | 2182 | # we use it and only print uncolored rewrite if we have unicode |
|
2149 | 2183 | rw = str(rw) |
|
2150 | 2184 | print >> io.stdout, rw |
|
2151 | 2185 | except UnicodeEncodeError: |
|
2152 | 2186 | print "------> " + cmd |
|
2153 | 2187 | |
|
2154 | 2188 | #------------------------------------------------------------------------- |
|
2155 | 2189 | # Things related to extracting values/expressions from kernel and user_ns |
|
2156 | 2190 | #------------------------------------------------------------------------- |
|
2157 | 2191 | |
|
2158 | 2192 | def _simple_error(self): |
|
2159 | 2193 | etype, value = sys.exc_info()[:2] |
|
2160 | 2194 | return u'[ERROR] {e.__name__}: {v}'.format(e=etype, v=value) |
|
2161 | 2195 | |
|
2162 | 2196 | def user_variables(self, names): |
|
2163 | 2197 | """Get a list of variable names from the user's namespace. |
|
2164 | 2198 | |
|
2165 | 2199 | Parameters |
|
2166 | 2200 | ---------- |
|
2167 | 2201 | names : list of strings |
|
2168 | 2202 | A list of names of variables to be read from the user namespace. |
|
2169 | 2203 | |
|
2170 | 2204 | Returns |
|
2171 | 2205 | ------- |
|
2172 | 2206 | A dict, keyed by the input names and with the repr() of each value. |
|
2173 | 2207 | """ |
|
2174 | 2208 | out = {} |
|
2175 | 2209 | user_ns = self.user_ns |
|
2176 | 2210 | for varname in names: |
|
2177 | 2211 | try: |
|
2178 | 2212 | value = repr(user_ns[varname]) |
|
2179 | 2213 | except: |
|
2180 | 2214 | value = self._simple_error() |
|
2181 | 2215 | out[varname] = value |
|
2182 | 2216 | return out |
|
2183 | 2217 | |
|
2184 | 2218 | def user_expressions(self, expressions): |
|
2185 | 2219 | """Evaluate a dict of expressions in the user's namespace. |
|
2186 | 2220 | |
|
2187 | 2221 | Parameters |
|
2188 | 2222 | ---------- |
|
2189 | 2223 | expressions : dict |
|
2190 | 2224 | A dict with string keys and string values. The expression values |
|
2191 | 2225 | should be valid Python expressions, each of which will be evaluated |
|
2192 | 2226 | in the user namespace. |
|
2193 | 2227 | |
|
2194 | 2228 | Returns |
|
2195 | 2229 | ------- |
|
2196 | 2230 | A dict, keyed like the input expressions dict, with the repr() of each |
|
2197 | 2231 | value. |
|
2198 | 2232 | """ |
|
2199 | 2233 | out = {} |
|
2200 | 2234 | user_ns = self.user_ns |
|
2201 | 2235 | global_ns = self.user_global_ns |
|
2202 | 2236 | for key, expr in expressions.iteritems(): |
|
2203 | 2237 | try: |
|
2204 | 2238 | value = repr(eval(expr, global_ns, user_ns)) |
|
2205 | 2239 | except: |
|
2206 | 2240 | value = self._simple_error() |
|
2207 | 2241 | out[key] = value |
|
2208 | 2242 | return out |
|
2209 | 2243 | |
|
2210 | 2244 | #------------------------------------------------------------------------- |
|
2211 | 2245 | # Things related to the running of code |
|
2212 | 2246 | #------------------------------------------------------------------------- |
|
2213 | 2247 | |
|
2214 | 2248 | def ex(self, cmd): |
|
2215 | 2249 | """Execute a normal python statement in user namespace.""" |
|
2216 | 2250 | with self.builtin_trap: |
|
2217 | 2251 | exec cmd in self.user_global_ns, self.user_ns |
|
2218 | 2252 | |
|
2219 | 2253 | def ev(self, expr): |
|
2220 | 2254 | """Evaluate python expression expr in user namespace. |
|
2221 | 2255 | |
|
2222 | 2256 | Returns the result of evaluation |
|
2223 | 2257 | """ |
|
2224 | 2258 | with self.builtin_trap: |
|
2225 | 2259 | return eval(expr, self.user_global_ns, self.user_ns) |
|
2226 | 2260 | |
|
2227 | 2261 | def safe_execfile(self, fname, *where, **kw): |
|
2228 | 2262 | """A safe version of the builtin execfile(). |
|
2229 | 2263 | |
|
2230 | 2264 | This version will never throw an exception, but instead print |
|
2231 | 2265 | helpful error messages to the screen. This only works on pure |
|
2232 | 2266 | Python files with the .py extension. |
|
2233 | 2267 | |
|
2234 | 2268 | Parameters |
|
2235 | 2269 | ---------- |
|
2236 | 2270 | fname : string |
|
2237 | 2271 | The name of the file to be executed. |
|
2238 | 2272 | where : tuple |
|
2239 | 2273 | One or two namespaces, passed to execfile() as (globals,locals). |
|
2240 | 2274 | If only one is given, it is passed as both. |
|
2241 | 2275 | exit_ignore : bool (False) |
|
2242 | 2276 | If True, then silence SystemExit for non-zero status (it is always |
|
2243 | 2277 | silenced for zero status, as it is so common). |
|
2244 | 2278 | raise_exceptions : bool (False) |
|
2245 | 2279 | If True raise exceptions everywhere. Meant for testing. |
|
2246 | 2280 | |
|
2247 | 2281 | """ |
|
2248 | 2282 | kw.setdefault('exit_ignore', False) |
|
2249 | 2283 | kw.setdefault('raise_exceptions', False) |
|
2250 | 2284 | |
|
2251 | 2285 | fname = os.path.abspath(os.path.expanduser(fname)) |
|
2252 | 2286 | |
|
2253 | 2287 | # Make sure we can open the file |
|
2254 | 2288 | try: |
|
2255 | 2289 | with open(fname) as thefile: |
|
2256 | 2290 | pass |
|
2257 | 2291 | except: |
|
2258 | 2292 | warn('Could not open file <%s> for safe execution.' % fname) |
|
2259 | 2293 | return |
|
2260 | 2294 | |
|
2261 | 2295 | # Find things also in current directory. This is needed to mimic the |
|
2262 | 2296 | # behavior of running a script from the system command line, where |
|
2263 | 2297 | # Python inserts the script's directory into sys.path |
|
2264 | 2298 | dname = os.path.dirname(fname) |
|
2265 | 2299 | |
|
2266 | 2300 | with prepended_to_syspath(dname): |
|
2267 | 2301 | try: |
|
2268 | 2302 | py3compat.execfile(fname,*where) |
|
2269 | 2303 | except SystemExit, status: |
|
2270 | 2304 | # If the call was made with 0 or None exit status (sys.exit(0) |
|
2271 | 2305 | # or sys.exit() ), don't bother showing a traceback, as both of |
|
2272 | 2306 | # these are considered normal by the OS: |
|
2273 | 2307 | # > python -c'import sys;sys.exit(0)'; echo $? |
|
2274 | 2308 | # 0 |
|
2275 | 2309 | # > python -c'import sys;sys.exit()'; echo $? |
|
2276 | 2310 | # 0 |
|
2277 | 2311 | # For other exit status, we show the exception unless |
|
2278 | 2312 | # explicitly silenced, but only in short form. |
|
2279 | 2313 | if kw['raise_exceptions']: |
|
2280 | 2314 | raise |
|
2281 | 2315 | if status.code not in (0, None) and not kw['exit_ignore']: |
|
2282 | 2316 | self.showtraceback(exception_only=True) |
|
2283 | 2317 | except: |
|
2284 | 2318 | if kw['raise_exceptions']: |
|
2285 | 2319 | raise |
|
2286 | 2320 | self.showtraceback() |
|
2287 | 2321 | |
|
2288 | 2322 | def safe_execfile_ipy(self, fname): |
|
2289 | 2323 | """Like safe_execfile, but for .ipy files with IPython syntax. |
|
2290 | 2324 | |
|
2291 | 2325 | Parameters |
|
2292 | 2326 | ---------- |
|
2293 | 2327 | fname : str |
|
2294 | 2328 | The name of the file to execute. The filename must have a |
|
2295 | 2329 | .ipy extension. |
|
2296 | 2330 | """ |
|
2297 | 2331 | fname = os.path.abspath(os.path.expanduser(fname)) |
|
2298 | 2332 | |
|
2299 | 2333 | # Make sure we can open the file |
|
2300 | 2334 | try: |
|
2301 | 2335 | with open(fname) as thefile: |
|
2302 | 2336 | pass |
|
2303 | 2337 | except: |
|
2304 | 2338 | warn('Could not open file <%s> for safe execution.' % fname) |
|
2305 | 2339 | return |
|
2306 | 2340 | |
|
2307 | 2341 | # Find things also in current directory. This is needed to mimic the |
|
2308 | 2342 | # behavior of running a script from the system command line, where |
|
2309 | 2343 | # Python inserts the script's directory into sys.path |
|
2310 | 2344 | dname = os.path.dirname(fname) |
|
2311 | 2345 | |
|
2312 | 2346 | with prepended_to_syspath(dname): |
|
2313 | 2347 | try: |
|
2314 | 2348 | with open(fname) as thefile: |
|
2315 | 2349 | # self.run_cell currently captures all exceptions |
|
2316 | 2350 | # raised in user code. It would be nice if there were |
|
2317 | 2351 | # versions of runlines, execfile that did raise, so |
|
2318 | 2352 | # we could catch the errors. |
|
2319 | 2353 | self.run_cell(thefile.read(), store_history=False) |
|
2320 | 2354 | except: |
|
2321 | 2355 | self.showtraceback() |
|
2322 | 2356 | warn('Unknown failure executing file: <%s>' % fname) |
|
2323 | 2357 | |
|
2324 | 2358 | def run_cell(self, raw_cell, store_history=False): |
|
2325 | 2359 | """Run a complete IPython cell. |
|
2326 | 2360 | |
|
2327 | 2361 | Parameters |
|
2328 | 2362 | ---------- |
|
2329 | 2363 | raw_cell : str |
|
2330 | 2364 | The code (including IPython code such as %magic functions) to run. |
|
2331 | 2365 | store_history : bool |
|
2332 | 2366 | If True, the raw and translated cell will be stored in IPython's |
|
2333 | 2367 | history. For user code calling back into IPython's machinery, this |
|
2334 | 2368 | should be set to False. |
|
2335 | 2369 | """ |
|
2336 | 2370 | if (not raw_cell) or raw_cell.isspace(): |
|
2337 | 2371 | return |
|
2338 | 2372 | |
|
2339 | 2373 | for line in raw_cell.splitlines(): |
|
2340 | 2374 | self.input_splitter.push(line) |
|
2341 | 2375 | cell = self.input_splitter.source_reset() |
|
2342 | 2376 | |
|
2343 | 2377 | with self.builtin_trap: |
|
2344 | 2378 | prefilter_failed = False |
|
2345 | 2379 | if len(cell.splitlines()) == 1: |
|
2346 | 2380 | try: |
|
2347 | 2381 | # use prefilter_lines to handle trailing newlines |
|
2348 | 2382 | # restore trailing newline for ast.parse |
|
2349 | 2383 | cell = self.prefilter_manager.prefilter_lines(cell) + '\n' |
|
2350 | 2384 | except AliasError as e: |
|
2351 | 2385 | error(e) |
|
2352 | 2386 | prefilter_failed = True |
|
2353 | 2387 | except Exception: |
|
2354 | 2388 | # don't allow prefilter errors to crash IPython |
|
2355 | 2389 | self.showtraceback() |
|
2356 | 2390 | prefilter_failed = True |
|
2357 | 2391 | |
|
2358 | 2392 | # Store raw and processed history |
|
2359 | 2393 | if store_history: |
|
2360 | 2394 | self.history_manager.store_inputs(self.execution_count, |
|
2361 | 2395 | cell, raw_cell) |
|
2362 | 2396 | |
|
2363 | 2397 | self.logger.log(cell, raw_cell) |
|
2364 | 2398 | |
|
2365 | 2399 | if not prefilter_failed: |
|
2366 | 2400 | # don't run if prefilter failed |
|
2367 | 2401 | cell_name = self.compile.cache(cell, self.execution_count) |
|
2368 | 2402 | |
|
2369 | 2403 | with self.display_trap: |
|
2370 | 2404 | try: |
|
2371 | 2405 | code_ast = self.compile.ast_parse(cell, filename=cell_name) |
|
2372 | 2406 | except IndentationError: |
|
2373 | 2407 | self.showindentationerror() |
|
2374 | 2408 | self.execution_count += 1 |
|
2375 | 2409 | return None |
|
2376 | 2410 | except (OverflowError, SyntaxError, ValueError, TypeError, |
|
2377 | 2411 | MemoryError): |
|
2378 | 2412 | self.showsyntaxerror() |
|
2379 | 2413 | self.execution_count += 1 |
|
2380 | 2414 | return None |
|
2381 | 2415 | |
|
2382 | 2416 | self.run_ast_nodes(code_ast.body, cell_name, |
|
2383 | 2417 | interactivity="last_expr") |
|
2384 | 2418 | |
|
2385 | 2419 | # Execute any registered post-execution functions. |
|
2386 | 2420 | for func, status in self._post_execute.iteritems(): |
|
2387 | 2421 | if not status: |
|
2388 | 2422 | continue |
|
2389 | 2423 | try: |
|
2390 | 2424 | func() |
|
2391 | 2425 | except KeyboardInterrupt: |
|
2392 | 2426 | print >> io.stderr, "\nKeyboardInterrupt" |
|
2393 | 2427 | except Exception: |
|
2394 | 2428 | print >> io.stderr, "Disabling failed post-execution function: %s" % func |
|
2395 | 2429 | self.showtraceback() |
|
2396 | 2430 | # Deactivate failing function |
|
2397 | 2431 | self._post_execute[func] = False |
|
2398 | 2432 | |
|
2399 | 2433 | if store_history: |
|
2400 | 2434 | # Write output to the database. Does nothing unless |
|
2401 | 2435 | # history output logging is enabled. |
|
2402 | 2436 | self.history_manager.store_output(self.execution_count) |
|
2403 | 2437 | # Each cell is a *single* input, regardless of how many lines it has |
|
2404 | 2438 | self.execution_count += 1 |
|
2405 | 2439 | |
|
2406 | 2440 | def run_ast_nodes(self, nodelist, cell_name, interactivity='last_expr'): |
|
2407 | 2441 | """Run a sequence of AST nodes. The execution mode depends on the |
|
2408 | 2442 | interactivity parameter. |
|
2409 | 2443 | |
|
2410 | 2444 | Parameters |
|
2411 | 2445 | ---------- |
|
2412 | 2446 | nodelist : list |
|
2413 | 2447 | A sequence of AST nodes to run. |
|
2414 | 2448 | cell_name : str |
|
2415 | 2449 | Will be passed to the compiler as the filename of the cell. Typically |
|
2416 | 2450 | the value returned by ip.compile.cache(cell). |
|
2417 | 2451 | interactivity : str |
|
2418 | 2452 | 'all', 'last', 'last_expr' or 'none', specifying which nodes should be |
|
2419 | 2453 | run interactively (displaying output from expressions). 'last_expr' |
|
2420 | 2454 | will run the last node interactively only if it is an expression (i.e. |
|
2421 | 2455 | expressions in loops or other blocks are not displayed. Other values |
|
2422 | 2456 | for this parameter will raise a ValueError. |
|
2423 | 2457 | """ |
|
2424 | 2458 | if not nodelist: |
|
2425 | 2459 | return |
|
2426 | 2460 | |
|
2427 | 2461 | if interactivity == 'last_expr': |
|
2428 | 2462 | if isinstance(nodelist[-1], ast.Expr): |
|
2429 | 2463 | interactivity = "last" |
|
2430 | 2464 | else: |
|
2431 | 2465 | interactivity = "none" |
|
2432 | 2466 | |
|
2433 | 2467 | if interactivity == 'none': |
|
2434 | 2468 | to_run_exec, to_run_interactive = nodelist, [] |
|
2435 | 2469 | elif interactivity == 'last': |
|
2436 | 2470 | to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:] |
|
2437 | 2471 | elif interactivity == 'all': |
|
2438 | 2472 | to_run_exec, to_run_interactive = [], nodelist |
|
2439 | 2473 | else: |
|
2440 | 2474 | raise ValueError("Interactivity was %r" % interactivity) |
|
2441 | 2475 | |
|
2442 | 2476 | exec_count = self.execution_count |
|
2443 | 2477 | |
|
2444 | 2478 | try: |
|
2445 | 2479 | for i, node in enumerate(to_run_exec): |
|
2446 | 2480 | mod = ast.Module([node]) |
|
2447 | 2481 | code = self.compile(mod, cell_name, "exec") |
|
2448 | 2482 | if self.run_code(code): |
|
2449 | 2483 | return True |
|
2450 | 2484 | |
|
2451 | 2485 | for i, node in enumerate(to_run_interactive): |
|
2452 | 2486 | mod = ast.Interactive([node]) |
|
2453 | 2487 | code = self.compile(mod, cell_name, "single") |
|
2454 | 2488 | if self.run_code(code): |
|
2455 | 2489 | return True |
|
2456 | 2490 | except: |
|
2457 | 2491 | # It's possible to have exceptions raised here, typically by |
|
2458 | 2492 | # compilation of odd code (such as a naked 'return' outside a |
|
2459 | 2493 | # function) that did parse but isn't valid. Typically the exception |
|
2460 | 2494 | # is a SyntaxError, but it's safest just to catch anything and show |
|
2461 | 2495 | # the user a traceback. |
|
2462 | 2496 | |
|
2463 | 2497 | # We do only one try/except outside the loop to minimize the impact |
|
2464 | 2498 | # on runtime, and also because if any node in the node list is |
|
2465 | 2499 | # broken, we should stop execution completely. |
|
2466 | 2500 | self.showtraceback() |
|
2467 | 2501 | |
|
2468 | 2502 | return False |
|
2469 | 2503 | |
|
2470 | 2504 | def run_code(self, code_obj): |
|
2471 | 2505 | """Execute a code object. |
|
2472 | 2506 | |
|
2473 | 2507 | When an exception occurs, self.showtraceback() is called to display a |
|
2474 | 2508 | traceback. |
|
2475 | 2509 | |
|
2476 | 2510 | Parameters |
|
2477 | 2511 | ---------- |
|
2478 | 2512 | code_obj : code object |
|
2479 | 2513 | A compiled code object, to be executed |
|
2480 | 2514 | post_execute : bool [default: True] |
|
2481 | 2515 | whether to call post_execute hooks after this particular execution. |
|
2482 | 2516 | |
|
2483 | 2517 | Returns |
|
2484 | 2518 | ------- |
|
2485 | 2519 | False : successful execution. |
|
2486 | 2520 | True : an error occurred. |
|
2487 | 2521 | """ |
|
2488 | 2522 | |
|
2489 | 2523 | # Set our own excepthook in case the user code tries to call it |
|
2490 | 2524 | # directly, so that the IPython crash handler doesn't get triggered |
|
2491 | 2525 | old_excepthook,sys.excepthook = sys.excepthook, self.excepthook |
|
2492 | 2526 | |
|
2493 | 2527 | # we save the original sys.excepthook in the instance, in case config |
|
2494 | 2528 | # code (such as magics) needs access to it. |
|
2495 | 2529 | self.sys_excepthook = old_excepthook |
|
2496 | 2530 | outflag = 1 # happens in more places, so it's easier as default |
|
2497 | 2531 | try: |
|
2498 | 2532 | try: |
|
2499 | 2533 | self.hooks.pre_run_code_hook() |
|
2500 | 2534 | #rprint('Running code', repr(code_obj)) # dbg |
|
2501 | 2535 | exec code_obj in self.user_global_ns, self.user_ns |
|
2502 | 2536 | finally: |
|
2503 | 2537 | # Reset our crash handler in place |
|
2504 | 2538 | sys.excepthook = old_excepthook |
|
2505 | 2539 | except SystemExit: |
|
2506 | 2540 | self.showtraceback(exception_only=True) |
|
2507 | 2541 | warn("To exit: use 'exit', 'quit', or Ctrl-D.", level=1) |
|
2508 | 2542 | except self.custom_exceptions: |
|
2509 | 2543 | etype,value,tb = sys.exc_info() |
|
2510 | 2544 | self.CustomTB(etype,value,tb) |
|
2511 | 2545 | except: |
|
2512 | 2546 | self.showtraceback() |
|
2513 | 2547 | else: |
|
2514 | 2548 | outflag = 0 |
|
2515 | 2549 | if softspace(sys.stdout, 0): |
|
2516 | 2550 | |
|
2517 | 2551 | |
|
2518 | 2552 | return outflag |
|
2519 | 2553 | |
|
2520 | 2554 | # For backwards compatibility |
|
2521 | 2555 | runcode = run_code |
|
2522 | 2556 | |
|
2523 | 2557 | #------------------------------------------------------------------------- |
|
2524 | 2558 | # Things related to GUI support and pylab |
|
2525 | 2559 | #------------------------------------------------------------------------- |
|
2526 | 2560 | |
|
2527 | 2561 | def enable_gui(self, gui=None): |
|
2528 | 2562 | raise NotImplementedError('Implement enable_gui in a subclass') |
|
2529 | 2563 | |
|
2530 | 2564 | def enable_pylab(self, gui=None, import_all=True): |
|
2531 | 2565 | """Activate pylab support at runtime. |
|
2532 | 2566 | |
|
2533 | 2567 | This turns on support for matplotlib, preloads into the interactive |
|
2534 | 2568 | namespace all of numpy and pylab, and configures IPython to correctly |
|
2535 | 2569 | interact with the GUI event loop. The GUI backend to be used can be |
|
2536 | 2570 | optionally selected with the optional :param:`gui` argument. |
|
2537 | 2571 | |
|
2538 | 2572 | Parameters |
|
2539 | 2573 | ---------- |
|
2540 | 2574 | gui : optional, string |
|
2541 | 2575 | |
|
2542 | 2576 | If given, dictates the choice of matplotlib GUI backend to use |
|
2543 | 2577 | (should be one of IPython's supported backends, 'qt', 'osx', 'tk', |
|
2544 | 2578 | 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by |
|
2545 | 2579 | matplotlib (as dictated by the matplotlib build-time options plus the |
|
2546 | 2580 | user's matplotlibrc configuration file). Note that not all backends |
|
2547 | 2581 | make sense in all contexts, for example a terminal ipython can't |
|
2548 | 2582 | display figures inline. |
|
2549 | 2583 | """ |
|
2550 | 2584 | |
|
2551 | 2585 | # We want to prevent the loading of pylab to pollute the user's |
|
2552 | 2586 | # namespace as shown by the %who* magics, so we execute the activation |
|
2553 | 2587 | # code in an empty namespace, and we update *both* user_ns and |
|
2554 | 2588 | # user_ns_hidden with this information. |
|
2555 | 2589 | ns = {} |
|
2556 | 2590 | try: |
|
2557 | 2591 | gui = pylab_activate(ns, gui, import_all, self) |
|
2558 | 2592 | except KeyError: |
|
2559 | 2593 | error("Backend %r not supported" % gui) |
|
2560 | 2594 | return |
|
2561 | 2595 | self.user_ns.update(ns) |
|
2562 | 2596 | self.user_ns_hidden.update(ns) |
|
2563 | 2597 | # Now we must activate the gui pylab wants to use, and fix %run to take |
|
2564 | 2598 | # plot updates into account |
|
2565 | 2599 | self.enable_gui(gui) |
|
2566 | 2600 | self.magic_run = self._pylab_magic_run |
|
2567 | 2601 | |
|
2568 | 2602 | #------------------------------------------------------------------------- |
|
2569 | 2603 | # Utilities |
|
2570 | 2604 | #------------------------------------------------------------------------- |
|
2571 | 2605 | |
|
2572 | 2606 | def var_expand(self, cmd, depth=0, formatter=DollarFormatter()): |
|
2573 | 2607 | """Expand python variables in a string. |
|
2574 | 2608 | |
|
2575 | 2609 | The depth argument indicates how many frames above the caller should |
|
2576 | 2610 | be walked to look for the local namespace where to expand variables. |
|
2577 | 2611 | |
|
2578 | 2612 | The global namespace for expansion is always the user's interactive |
|
2579 | 2613 | namespace. |
|
2580 | 2614 | """ |
|
2581 | 2615 | ns = self.user_ns.copy() |
|
2582 | 2616 | ns.update(sys._getframe(depth+1).f_locals) |
|
2583 | 2617 | ns.pop('self', None) |
|
2584 | 2618 | return formatter.format(cmd, **ns) |
|
2585 | 2619 | |
|
2586 | 2620 | def mktempfile(self, data=None, prefix='ipython_edit_'): |
|
2587 | 2621 | """Make a new tempfile and return its filename. |
|
2588 | 2622 | |
|
2589 | 2623 | This makes a call to tempfile.mktemp, but it registers the created |
|
2590 | 2624 | filename internally so ipython cleans it up at exit time. |
|
2591 | 2625 | |
|
2592 | 2626 | Optional inputs: |
|
2593 | 2627 | |
|
2594 | 2628 | - data(None): if data is given, it gets written out to the temp file |
|
2595 | 2629 | immediately, and the file is closed again.""" |
|
2596 | 2630 | |
|
2597 | 2631 | filename = tempfile.mktemp('.py', prefix) |
|
2598 | 2632 | self.tempfiles.append(filename) |
|
2599 | 2633 | |
|
2600 | 2634 | if data: |
|
2601 | 2635 | tmp_file = open(filename,'w') |
|
2602 | 2636 | tmp_file.write(data) |
|
2603 | 2637 | tmp_file.close() |
|
2604 | 2638 | return filename |
|
2605 | 2639 | |
|
2606 | 2640 | # TODO: This should be removed when Term is refactored. |
|
2607 | 2641 | def write(self,data): |
|
2608 | 2642 | """Write a string to the default output""" |
|
2609 | 2643 | io.stdout.write(data) |
|
2610 | 2644 | |
|
2611 | 2645 | # TODO: This should be removed when Term is refactored. |
|
2612 | 2646 | def write_err(self,data): |
|
2613 | 2647 | """Write a string to the default error output""" |
|
2614 | 2648 | io.stderr.write(data) |
|
2615 | 2649 | |
|
2616 | 2650 | def ask_yes_no(self, prompt, default=None): |
|
2617 | 2651 | if self.quiet: |
|
2618 | 2652 | return True |
|
2619 | 2653 | return ask_yes_no(prompt,default) |
|
2620 | 2654 | |
|
2621 | 2655 | def show_usage(self): |
|
2622 | 2656 | """Show a usage message""" |
|
2623 | 2657 | page.page(IPython.core.usage.interactive_usage) |
|
2624 | 2658 | |
|
2625 | 2659 | def find_user_code(self, target, raw=True): |
|
2626 | 2660 | """Get a code string from history, file, or a string or macro. |
|
2627 | 2661 | |
|
2628 | 2662 | This is mainly used by magic functions. |
|
2629 | 2663 | |
|
2630 | 2664 | Parameters |
|
2631 | 2665 | ---------- |
|
2632 | 2666 | target : str |
|
2633 | 2667 | A string specifying code to retrieve. This will be tried respectively |
|
2634 | 2668 | as: ranges of input history (see %history for syntax), a filename, or |
|
2635 | 2669 | an expression evaluating to a string or Macro in the user namespace. |
|
2636 | 2670 | raw : bool |
|
2637 | 2671 | If true (default), retrieve raw history. Has no effect on the other |
|
2638 | 2672 | retrieval mechanisms. |
|
2639 | 2673 | |
|
2640 | 2674 | Returns |
|
2641 | 2675 | ------- |
|
2642 | 2676 | A string of code. |
|
2643 | 2677 | |
|
2644 | 2678 | ValueError is raised if nothing is found, and TypeError if it evaluates |
|
2645 | 2679 | to an object of another type. In each case, .args[0] is a printable |
|
2646 | 2680 | message. |
|
2647 | 2681 | """ |
|
2648 | 2682 | code = self.extract_input_lines(target, raw=raw) # Grab history |
|
2649 | 2683 | if code: |
|
2650 | 2684 | return code |
|
2651 | 2685 | if os.path.isfile(target): # Read file |
|
2652 | 2686 | return open(target, "r").read() |
|
2653 | 2687 | |
|
2654 | 2688 | try: # User namespace |
|
2655 | 2689 | codeobj = eval(target, self.user_ns) |
|
2656 | 2690 | except Exception: |
|
2657 | 2691 | raise ValueError(("'%s' was not found in history, as a file, nor in" |
|
2658 | 2692 | " the user namespace.") % target) |
|
2659 | 2693 | if isinstance(codeobj, basestring): |
|
2660 | 2694 | return codeobj |
|
2661 | 2695 | elif isinstance(codeobj, Macro): |
|
2662 | 2696 | return codeobj.value |
|
2663 | 2697 | |
|
2664 | 2698 | raise TypeError("%s is neither a string nor a macro." % target, |
|
2665 | 2699 | codeobj) |
|
2666 | 2700 | |
|
2667 | 2701 | #------------------------------------------------------------------------- |
|
2668 | 2702 | # Things related to IPython exiting |
|
2669 | 2703 | #------------------------------------------------------------------------- |
|
2670 | 2704 | def atexit_operations(self): |
|
2671 | 2705 | """This will be executed at the time of exit. |
|
2672 | 2706 | |
|
2673 | 2707 | Cleanup operations and saving of persistent data that is done |
|
2674 | 2708 | unconditionally by IPython should be performed here. |
|
2675 | 2709 | |
|
2676 | 2710 | For things that may depend on startup flags or platform specifics (such |
|
2677 | 2711 | as having readline or not), register a separate atexit function in the |
|
2678 | 2712 | code that has the appropriate information, rather than trying to |
|
2679 | 2713 | clutter |
|
2680 | 2714 | """ |
|
2681 | 2715 | # Close the history session (this stores the end time and line count) |
|
2682 | 2716 | # this must be *before* the tempfile cleanup, in case of temporary |
|
2683 | 2717 | # history db |
|
2684 | 2718 | self.history_manager.end_session() |
|
2685 | 2719 | |
|
2686 | 2720 | # Cleanup all tempfiles left around |
|
2687 | 2721 | for tfile in self.tempfiles: |
|
2688 | 2722 | try: |
|
2689 | 2723 | os.unlink(tfile) |
|
2690 | 2724 | except OSError: |
|
2691 | 2725 | pass |
|
2692 | 2726 | |
|
2693 | 2727 | # Clear all user namespaces to release all references cleanly. |
|
2694 | 2728 | self.reset(new_session=False) |
|
2695 | 2729 | |
|
2696 | 2730 | # Run user hooks |
|
2697 | 2731 | self.hooks.shutdown_hook() |
|
2698 | 2732 | |
|
2699 | 2733 | def cleanup(self): |
|
2700 | 2734 | self.restore_sys_module_state() |
|
2701 | 2735 | |
|
2702 | 2736 | |
|
2703 | 2737 | class InteractiveShellABC(object): |
|
2704 | 2738 | """An abstract base class for InteractiveShell.""" |
|
2705 | 2739 | __metaclass__ = abc.ABCMeta |
|
2706 | 2740 | |
|
2707 | 2741 | InteractiveShellABC.register(InteractiveShell) |
@@ -1,378 +1,396 b'' | |||
|
1 | 1 | # -*- coding: utf-8 -*- |
|
2 | 2 | """Classes for handling input/output prompts. |
|
3 | 3 | |
|
4 | 4 | Authors: |
|
5 | 5 | |
|
6 | 6 | * Fernando Perez |
|
7 | 7 | * Brian Granger |
|
8 | 8 | * Thomas Kluyver |
|
9 | 9 | """ |
|
10 | 10 | |
|
11 | 11 | #----------------------------------------------------------------------------- |
|
12 | 12 | # Copyright (C) 2008-2011 The IPython Development Team |
|
13 | 13 | # Copyright (C) 2001-2007 Fernando Perez <fperez@colorado.edu> |
|
14 | 14 | # |
|
15 | 15 | # Distributed under the terms of the BSD License. The full license is in |
|
16 | 16 | # the file COPYING, distributed as part of this software. |
|
17 | 17 | #----------------------------------------------------------------------------- |
|
18 | 18 | |
|
19 | 19 | #----------------------------------------------------------------------------- |
|
20 | 20 | # Imports |
|
21 | 21 | #----------------------------------------------------------------------------- |
|
22 | 22 | |
|
23 | 23 | import os |
|
24 | 24 | import re |
|
25 | 25 | import socket |
|
26 | 26 | import sys |
|
27 | 27 | import time |
|
28 | 28 | |
|
29 | 29 | from IPython.config.configurable import Configurable |
|
30 | 30 | from IPython.core import release |
|
31 | 31 | from IPython.utils import coloransi |
|
32 | 32 | from IPython.utils.traitlets import (Unicode, Instance, Dict, Bool, Int) |
|
33 | 33 | |
|
34 | 34 | #----------------------------------------------------------------------------- |
|
35 | 35 | # Color schemes for prompts |
|
36 | 36 | #----------------------------------------------------------------------------- |
|
37 | 37 | |
|
38 | 38 | InputColors = coloransi.InputTermColors # just a shorthand |
|
39 | 39 | Colors = coloransi.TermColors # just a shorthand |
|
40 | 40 | |
|
41 | 41 | color_lists = dict(normal=Colors(), inp=InputColors(), nocolor=coloransi.NoColors()) |
|
42 | 42 | |
|
43 | 43 | PColNoColors = coloransi.ColorScheme( |
|
44 | 44 | 'NoColor', |
|
45 | 45 | in_prompt = InputColors.NoColor, # Input prompt |
|
46 | 46 | in_number = InputColors.NoColor, # Input prompt number |
|
47 | 47 | in_prompt2 = InputColors.NoColor, # Continuation prompt |
|
48 | 48 | in_normal = InputColors.NoColor, # color off (usu. Colors.Normal) |
|
49 | 49 | |
|
50 | 50 | out_prompt = Colors.NoColor, # Output prompt |
|
51 | 51 | out_number = Colors.NoColor, # Output prompt number |
|
52 | 52 | |
|
53 | 53 | normal = Colors.NoColor # color off (usu. Colors.Normal) |
|
54 | 54 | ) |
|
55 | 55 | |
|
56 | 56 | # make some schemes as instances so we can copy them for modification easily: |
|
57 | 57 | PColLinux = coloransi.ColorScheme( |
|
58 | 58 | 'Linux', |
|
59 | 59 | in_prompt = InputColors.Green, |
|
60 | 60 | in_number = InputColors.LightGreen, |
|
61 | 61 | in_prompt2 = InputColors.Green, |
|
62 | 62 | in_normal = InputColors.Normal, # color off (usu. Colors.Normal) |
|
63 | 63 | |
|
64 | 64 | out_prompt = Colors.Red, |
|
65 | 65 | out_number = Colors.LightRed, |
|
66 | 66 | |
|
67 | 67 | normal = Colors.Normal |
|
68 | 68 | ) |
|
69 | 69 | |
|
70 | 70 | # Slightly modified Linux for light backgrounds |
|
71 | 71 | PColLightBG = PColLinux.copy('LightBG') |
|
72 | 72 | |
|
73 | 73 | PColLightBG.colors.update( |
|
74 | 74 | in_prompt = InputColors.Blue, |
|
75 | 75 | in_number = InputColors.LightBlue, |
|
76 | 76 | in_prompt2 = InputColors.Blue |
|
77 | 77 | ) |
|
78 | 78 | |
|
79 | 79 | #----------------------------------------------------------------------------- |
|
80 | 80 | # Utilities |
|
81 | 81 | #----------------------------------------------------------------------------- |
|
82 | 82 | |
|
83 | 83 | class LazyEvaluate(object): |
|
84 | 84 | """This is used for formatting strings with values that need to be updated |
|
85 | 85 | at that time, such as the current time or working directory.""" |
|
86 | 86 | def __init__(self, func, *args, **kwargs): |
|
87 | 87 | self.func = func |
|
88 | 88 | self.args = args |
|
89 | 89 | self.kwargs = kwargs |
|
90 | 90 | |
|
91 | 91 | def __call__(self, **kwargs): |
|
92 | 92 | self.kwargs.update(kwargs) |
|
93 | 93 | return self.func(*self.args, **self.kwargs) |
|
94 | 94 | |
|
95 | 95 | def __str__(self): |
|
96 | 96 | return str(self()) |
|
97 | 97 | |
|
98 | 98 | def multiple_replace(dict, text): |
|
99 | 99 | """ Replace in 'text' all occurences of any key in the given |
|
100 | 100 | dictionary by its corresponding value. Returns the new string.""" |
|
101 | 101 | |
|
102 | 102 | # Function by Xavier Defrang, originally found at: |
|
103 | 103 | # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81330 |
|
104 | 104 | |
|
105 | 105 | # Create a regular expression from the dictionary keys |
|
106 | 106 | regex = re.compile("(%s)" % "|".join(map(re.escape, dict.keys()))) |
|
107 | 107 | # For each match, look-up corresponding value in dictionary |
|
108 | 108 | return regex.sub(lambda mo: dict[mo.string[mo.start():mo.end()]], text) |
|
109 | 109 | |
|
110 | 110 | #----------------------------------------------------------------------------- |
|
111 | 111 | # Special characters that can be used in prompt templates, mainly bash-like |
|
112 | 112 | #----------------------------------------------------------------------------- |
|
113 | 113 | |
|
114 | 114 | # If $HOME isn't defined (Windows), make it an absurd string so that it can |
|
115 | 115 | # never be expanded out into '~'. Basically anything which can never be a |
|
116 | 116 | # reasonable directory name will do, we just want the $HOME -> '~' operation |
|
117 | 117 | # to become a no-op. We pre-compute $HOME here so it's not done on every |
|
118 | 118 | # prompt call. |
|
119 | 119 | |
|
120 | 120 | # FIXME: |
|
121 | 121 | |
|
122 | 122 | # - This should be turned into a class which does proper namespace management, |
|
123 | 123 | # since the prompt specials need to be evaluated in a certain namespace. |
|
124 | 124 | # Currently it's just globals, which need to be managed manually by code |
|
125 | 125 | # below. |
|
126 | 126 | |
|
127 | 127 | # - I also need to split up the color schemes from the prompt specials |
|
128 | 128 | # somehow. I don't have a clean design for that quite yet. |
|
129 | 129 | |
|
130 | 130 | HOME = os.environ.get("HOME","//////:::::ZZZZZ,,,~~~") |
|
131 | 131 | |
|
132 | 132 | # We precompute a few more strings here for the prompt_specials, which are |
|
133 | 133 | # fixed once ipython starts. This reduces the runtime overhead of computing |
|
134 | 134 | # prompt strings. |
|
135 | 135 | USER = os.environ.get("USER") |
|
136 | 136 | HOSTNAME = socket.gethostname() |
|
137 | 137 | HOSTNAME_SHORT = HOSTNAME.split(".")[0] |
|
138 | 138 | ROOT_SYMBOL = "#" if (os.name=='nt' or os.getuid()==0) else "$" |
|
139 | 139 | |
|
140 | 140 | prompt_abbreviations = { |
|
141 | 141 | # Prompt/history count |
|
142 | 142 | '%n' : '{color.number}' '{count}' '{color.prompt}', |
|
143 | 143 | r'\#': '{color.number}' '{count}' '{color.prompt}', |
|
144 | 144 | # Just the prompt counter number, WITHOUT any coloring wrappers, so users |
|
145 | 145 | # can get numbers displayed in whatever color they want. |
|
146 | 146 | r'\N': '{count}', |
|
147 | 147 | |
|
148 | 148 | # Prompt/history count, with the actual digits replaced by dots. Used |
|
149 | 149 | # mainly in continuation prompts (prompt_in2) |
|
150 | 150 | r'\D': '{dots}', |
|
151 | 151 | |
|
152 | 152 | # Current time |
|
153 | 153 | r'\T' : '{time}', |
|
154 | 154 | # Current working directory |
|
155 | 155 | r'\w': '{cwd}', |
|
156 | 156 | # Basename of current working directory. |
|
157 | 157 | # (use os.sep to make this portable across OSes) |
|
158 | 158 | r'\W' : '{cwd_last}', |
|
159 | 159 | # These X<N> are an extension to the normal bash prompts. They return |
|
160 | 160 | # N terms of the path, after replacing $HOME with '~' |
|
161 | 161 | r'\X0': '{cwd_x[0]}', |
|
162 | 162 | r'\X1': '{cwd_x[1]}', |
|
163 | 163 | r'\X2': '{cwd_x[2]}', |
|
164 | 164 | r'\X3': '{cwd_x[3]}', |
|
165 | 165 | r'\X4': '{cwd_x[4]}', |
|
166 | 166 | r'\X5': '{cwd_x[5]}', |
|
167 | 167 | # Y<N> are similar to X<N>, but they show '~' if it's the directory |
|
168 | 168 | # N+1 in the list. Somewhat like %cN in tcsh. |
|
169 | 169 | r'\Y0': '{cwd_y[0]}', |
|
170 | 170 | r'\Y1': '{cwd_y[1]}', |
|
171 | 171 | r'\Y2': '{cwd_y[2]}', |
|
172 | 172 | r'\Y3': '{cwd_y[3]}', |
|
173 | 173 | r'\Y4': '{cwd_y[4]}', |
|
174 | 174 | r'\Y5': '{cwd_y[5]}', |
|
175 | 175 | # Hostname up to first . |
|
176 | 176 | r'\h': HOSTNAME_SHORT, |
|
177 | 177 | # Full hostname |
|
178 | 178 | r'\H': HOSTNAME, |
|
179 | 179 | # Username of current user |
|
180 | 180 | r'\u': USER, |
|
181 | 181 | # Escaped '\' |
|
182 | 182 | '\\\\': '\\', |
|
183 | 183 | # Newline |
|
184 | 184 | r'\n': '\n', |
|
185 | 185 | # Carriage return |
|
186 | 186 | r'\r': '\r', |
|
187 | 187 | # Release version |
|
188 | 188 | r'\v': release.version, |
|
189 | 189 | # Root symbol ($ or #) |
|
190 | 190 | r'\$': ROOT_SYMBOL, |
|
191 | 191 | } |
|
192 | 192 | |
|
193 | 193 | #----------------------------------------------------------------------------- |
|
194 | 194 | # More utilities |
|
195 | 195 | #----------------------------------------------------------------------------- |
|
196 | 196 | |
|
197 | 197 | def cwd_filt(depth): |
|
198 | 198 | """Return the last depth elements of the current working directory. |
|
199 | 199 | |
|
200 | 200 | $HOME is always replaced with '~'. |
|
201 | 201 | If depth==0, the full path is returned.""" |
|
202 | 202 | |
|
203 | 203 | cwd = os.getcwd().replace(HOME,"~") |
|
204 | 204 | out = os.sep.join(cwd.split(os.sep)[-depth:]) |
|
205 | 205 | return out or os.sep |
|
206 | 206 | |
|
207 | 207 | def cwd_filt2(depth): |
|
208 | 208 | """Return the last depth elements of the current working directory. |
|
209 | 209 | |
|
210 | 210 | $HOME is always replaced with '~'. |
|
211 | 211 | If depth==0, the full path is returned.""" |
|
212 | 212 | |
|
213 | 213 | full_cwd = os.getcwd() |
|
214 | 214 | cwd = full_cwd.replace(HOME,"~").split(os.sep) |
|
215 | 215 | if '~' in cwd and len(cwd) == depth+1: |
|
216 | 216 | depth += 1 |
|
217 | 217 | drivepart = '' |
|
218 | 218 | if sys.platform == 'win32' and len(cwd) > depth: |
|
219 | 219 | drivepart = os.path.splitdrive(full_cwd)[0] |
|
220 | 220 | out = drivepart + '/'.join(cwd[-depth:]) |
|
221 | 221 | |
|
222 | 222 | return out or os.sep |
|
223 | 223 | |
|
224 | 224 | #----------------------------------------------------------------------------- |
|
225 | 225 | # Prompt classes |
|
226 | 226 | #----------------------------------------------------------------------------- |
|
227 | 227 | |
|
228 | 228 | lazily_evaluate = {'time': LazyEvaluate(time.strftime, "%H:%M:%S"), |
|
229 | 229 | 'cwd': LazyEvaluate(os.getcwd), |
|
230 | 230 | 'cwd_last': LazyEvaluate(lambda: os.getcwd().split(os.sep)[-1]), |
|
231 | 231 | 'cwd_x': [LazyEvaluate(lambda: os.getcwd().replace("%s","~"))] +\ |
|
232 | 232 | [LazyEvaluate(cwd_filt, x) for x in range(1,6)], |
|
233 | 233 | 'cwd_y': [LazyEvaluate(cwd_filt2, x) for x in range(6)] |
|
234 | 234 | } |
|
235 | 235 | |
|
236 | 236 | |
|
237 | 237 | class PromptManager(Configurable): |
|
238 | 238 | """This is the primary interface for producing IPython's prompts.""" |
|
239 | 239 | shell = Instance('IPython.core.interactiveshell.InteractiveShellABC') |
|
240 | 240 | |
|
241 | 241 | color_scheme_table = Instance(coloransi.ColorSchemeTable) |
|
242 | 242 | color_scheme = Unicode('Linux', config=True) |
|
243 | 243 | def _color_scheme_changed(self, name, new_value): |
|
244 | 244 | self.color_scheme_table.set_active_scheme(new_value) |
|
245 | 245 | for pname in ['in', 'in2', 'out', 'rewrite']: |
|
246 | 246 | # We need to recalculate the number of invisible characters |
|
247 | 247 | self.update_prompt(pname) |
|
248 | 248 | |
|
249 | 249 | lazy_evaluate_fields = Dict(help=""" |
|
250 | 250 | This maps field names used in the prompt templates to functions which |
|
251 | 251 | will be called when the prompt is rendered. This allows us to include |
|
252 | 252 | things like the current time in the prompts. Functions are only called |
|
253 | 253 | if they are used in the prompt. |
|
254 | 254 | """) |
|
255 | 255 | def _lazy_evaluate_fields_default(self): return lazily_evaluate.copy() |
|
256 | 256 | |
|
257 |
in_template = Unicode('In [\\#]: ', config=True |
|
|
258 | in2_template = Unicode(' .\\D.: ', config=True) | |
|
259 |
|
|
|
260 | rewrite_template = Unicode("------> ", config=True) | |
|
257 | in_template = Unicode('In [\\#]: ', config=True, | |
|
258 | help="Input prompt. '\\#' will be transformed to the prompt number") | |
|
259 | in2_template = Unicode(' .\\D.: ', config=True, | |
|
260 | help="Continuation prompt.") | |
|
261 | out_template = Unicode('Out[\\#]: ', config=True, | |
|
262 | help="Output prompt. '\\#' will be transformed to the prompt number") | |
|
261 | 263 | |
|
262 | 264 | justify = Bool(True, config=True, help=""" |
|
263 | 265 | If True (default), each prompt will be right-aligned with the |
|
264 | 266 | preceding one. |
|
265 | 267 | """) |
|
266 | 268 | |
|
267 | 269 | # We actually store the expanded templates here: |
|
268 | 270 | templates = Dict() |
|
269 | 271 | |
|
270 | 272 | # The number of characters in the last prompt rendered, not including |
|
271 | 273 | # colour characters. |
|
272 | 274 | width = Int() |
|
275 | txtwidth = Int() # Not including right-justification | |
|
273 | 276 | |
|
274 | 277 | # The number of characters in each prompt which don't contribute to width |
|
275 | 278 | invisible_chars = Dict() |
|
276 | 279 | def _invisible_chars_default(self): |
|
277 |
return {'in': 0, 'in2': 0, 'out': 0, 'rewrite': |
|
|
280 | return {'in': 0, 'in2': 0, 'out': 0, 'rewrite':0} | |
|
278 | 281 | |
|
279 | 282 | def __init__(self, shell, config=None): |
|
280 | 283 | super(PromptManager, self).__init__(shell=shell, config=config) |
|
281 | 284 | |
|
282 | 285 | # Prepare colour scheme table |
|
283 | 286 | self.color_scheme_table = coloransi.ColorSchemeTable([PColNoColors, |
|
284 | 287 | PColLinux, PColLightBG], self.color_scheme) |
|
285 | 288 | |
|
286 | # Prepare templates | |
|
289 | # Prepare templates & numbers of invisible characters | |
|
287 | 290 | self.update_prompt('in', self.in_template) |
|
288 | 291 | self.update_prompt('in2', self.in2_template) |
|
289 | 292 | self.update_prompt('out', self.out_template) |
|
290 |
self.update_prompt('rewrite' |
|
|
293 | self.update_prompt('rewrite') | |
|
291 | 294 | self.on_trait_change(self._update_prompt_trait, ['in_template', |
|
292 |
'in2_template', 'out_template' |
|
|
295 | 'in2_template', 'out_template']) | |
|
293 | 296 | |
|
294 | 297 | def update_prompt(self, name, new_template=None): |
|
295 | 298 | """This is called when a prompt template is updated. It processes |
|
296 | 299 | abbreviations used in the prompt template (like \#) and calculates how |
|
297 | 300 | many invisible characters (ANSI colour escapes) the resulting prompt |
|
298 | 301 | contains. |
|
299 | 302 | |
|
300 | 303 | It is also called for each prompt on changing the colour scheme. In both |
|
301 | 304 | cases, traitlets should take care of calling this automatically. |
|
302 | 305 | """ |
|
303 | 306 | if new_template is not None: |
|
304 | 307 | self.templates[name] = multiple_replace(prompt_abbreviations, new_template) |
|
305 |
invis_chars = len(self.render(name, color=True |
|
|
306 |
len(self.render(name, color=False |
|
|
308 | invis_chars = len(self._render(name, color=True)) - \ | |
|
309 | len(self._render(name, color=False)) | |
|
307 | 310 | self.invisible_chars[name] = invis_chars |
|
308 | 311 | |
|
309 | 312 | def _update_prompt_trait(self, traitname, new_template): |
|
310 | 313 | name = traitname[:-9] # Cut off '_template' |
|
311 | 314 | self.update_prompt(name, new_template) |
|
312 | 315 | |
|
313 |
def render(self, name, color=True, |
|
|
316 | def _render(self, name, color=True, **kwargs): | |
|
317 | """Render but don't justify, or update the width or txtwidth attributes. | |
|
314 | 318 |
|
|
315 | Render the selected prompt. | |
|
319 | if name == 'rewrite': | |
|
320 | return self._render_rewrite(color=color) | |
|
316 | 321 | |
|
317 | Parameters | |
|
318 | ---------- | |
|
319 | name : str | |
|
320 | Which prompt to render. One of 'in', 'in2', 'out', 'rewrite' | |
|
321 | color : bool | |
|
322 | If True (default), include ANSI escape sequences for a coloured prompt. | |
|
323 | just : bool | |
|
324 | If True, justify the prompt to the width of the last prompt. The | |
|
325 | default is stored in self.justify. | |
|
326 | **kwargs : | |
|
327 | Additional arguments will be passed to the string formatting operation, | |
|
328 | so they can override the values that would otherwise fill in the | |
|
329 | template. | |
|
330 | ||
|
331 | Returns | |
|
332 | ------- | |
|
333 | A string containing the rendered prompt. | |
|
334 | """ | |
|
335 | 322 | if color: |
|
336 | 323 | scheme = self.color_scheme_table.active_colors |
|
337 | 324 | if name=='out': |
|
338 | 325 | colors = color_lists['normal'] |
|
339 | 326 | colors.number, colors.prompt, colors.normal = \ |
|
340 | 327 | scheme.out_number, scheme.out_prompt, scheme.normal |
|
341 | elif name=='rewrite': | |
|
342 | colors = color_lists['normal'] | |
|
343 | # We need a non-input version of these escapes | |
|
344 | colors.number = scheme.in_number.replace("\001","").replace("\002","") | |
|
345 | colors.prompt = scheme.in_prompt.replace("\001","").replace("\002","") | |
|
346 | colors.normal = scheme.normal | |
|
347 | 328 | else: |
|
348 | 329 | colors = color_lists['inp'] |
|
349 | 330 | colors.number, colors.prompt, colors.normal = \ |
|
350 | 331 | scheme.in_number, scheme.in_prompt, scheme.in_normal |
|
351 | 332 | if name=='in2': |
|
352 | 333 | colors.prompt = scheme.in_prompt2 |
|
353 | 334 | else: |
|
354 | 335 | # No color |
|
355 | 336 | colors = color_lists['nocolor'] |
|
356 | 337 | colors.number, colors.prompt, colors.normal = '', '', '' |
|
357 | 338 | |
|
358 | 339 | count = self.shell.execution_count # Shorthand |
|
359 | 340 | # Build the dictionary to be passed to string formatting |
|
360 | 341 | fmtargs = dict(color=colors, count=count, |
|
361 |
dots="."*len(str(count)) |
|
|
342 | dots="."*len(str(count)), | |
|
343 | width=self.width, txtwidth=self.txtwidth ) | |
|
362 | 344 | fmtargs.update(self.lazy_evaluate_fields) |
|
363 | 345 | fmtargs.update(kwargs) |
|
364 | 346 | |
|
365 | 347 | # Prepare the prompt |
|
366 | 348 | prompt = colors.prompt + self.templates[name] + colors.normal |
|
367 | 349 | |
|
368 | 350 | # Fill in required fields |
|
369 |
re |
|
|
351 | return prompt.format(**fmtargs) | |
|
352 | ||
|
353 | def _render_rewrite(self, color=True): | |
|
354 | """Render the ---> rewrite prompt.""" | |
|
355 | if color: | |
|
356 | scheme = self.color_scheme_table.active_colors | |
|
357 | # We need a non-input version of these escapes | |
|
358 | color_prompt = scheme.in_prompt.replace("\001","").replace("\002","") | |
|
359 | color_normal = scheme.normal | |
|
360 | else: | |
|
361 | color_prompt, color_normal = '', '' | |
|
362 | ||
|
363 | return color_prompt + "-> ".rjust(self.txtwidth, "-") + color_normal | |
|
364 | ||
|
365 | def render(self, name, color=True, just=None, **kwargs): | |
|
366 | """ | |
|
367 | Render the selected prompt. | |
|
368 | ||
|
369 | Parameters | |
|
370 | ---------- | |
|
371 | name : str | |
|
372 | Which prompt to render. One of 'in', 'in2', 'out', 'rewrite' | |
|
373 | color : bool | |
|
374 | If True (default), include ANSI escape sequences for a coloured prompt. | |
|
375 | just : bool | |
|
376 | If True, justify the prompt to the width of the last prompt. The | |
|
377 | default is stored in self.justify. | |
|
378 | **kwargs : | |
|
379 | Additional arguments will be passed to the string formatting operation, | |
|
380 | so they can override the values that would otherwise fill in the | |
|
381 | template. | |
|
382 | ||
|
383 | Returns | |
|
384 | ------- | |
|
385 | A string containing the rendered prompt. | |
|
386 | """ | |
|
387 | res = self._render(name, color=color, **kwargs) | |
|
370 | 388 | |
|
371 | 389 | # Handle justification of prompt |
|
372 | 390 | invis_chars = self.invisible_chars[name] if color else 0 |
|
391 | self.txtwidth = len(res) - invis_chars | |
|
373 | 392 | just = self.justify if (just is None) else just |
|
374 | 393 | if just: |
|
375 | 394 | res = res.rjust(self.width + invis_chars) |
|
376 | 395 | self.width = len(res) - invis_chars |
|
377 | 396 | return res |
|
378 |
@@ -1,397 +1,399 b'' | |||
|
1 | 1 | #!/usr/bin/env python |
|
2 | 2 | # encoding: utf-8 |
|
3 | 3 | """ |
|
4 | 4 | The :class:`~IPython.core.application.Application` object for the command |
|
5 | 5 | line :command:`ipython` program. |
|
6 | 6 | |
|
7 | 7 | Authors |
|
8 | 8 | ------- |
|
9 | 9 | |
|
10 | 10 | * Brian Granger |
|
11 | 11 | * Fernando Perez |
|
12 | 12 | * Min Ragan-Kelley |
|
13 | 13 | """ |
|
14 | 14 | |
|
15 | 15 | #----------------------------------------------------------------------------- |
|
16 | 16 | # Copyright (C) 2008-2011 The IPython Development Team |
|
17 | 17 | # |
|
18 | 18 | # Distributed under the terms of the BSD License. The full license is in |
|
19 | 19 | # the file COPYING, distributed as part of this software. |
|
20 | 20 | #----------------------------------------------------------------------------- |
|
21 | 21 | |
|
22 | 22 | #----------------------------------------------------------------------------- |
|
23 | 23 | # Imports |
|
24 | 24 | #----------------------------------------------------------------------------- |
|
25 | 25 | |
|
26 | 26 | from __future__ import absolute_import |
|
27 | 27 | |
|
28 | 28 | import logging |
|
29 | 29 | import os |
|
30 | 30 | import sys |
|
31 | 31 | |
|
32 | 32 | from IPython.config.loader import ( |
|
33 | 33 | Config, PyFileConfigLoader, ConfigFileNotFound |
|
34 | 34 | ) |
|
35 | 35 | from IPython.config.application import boolean_flag, catch_config_error |
|
36 | 36 | from IPython.core import release |
|
37 | 37 | from IPython.core import usage |
|
38 | 38 | from IPython.core.completer import IPCompleter |
|
39 | 39 | from IPython.core.crashhandler import CrashHandler |
|
40 | 40 | from IPython.core.formatters import PlainTextFormatter |
|
41 | from IPython.core.prompts import PromptManager | |
|
41 | 42 | from IPython.core.application import ( |
|
42 | 43 | ProfileDir, BaseIPythonApplication, base_flags, base_aliases |
|
43 | 44 | ) |
|
44 | 45 | from IPython.core.shellapp import ( |
|
45 | 46 | InteractiveShellApp, shell_flags, shell_aliases |
|
46 | 47 | ) |
|
47 | 48 | from IPython.frontend.terminal.interactiveshell import TerminalInteractiveShell |
|
48 | 49 | from IPython.lib import inputhook |
|
49 | 50 | from IPython.utils import warn |
|
50 | 51 | from IPython.utils.path import get_ipython_dir, check_for_old_config |
|
51 | 52 | from IPython.utils.traitlets import ( |
|
52 | 53 | Bool, List, Dict, CaselessStrEnum |
|
53 | 54 | ) |
|
54 | 55 | |
|
55 | 56 | #----------------------------------------------------------------------------- |
|
56 | 57 | # Globals, utilities and helpers |
|
57 | 58 | #----------------------------------------------------------------------------- |
|
58 | 59 | |
|
59 | 60 | #: The default config file name for this application. |
|
60 | 61 | default_config_file_name = u'ipython_config.py' |
|
61 | 62 | |
|
62 | 63 | _examples = """ |
|
63 | 64 | ipython --pylab # start in pylab mode |
|
64 | 65 | ipython --pylab=qt # start in pylab mode with the qt4 backend |
|
65 | 66 | ipython --log-level=DEBUG # set logging to DEBUG |
|
66 | 67 | ipython --profile=foo # start with profile foo |
|
67 | 68 | |
|
68 | 69 | ipython qtconsole # start the qtconsole GUI application |
|
69 | 70 | ipython qtconsole -h # show the help string for the qtconsole subcmd |
|
70 | 71 | |
|
71 | 72 | ipython profile create foo # create profile foo w/ default config files |
|
72 | 73 | ipython profile -h # show the help string for the profile subcmd |
|
73 | 74 | """ |
|
74 | 75 | |
|
75 | 76 | #----------------------------------------------------------------------------- |
|
76 | 77 | # Crash handler for this application |
|
77 | 78 | #----------------------------------------------------------------------------- |
|
78 | 79 | |
|
79 | 80 | class IPAppCrashHandler(CrashHandler): |
|
80 | 81 | """sys.excepthook for IPython itself, leaves a detailed report on disk.""" |
|
81 | 82 | |
|
82 | 83 | def __init__(self, app): |
|
83 | 84 | contact_name = release.authors['Fernando'][0] |
|
84 | 85 | contact_email = release.author_email |
|
85 | 86 | bug_tracker = 'https://github.com/ipython/ipython/issues' |
|
86 | 87 | super(IPAppCrashHandler,self).__init__( |
|
87 | 88 | app, contact_name, contact_email, bug_tracker |
|
88 | 89 | ) |
|
89 | 90 | |
|
90 | 91 | def make_report(self,traceback): |
|
91 | 92 | """Return a string containing a crash report.""" |
|
92 | 93 | |
|
93 | 94 | sec_sep = self.section_sep |
|
94 | 95 | # Start with parent report |
|
95 | 96 | report = [super(IPAppCrashHandler, self).make_report(traceback)] |
|
96 | 97 | # Add interactive-specific info we may have |
|
97 | 98 | rpt_add = report.append |
|
98 | 99 | try: |
|
99 | 100 | rpt_add(sec_sep+"History of session input:") |
|
100 | 101 | for line in self.app.shell.user_ns['_ih']: |
|
101 | 102 | rpt_add(line) |
|
102 | 103 | rpt_add('\n*** Last line of input (may not be in above history):\n') |
|
103 | 104 | rpt_add(self.app.shell._last_input_line+'\n') |
|
104 | 105 | except: |
|
105 | 106 | pass |
|
106 | 107 | |
|
107 | 108 | return ''.join(report) |
|
108 | 109 | |
|
109 | 110 | #----------------------------------------------------------------------------- |
|
110 | 111 | # Aliases and Flags |
|
111 | 112 | #----------------------------------------------------------------------------- |
|
112 | 113 | flags = dict(base_flags) |
|
113 | 114 | flags.update(shell_flags) |
|
114 | 115 | addflag = lambda *args: flags.update(boolean_flag(*args)) |
|
115 | 116 | addflag('autoedit-syntax', 'TerminalInteractiveShell.autoedit_syntax', |
|
116 | 117 | 'Turn on auto editing of files with syntax errors.', |
|
117 | 118 | 'Turn off auto editing of files with syntax errors.' |
|
118 | 119 | ) |
|
119 | 120 | addflag('banner', 'TerminalIPythonApp.display_banner', |
|
120 | 121 | "Display a banner upon starting IPython.", |
|
121 | 122 | "Don't display a banner upon starting IPython." |
|
122 | 123 | ) |
|
123 | 124 | addflag('confirm-exit', 'TerminalInteractiveShell.confirm_exit', |
|
124 | 125 | """Set to confirm when you try to exit IPython with an EOF (Control-D |
|
125 | 126 | in Unix, Control-Z/Enter in Windows). By typing 'exit' or 'quit', |
|
126 | 127 | you can force a direct exit without any confirmation.""", |
|
127 | 128 | "Don't prompt the user when exiting." |
|
128 | 129 | ) |
|
129 | 130 | addflag('term-title', 'TerminalInteractiveShell.term_title', |
|
130 | 131 | "Enable auto setting the terminal title.", |
|
131 | 132 | "Disable auto setting the terminal title." |
|
132 | 133 | ) |
|
133 | 134 | classic_config = Config() |
|
134 | 135 | classic_config.InteractiveShell.cache_size = 0 |
|
135 | 136 | classic_config.PlainTextFormatter.pprint = False |
|
136 |
classic_config. |
|
|
137 |
classic_config. |
|
|
138 |
classic_config. |
|
|
137 | classic_config.PromptManager.in_template = '>>> ' | |
|
138 | classic_config.PromptManager.in2_template = '... ' | |
|
139 | classic_config.PromptManager.out_template = '' | |
|
139 | 140 | classic_config.InteractiveShell.separate_in = '' |
|
140 | 141 | classic_config.InteractiveShell.separate_out = '' |
|
141 | 142 | classic_config.InteractiveShell.separate_out2 = '' |
|
142 | 143 | classic_config.InteractiveShell.colors = 'NoColor' |
|
143 | 144 | classic_config.InteractiveShell.xmode = 'Plain' |
|
144 | 145 | |
|
145 | 146 | flags['classic']=( |
|
146 | 147 | classic_config, |
|
147 | 148 | "Gives IPython a similar feel to the classic Python prompt." |
|
148 | 149 | ) |
|
149 | 150 | # # log doesn't make so much sense this way anymore |
|
150 | 151 | # paa('--log','-l', |
|
151 | 152 | # action='store_true', dest='InteractiveShell.logstart', |
|
152 | 153 | # help="Start logging to the default log file (./ipython_log.py).") |
|
153 | 154 | # |
|
154 | 155 | # # quick is harder to implement |
|
155 | 156 | flags['quick']=( |
|
156 | 157 | {'TerminalIPythonApp' : {'quick' : True}}, |
|
157 | 158 | "Enable quick startup with no config files." |
|
158 | 159 | ) |
|
159 | 160 | |
|
160 | 161 | flags['i'] = ( |
|
161 | 162 | {'TerminalIPythonApp' : {'force_interact' : True}}, |
|
162 | 163 | """If running code from the command line, become interactive afterwards. |
|
163 | 164 | Note: can also be given simply as '-i.'""" |
|
164 | 165 | ) |
|
165 | 166 | flags['pylab'] = ( |
|
166 | 167 | {'TerminalIPythonApp' : {'pylab' : 'auto'}}, |
|
167 | 168 | """Pre-load matplotlib and numpy for interactive use with |
|
168 | 169 | the default matplotlib backend.""" |
|
169 | 170 | ) |
|
170 | 171 | |
|
171 | 172 | aliases = dict(base_aliases) |
|
172 | 173 | aliases.update(shell_aliases) |
|
173 | 174 | |
|
174 | 175 | # it's possible we don't want short aliases for *all* of these: |
|
175 | 176 | aliases.update(dict( |
|
176 | 177 | gui='TerminalIPythonApp.gui', |
|
177 | 178 | pylab='TerminalIPythonApp.pylab', |
|
178 | 179 | )) |
|
179 | 180 | |
|
180 | 181 | #----------------------------------------------------------------------------- |
|
181 | 182 | # Main classes and functions |
|
182 | 183 | #----------------------------------------------------------------------------- |
|
183 | 184 | |
|
184 | 185 | class TerminalIPythonApp(BaseIPythonApplication, InteractiveShellApp): |
|
185 | 186 | name = u'ipython' |
|
186 | 187 | description = usage.cl_usage |
|
187 | 188 | default_config_file_name = default_config_file_name |
|
188 | 189 | crash_handler_class = IPAppCrashHandler |
|
189 | 190 | examples = _examples |
|
190 | 191 | |
|
191 | 192 | flags = Dict(flags) |
|
192 | 193 | aliases = Dict(aliases) |
|
193 | 194 | classes = List() |
|
194 | 195 | def _classes_default(self): |
|
195 | 196 | """This has to be in a method, for TerminalIPythonApp to be available.""" |
|
196 | 197 | return [ |
|
197 | 198 | InteractiveShellApp, # ShellApp comes before TerminalApp, because |
|
198 | 199 | self.__class__, # it will also affect subclasses (e.g. QtConsole) |
|
199 | 200 | TerminalInteractiveShell, |
|
201 | PromptManager, | |
|
200 | 202 | ProfileDir, |
|
201 | 203 | PlainTextFormatter, |
|
202 | 204 | IPCompleter, |
|
203 | 205 | ] |
|
204 | 206 | |
|
205 | 207 | subcommands = Dict(dict( |
|
206 | 208 | qtconsole=('IPython.frontend.qt.console.qtconsoleapp.IPythonQtConsoleApp', |
|
207 | 209 | """Launch the IPython Qt Console.""" |
|
208 | 210 | ), |
|
209 | 211 | notebook=('IPython.frontend.html.notebook.notebookapp.NotebookApp', |
|
210 | 212 | """Launch the IPython HTML Notebook Server""" |
|
211 | 213 | ), |
|
212 | 214 | profile = ("IPython.core.profileapp.ProfileApp", |
|
213 | 215 | "Create and manage IPython profiles." |
|
214 | 216 | ), |
|
215 | 217 | kernel = ("IPython.zmq.ipkernel.IPKernelApp", |
|
216 | 218 | "Start a kernel without an attached frontend." |
|
217 | 219 | ), |
|
218 | 220 | )) |
|
219 | 221 | |
|
220 | 222 | # *do* autocreate requested profile, but don't create the config file. |
|
221 | 223 | auto_create=Bool(True) |
|
222 | 224 | # configurables |
|
223 | 225 | ignore_old_config=Bool(False, config=True, |
|
224 | 226 | help="Suppress warning messages about legacy config files" |
|
225 | 227 | ) |
|
226 | 228 | quick = Bool(False, config=True, |
|
227 | 229 | help="""Start IPython quickly by skipping the loading of config files.""" |
|
228 | 230 | ) |
|
229 | 231 | def _quick_changed(self, name, old, new): |
|
230 | 232 | if new: |
|
231 | 233 | self.load_config_file = lambda *a, **kw: None |
|
232 | 234 | self.ignore_old_config=True |
|
233 | 235 | |
|
234 | 236 | gui = CaselessStrEnum(('qt', 'wx', 'gtk', 'glut', 'pyglet'), config=True, |
|
235 | 237 | help="Enable GUI event loop integration ('qt', 'wx', 'gtk', 'glut', 'pyglet')." |
|
236 | 238 | ) |
|
237 | 239 | pylab = CaselessStrEnum(['tk', 'qt', 'wx', 'gtk', 'osx', 'auto'], |
|
238 | 240 | config=True, |
|
239 | 241 | help="""Pre-load matplotlib and numpy for interactive use, |
|
240 | 242 | selecting a particular matplotlib backend and loop integration. |
|
241 | 243 | """ |
|
242 | 244 | ) |
|
243 | 245 | display_banner = Bool(True, config=True, |
|
244 | 246 | help="Whether to display a banner upon starting IPython." |
|
245 | 247 | ) |
|
246 | 248 | |
|
247 | 249 | # if there is code of files to run from the cmd line, don't interact |
|
248 | 250 | # unless the --i flag (App.force_interact) is true. |
|
249 | 251 | force_interact = Bool(False, config=True, |
|
250 | 252 | help="""If a command or file is given via the command-line, |
|
251 | 253 | e.g. 'ipython foo.py""" |
|
252 | 254 | ) |
|
253 | 255 | def _force_interact_changed(self, name, old, new): |
|
254 | 256 | if new: |
|
255 | 257 | self.interact = True |
|
256 | 258 | |
|
257 | 259 | def _file_to_run_changed(self, name, old, new): |
|
258 | 260 | if new and not self.force_interact: |
|
259 | 261 | self.interact = False |
|
260 | 262 | _code_to_run_changed = _file_to_run_changed |
|
261 | 263 | |
|
262 | 264 | # internal, not-configurable |
|
263 | 265 | interact=Bool(True) |
|
264 | 266 | |
|
265 | 267 | |
|
266 | 268 | def parse_command_line(self, argv=None): |
|
267 | 269 | """override to allow old '-pylab' flag with deprecation warning""" |
|
268 | 270 | |
|
269 | 271 | argv = sys.argv[1:] if argv is None else argv |
|
270 | 272 | |
|
271 | 273 | if '-pylab' in argv: |
|
272 | 274 | # deprecated `-pylab` given, |
|
273 | 275 | # warn and transform into current syntax |
|
274 | 276 | argv = argv[:] # copy, don't clobber |
|
275 | 277 | idx = argv.index('-pylab') |
|
276 | 278 | warn.warn("`-pylab` flag has been deprecated.\n" |
|
277 | 279 | " Use `--pylab` instead, or `--pylab=foo` to specify a backend.") |
|
278 | 280 | sub = '--pylab' |
|
279 | 281 | if len(argv) > idx+1: |
|
280 | 282 | # check for gui arg, as in '-pylab qt' |
|
281 | 283 | gui = argv[idx+1] |
|
282 | 284 | if gui in ('wx', 'qt', 'qt4', 'gtk', 'auto'): |
|
283 | 285 | sub = '--pylab='+gui |
|
284 | 286 | argv.pop(idx+1) |
|
285 | 287 | argv[idx] = sub |
|
286 | 288 | |
|
287 | 289 | return super(TerminalIPythonApp, self).parse_command_line(argv) |
|
288 | 290 | |
|
289 | 291 | @catch_config_error |
|
290 | 292 | def initialize(self, argv=None): |
|
291 | 293 | """Do actions after construct, but before starting the app.""" |
|
292 | 294 | super(TerminalIPythonApp, self).initialize(argv) |
|
293 | 295 | if self.subapp is not None: |
|
294 | 296 | # don't bother initializing further, starting subapp |
|
295 | 297 | return |
|
296 | 298 | if not self.ignore_old_config: |
|
297 | 299 | check_for_old_config(self.ipython_dir) |
|
298 | 300 | # print self.extra_args |
|
299 | 301 | if self.extra_args: |
|
300 | 302 | self.file_to_run = self.extra_args[0] |
|
301 | 303 | # create the shell |
|
302 | 304 | self.init_shell() |
|
303 | 305 | # and draw the banner |
|
304 | 306 | self.init_banner() |
|
305 | 307 | # Now a variety of things that happen after the banner is printed. |
|
306 | 308 | self.init_gui_pylab() |
|
307 | 309 | self.init_extensions() |
|
308 | 310 | self.init_code() |
|
309 | 311 | |
|
310 | 312 | def init_shell(self): |
|
311 | 313 | """initialize the InteractiveShell instance""" |
|
312 | 314 | # I am a little hesitant to put these into InteractiveShell itself. |
|
313 | 315 | # But that might be the place for them |
|
314 | 316 | sys.path.insert(0, '') |
|
315 | 317 | |
|
316 | 318 | # Create an InteractiveShell instance. |
|
317 | 319 | # shell.display_banner should always be False for the terminal |
|
318 | 320 | # based app, because we call shell.show_banner() by hand below |
|
319 | 321 | # so the banner shows *before* all extension loading stuff. |
|
320 | 322 | self.shell = TerminalInteractiveShell.instance(config=self.config, |
|
321 | 323 | display_banner=False, profile_dir=self.profile_dir, |
|
322 | 324 | ipython_dir=self.ipython_dir) |
|
323 | 325 | self.shell.configurables.append(self) |
|
324 | 326 | |
|
325 | 327 | def init_banner(self): |
|
326 | 328 | """optionally display the banner""" |
|
327 | 329 | if self.display_banner and self.interact: |
|
328 | 330 | self.shell.show_banner() |
|
329 | 331 | # Make sure there is a space below the banner. |
|
330 | 332 | if self.log_level <= logging.INFO: print |
|
331 | 333 | |
|
332 | 334 | |
|
333 | 335 | def init_gui_pylab(self): |
|
334 | 336 | """Enable GUI event loop integration, taking pylab into account.""" |
|
335 | 337 | gui = self.gui |
|
336 | 338 | |
|
337 | 339 | # Using `pylab` will also require gui activation, though which toolkit |
|
338 | 340 | # to use may be chosen automatically based on mpl configuration. |
|
339 | 341 | if self.pylab: |
|
340 | 342 | activate = self.shell.enable_pylab |
|
341 | 343 | if self.pylab == 'auto': |
|
342 | 344 | gui = None |
|
343 | 345 | else: |
|
344 | 346 | gui = self.pylab |
|
345 | 347 | else: |
|
346 | 348 | # Enable only GUI integration, no pylab |
|
347 | 349 | activate = inputhook.enable_gui |
|
348 | 350 | |
|
349 | 351 | if gui or self.pylab: |
|
350 | 352 | try: |
|
351 | 353 | self.log.info("Enabling GUI event loop integration, " |
|
352 | 354 | "toolkit=%s, pylab=%s" % (gui, self.pylab) ) |
|
353 | 355 | if self.pylab: |
|
354 | 356 | activate(gui, import_all=self.pylab_import_all) |
|
355 | 357 | else: |
|
356 | 358 | activate(gui) |
|
357 | 359 | except: |
|
358 | 360 | self.log.warn("Error in enabling GUI event loop integration:") |
|
359 | 361 | self.shell.showtraceback() |
|
360 | 362 | |
|
361 | 363 | def start(self): |
|
362 | 364 | if self.subapp is not None: |
|
363 | 365 | return self.subapp.start() |
|
364 | 366 | # perform any prexec steps: |
|
365 | 367 | if self.interact: |
|
366 | 368 | self.log.debug("Starting IPython's mainloop...") |
|
367 | 369 | self.shell.mainloop() |
|
368 | 370 | else: |
|
369 | 371 | self.log.debug("IPython not interactive...") |
|
370 | 372 | |
|
371 | 373 | |
|
372 | 374 | def load_default_config(ipython_dir=None): |
|
373 | 375 | """Load the default config file from the default ipython_dir. |
|
374 | 376 | |
|
375 | 377 | This is useful for embedded shells. |
|
376 | 378 | """ |
|
377 | 379 | if ipython_dir is None: |
|
378 | 380 | ipython_dir = get_ipython_dir() |
|
379 | 381 | profile_dir = os.path.join(ipython_dir, 'profile_default') |
|
380 | 382 | cl = PyFileConfigLoader(default_config_file_name, profile_dir) |
|
381 | 383 | try: |
|
382 | 384 | config = cl.load_config() |
|
383 | 385 | except ConfigFileNotFound: |
|
384 | 386 | # no config found |
|
385 | 387 | config = Config() |
|
386 | 388 | return config |
|
387 | 389 | |
|
388 | 390 | |
|
389 | 391 | def launch_new_instance(): |
|
390 | 392 | """Create and run a full blown IPython instance""" |
|
391 | 393 | app = TerminalIPythonApp.instance() |
|
392 | 394 | app.initialize() |
|
393 | 395 | app.start() |
|
394 | 396 | |
|
395 | 397 | |
|
396 | 398 | if __name__ == '__main__': |
|
397 | 399 | launch_new_instance() |
@@ -1,402 +1,402 b'' | |||
|
1 | 1 | """Generic testing tools that do NOT depend on Twisted. |
|
2 | 2 | |
|
3 | 3 | In particular, this module exposes a set of top-level assert* functions that |
|
4 | 4 | can be used in place of nose.tools.assert* in method generators (the ones in |
|
5 | 5 | nose can not, at least as of nose 0.10.4). |
|
6 | 6 | |
|
7 | 7 | Note: our testing package contains testing.util, which does depend on Twisted |
|
8 | 8 | and provides utilities for tests that manage Deferreds. All testing support |
|
9 | 9 | tools that only depend on nose, IPython or the standard library should go here |
|
10 | 10 | instead. |
|
11 | 11 | |
|
12 | 12 | |
|
13 | 13 | Authors |
|
14 | 14 | ------- |
|
15 | 15 | - Fernando Perez <Fernando.Perez@berkeley.edu> |
|
16 | 16 | """ |
|
17 | 17 | |
|
18 | 18 | from __future__ import absolute_import |
|
19 | 19 | |
|
20 | 20 | #----------------------------------------------------------------------------- |
|
21 | 21 | # Copyright (C) 2009-2011 The IPython Development Team |
|
22 | 22 | # |
|
23 | 23 | # Distributed under the terms of the BSD License. The full license is in |
|
24 | 24 | # the file COPYING, distributed as part of this software. |
|
25 | 25 | #----------------------------------------------------------------------------- |
|
26 | 26 | |
|
27 | 27 | #----------------------------------------------------------------------------- |
|
28 | 28 | # Imports |
|
29 | 29 | #----------------------------------------------------------------------------- |
|
30 | 30 | |
|
31 | 31 | import os |
|
32 | 32 | import re |
|
33 | 33 | import sys |
|
34 | 34 | import tempfile |
|
35 | 35 | |
|
36 | 36 | from contextlib import contextmanager |
|
37 | 37 | from io import StringIO |
|
38 | 38 | |
|
39 | 39 | try: |
|
40 | 40 | # These tools are used by parts of the runtime, so we make the nose |
|
41 | 41 | # dependency optional at this point. Nose is a hard dependency to run the |
|
42 | 42 | # test suite, but NOT to use ipython itself. |
|
43 | 43 | import nose.tools as nt |
|
44 | 44 | has_nose = True |
|
45 | 45 | except ImportError: |
|
46 | 46 | has_nose = False |
|
47 | 47 | |
|
48 | 48 | from IPython.config.loader import Config |
|
49 | 49 | from IPython.utils.process import find_cmd, getoutputerror |
|
50 | 50 | from IPython.utils.text import list_strings, getdefaultencoding |
|
51 | 51 | from IPython.utils.io import temp_pyfile, Tee |
|
52 | 52 | from IPython.utils import py3compat |
|
53 | 53 | |
|
54 | 54 | from . import decorators as dec |
|
55 | 55 | from . import skipdoctest |
|
56 | 56 | |
|
57 | 57 | #----------------------------------------------------------------------------- |
|
58 | 58 | # Globals |
|
59 | 59 | #----------------------------------------------------------------------------- |
|
60 | 60 | |
|
61 | 61 | # Make a bunch of nose.tools assert wrappers that can be used in test |
|
62 | 62 | # generators. This will expose an assert* function for each one in nose.tools. |
|
63 | 63 | |
|
64 | 64 | _tpl = """ |
|
65 | 65 | def %(name)s(*a,**kw): |
|
66 | 66 | return nt.%(name)s(*a,**kw) |
|
67 | 67 | """ |
|
68 | 68 | |
|
69 | 69 | if has_nose: |
|
70 | 70 | for _x in [a for a in dir(nt) if a.startswith('assert')]: |
|
71 | 71 | exec _tpl % dict(name=_x) |
|
72 | 72 | |
|
73 | 73 | #----------------------------------------------------------------------------- |
|
74 | 74 | # Functions and classes |
|
75 | 75 | #----------------------------------------------------------------------------- |
|
76 | 76 | |
|
77 | 77 | # The docstring for full_path doctests differently on win32 (different path |
|
78 | 78 | # separator) so just skip the doctest there. The example remains informative. |
|
79 | 79 | doctest_deco = skipdoctest.skip_doctest if sys.platform == 'win32' else dec.null_deco |
|
80 | 80 | |
|
81 | 81 | @doctest_deco |
|
82 | 82 | def full_path(startPath,files): |
|
83 | 83 | """Make full paths for all the listed files, based on startPath. |
|
84 | 84 | |
|
85 | 85 | Only the base part of startPath is kept, since this routine is typically |
|
86 | 86 | used with a script's __file__ variable as startPath. The base of startPath |
|
87 | 87 | is then prepended to all the listed files, forming the output list. |
|
88 | 88 | |
|
89 | 89 | Parameters |
|
90 | 90 | ---------- |
|
91 | 91 | startPath : string |
|
92 | 92 | Initial path to use as the base for the results. This path is split |
|
93 | 93 | using os.path.split() and only its first component is kept. |
|
94 | 94 | |
|
95 | 95 | files : string or list |
|
96 | 96 | One or more files. |
|
97 | 97 | |
|
98 | 98 | Examples |
|
99 | 99 | -------- |
|
100 | 100 | |
|
101 | 101 | >>> full_path('/foo/bar.py',['a.txt','b.txt']) |
|
102 | 102 | ['/foo/a.txt', '/foo/b.txt'] |
|
103 | 103 | |
|
104 | 104 | >>> full_path('/foo',['a.txt','b.txt']) |
|
105 | 105 | ['/a.txt', '/b.txt'] |
|
106 | 106 | |
|
107 | 107 | If a single file is given, the output is still a list: |
|
108 | 108 | >>> full_path('/foo','a.txt') |
|
109 | 109 | ['/a.txt'] |
|
110 | 110 | """ |
|
111 | 111 | |
|
112 | 112 | files = list_strings(files) |
|
113 | 113 | base = os.path.split(startPath)[0] |
|
114 | 114 | return [ os.path.join(base,f) for f in files ] |
|
115 | 115 | |
|
116 | 116 | |
|
117 | 117 | def parse_test_output(txt): |
|
118 | 118 | """Parse the output of a test run and return errors, failures. |
|
119 | 119 | |
|
120 | 120 | Parameters |
|
121 | 121 | ---------- |
|
122 | 122 | txt : str |
|
123 | 123 | Text output of a test run, assumed to contain a line of one of the |
|
124 | 124 | following forms:: |
|
125 | 125 | 'FAILED (errors=1)' |
|
126 | 126 | 'FAILED (failures=1)' |
|
127 | 127 | 'FAILED (errors=1, failures=1)' |
|
128 | 128 | |
|
129 | 129 | Returns |
|
130 | 130 | ------- |
|
131 | 131 | nerr, nfail: number of errors and failures. |
|
132 | 132 | """ |
|
133 | 133 | |
|
134 | 134 | err_m = re.search(r'^FAILED \(errors=(\d+)\)', txt, re.MULTILINE) |
|
135 | 135 | if err_m: |
|
136 | 136 | nerr = int(err_m.group(1)) |
|
137 | 137 | nfail = 0 |
|
138 | 138 | return nerr, nfail |
|
139 | 139 | |
|
140 | 140 | fail_m = re.search(r'^FAILED \(failures=(\d+)\)', txt, re.MULTILINE) |
|
141 | 141 | if fail_m: |
|
142 | 142 | nerr = 0 |
|
143 | 143 | nfail = int(fail_m.group(1)) |
|
144 | 144 | return nerr, nfail |
|
145 | 145 | |
|
146 | 146 | both_m = re.search(r'^FAILED \(errors=(\d+), failures=(\d+)\)', txt, |
|
147 | 147 | re.MULTILINE) |
|
148 | 148 | if both_m: |
|
149 | 149 | nerr = int(both_m.group(1)) |
|
150 | 150 | nfail = int(both_m.group(2)) |
|
151 | 151 | return nerr, nfail |
|
152 | 152 | |
|
153 | 153 | # If the input didn't match any of these forms, assume no error/failures |
|
154 | 154 | return 0, 0 |
|
155 | 155 | |
|
156 | 156 | |
|
157 | 157 | # So nose doesn't think this is a test |
|
158 | 158 | parse_test_output.__test__ = False |
|
159 | 159 | |
|
160 | 160 | |
|
161 | 161 | def default_argv(): |
|
162 | 162 | """Return a valid default argv for creating testing instances of ipython""" |
|
163 | 163 | |
|
164 | 164 | return ['--quick', # so no config file is loaded |
|
165 | 165 | # Other defaults to minimize side effects on stdout |
|
166 | 166 | '--colors=NoColor', '--no-term-title','--no-banner', |
|
167 | 167 | '--autocall=0'] |
|
168 | 168 | |
|
169 | 169 | |
|
170 | 170 | def default_config(): |
|
171 | 171 | """Return a config object with good defaults for testing.""" |
|
172 | 172 | config = Config() |
|
173 | 173 | config.TerminalInteractiveShell.colors = 'NoColor' |
|
174 | 174 | config.TerminalTerminalInteractiveShell.term_title = False, |
|
175 | 175 | config.TerminalInteractiveShell.autocall = 0 |
|
176 | 176 | config.HistoryManager.hist_file = tempfile.mktemp(u'test_hist.sqlite') |
|
177 | 177 | config.HistoryManager.db_cache_size = 10000 |
|
178 | 178 | return config |
|
179 | 179 | |
|
180 | 180 | |
|
181 | 181 | def ipexec(fname, options=None): |
|
182 | 182 | """Utility to call 'ipython filename'. |
|
183 | 183 | |
|
184 | 184 | Starts IPython witha minimal and safe configuration to make startup as fast |
|
185 | 185 | as possible. |
|
186 | 186 | |
|
187 | 187 | Note that this starts IPython in a subprocess! |
|
188 | 188 | |
|
189 | 189 | Parameters |
|
190 | 190 | ---------- |
|
191 | 191 | fname : str |
|
192 | 192 | Name of file to be executed (should have .py or .ipy extension). |
|
193 | 193 | |
|
194 | 194 | options : optional, list |
|
195 | 195 | Extra command-line flags to be passed to IPython. |
|
196 | 196 | |
|
197 | 197 | Returns |
|
198 | 198 | ------- |
|
199 | 199 | (stdout, stderr) of ipython subprocess. |
|
200 | 200 | """ |
|
201 | 201 | if options is None: options = [] |
|
202 | 202 | |
|
203 | 203 | # For these subprocess calls, eliminate all prompt printing so we only see |
|
204 | 204 | # output from script execution |
|
205 |
prompt_opts = [ '-- |
|
|
206 |
'-- |
|
|
207 |
'-- |
|
|
205 | prompt_opts = [ '--PromptManager.in_template=""', | |
|
206 | '--PromptManager.in2_template=""', | |
|
207 | '--PromptManager.out_template=""' | |
|
208 | 208 | ] |
|
209 | 209 | cmdargs = ' '.join(default_argv() + prompt_opts + options) |
|
210 | 210 | |
|
211 | 211 | _ip = get_ipython() |
|
212 | 212 | test_dir = os.path.dirname(__file__) |
|
213 | 213 | |
|
214 | 214 | ipython_cmd = find_cmd('ipython3' if py3compat.PY3 else 'ipython') |
|
215 | 215 | # Absolute path for filename |
|
216 | 216 | full_fname = os.path.join(test_dir, fname) |
|
217 | 217 | full_cmd = '%s %s %s' % (ipython_cmd, cmdargs, full_fname) |
|
218 | 218 | #print >> sys.stderr, 'FULL CMD:', full_cmd # dbg |
|
219 | 219 | out = getoutputerror(full_cmd) |
|
220 | 220 | # `import readline` causes 'ESC[?1034h' to be the first output sometimes, |
|
221 | 221 | # so strip that off the front of the first line if it is found |
|
222 | 222 | if out: |
|
223 | 223 | first = out[0] |
|
224 | 224 | m = re.match(r'\x1b\[[^h]+h', first) |
|
225 | 225 | if m: |
|
226 | 226 | # strip initial readline escape |
|
227 | 227 | out = list(out) |
|
228 | 228 | out[0] = first[len(m.group()):] |
|
229 | 229 | out = tuple(out) |
|
230 | 230 | return out |
|
231 | 231 | |
|
232 | 232 | |
|
233 | 233 | def ipexec_validate(fname, expected_out, expected_err='', |
|
234 | 234 | options=None): |
|
235 | 235 | """Utility to call 'ipython filename' and validate output/error. |
|
236 | 236 | |
|
237 | 237 | This function raises an AssertionError if the validation fails. |
|
238 | 238 | |
|
239 | 239 | Note that this starts IPython in a subprocess! |
|
240 | 240 | |
|
241 | 241 | Parameters |
|
242 | 242 | ---------- |
|
243 | 243 | fname : str |
|
244 | 244 | Name of the file to be executed (should have .py or .ipy extension). |
|
245 | 245 | |
|
246 | 246 | expected_out : str |
|
247 | 247 | Expected stdout of the process. |
|
248 | 248 | |
|
249 | 249 | expected_err : optional, str |
|
250 | 250 | Expected stderr of the process. |
|
251 | 251 | |
|
252 | 252 | options : optional, list |
|
253 | 253 | Extra command-line flags to be passed to IPython. |
|
254 | 254 | |
|
255 | 255 | Returns |
|
256 | 256 | ------- |
|
257 | 257 | None |
|
258 | 258 | """ |
|
259 | 259 | |
|
260 | 260 | import nose.tools as nt |
|
261 | 261 | |
|
262 | 262 | out, err = ipexec(fname, options) |
|
263 | 263 | #print 'OUT', out # dbg |
|
264 | 264 | #print 'ERR', err # dbg |
|
265 | 265 | # If there are any errors, we must check those befor stdout, as they may be |
|
266 | 266 | # more informative than simply having an empty stdout. |
|
267 | 267 | if err: |
|
268 | 268 | if expected_err: |
|
269 | 269 | nt.assert_equals(err.strip(), expected_err.strip()) |
|
270 | 270 | else: |
|
271 | 271 | raise ValueError('Running file %r produced error: %r' % |
|
272 | 272 | (fname, err)) |
|
273 | 273 | # If no errors or output on stderr was expected, match stdout |
|
274 | 274 | nt.assert_equals(out.strip(), expected_out.strip()) |
|
275 | 275 | |
|
276 | 276 | |
|
277 | 277 | class TempFileMixin(object): |
|
278 | 278 | """Utility class to create temporary Python/IPython files. |
|
279 | 279 | |
|
280 | 280 | Meant as a mixin class for test cases.""" |
|
281 | 281 | |
|
282 | 282 | def mktmp(self, src, ext='.py'): |
|
283 | 283 | """Make a valid python temp file.""" |
|
284 | 284 | fname, f = temp_pyfile(src, ext) |
|
285 | 285 | self.tmpfile = f |
|
286 | 286 | self.fname = fname |
|
287 | 287 | |
|
288 | 288 | def tearDown(self): |
|
289 | 289 | if hasattr(self, 'tmpfile'): |
|
290 | 290 | # If the tmpfile wasn't made because of skipped tests, like in |
|
291 | 291 | # win32, there's nothing to cleanup. |
|
292 | 292 | self.tmpfile.close() |
|
293 | 293 | try: |
|
294 | 294 | os.unlink(self.fname) |
|
295 | 295 | except: |
|
296 | 296 | # On Windows, even though we close the file, we still can't |
|
297 | 297 | # delete it. I have no clue why |
|
298 | 298 | pass |
|
299 | 299 | |
|
300 | 300 | pair_fail_msg = ("Testing {0}\n\n" |
|
301 | 301 | "In:\n" |
|
302 | 302 | " {1!r}\n" |
|
303 | 303 | "Expected:\n" |
|
304 | 304 | " {2!r}\n" |
|
305 | 305 | "Got:\n" |
|
306 | 306 | " {3!r}\n") |
|
307 | 307 | def check_pairs(func, pairs): |
|
308 | 308 | """Utility function for the common case of checking a function with a |
|
309 | 309 | sequence of input/output pairs. |
|
310 | 310 | |
|
311 | 311 | Parameters |
|
312 | 312 | ---------- |
|
313 | 313 | func : callable |
|
314 | 314 | The function to be tested. Should accept a single argument. |
|
315 | 315 | pairs : iterable |
|
316 | 316 | A list of (input, expected_output) tuples. |
|
317 | 317 | |
|
318 | 318 | Returns |
|
319 | 319 | ------- |
|
320 | 320 | None. Raises an AssertionError if any output does not match the expected |
|
321 | 321 | value. |
|
322 | 322 | """ |
|
323 | 323 | name = getattr(func, "func_name", getattr(func, "__name__", "<unknown>")) |
|
324 | 324 | for inp, expected in pairs: |
|
325 | 325 | out = func(inp) |
|
326 | 326 | assert out == expected, pair_fail_msg.format(name, inp, expected, out) |
|
327 | 327 | |
|
328 | 328 | |
|
329 | 329 | if py3compat.PY3: |
|
330 | 330 | MyStringIO = StringIO |
|
331 | 331 | else: |
|
332 | 332 | # In Python 2, stdout/stderr can have either bytes or unicode written to them, |
|
333 | 333 | # so we need a class that can handle both. |
|
334 | 334 | class MyStringIO(StringIO): |
|
335 | 335 | def write(self, s): |
|
336 | 336 | s = py3compat.cast_unicode(s, encoding=getdefaultencoding()) |
|
337 | 337 | super(MyStringIO, self).write(s) |
|
338 | 338 | |
|
339 | 339 | notprinted_msg = """Did not find {0!r} in printed output (on {1}): |
|
340 | 340 | {2!r}""" |
|
341 | 341 | |
|
342 | 342 | class AssertPrints(object): |
|
343 | 343 | """Context manager for testing that code prints certain text. |
|
344 | 344 | |
|
345 | 345 | Examples |
|
346 | 346 | -------- |
|
347 | 347 | >>> with AssertPrints("abc", suppress=False): |
|
348 | 348 | ... print "abcd" |
|
349 | 349 | ... print "def" |
|
350 | 350 | ... |
|
351 | 351 | abcd |
|
352 | 352 | def |
|
353 | 353 | """ |
|
354 | 354 | def __init__(self, s, channel='stdout', suppress=True): |
|
355 | 355 | self.s = s |
|
356 | 356 | self.channel = channel |
|
357 | 357 | self.suppress = suppress |
|
358 | 358 | |
|
359 | 359 | def __enter__(self): |
|
360 | 360 | self.orig_stream = getattr(sys, self.channel) |
|
361 | 361 | self.buffer = MyStringIO() |
|
362 | 362 | self.tee = Tee(self.buffer, channel=self.channel) |
|
363 | 363 | setattr(sys, self.channel, self.buffer if self.suppress else self.tee) |
|
364 | 364 | |
|
365 | 365 | def __exit__(self, etype, value, traceback): |
|
366 | 366 | self.tee.flush() |
|
367 | 367 | setattr(sys, self.channel, self.orig_stream) |
|
368 | 368 | printed = self.buffer.getvalue() |
|
369 | 369 | assert self.s in printed, notprinted_msg.format(self.s, self.channel, printed) |
|
370 | 370 | return False |
|
371 | 371 | |
|
372 | 372 | class AssertNotPrints(AssertPrints): |
|
373 | 373 | """Context manager for checking that certain output *isn't* produced. |
|
374 | 374 | |
|
375 | 375 | Counterpart of AssertPrints""" |
|
376 | 376 | def __exit__(self, etype, value, traceback): |
|
377 | 377 | self.tee.flush() |
|
378 | 378 | setattr(sys, self.channel, self.orig_stream) |
|
379 | 379 | printed = self.buffer.getvalue() |
|
380 | 380 | assert self.s not in printed, notprinted_msg.format(self.s, self.channel, printed) |
|
381 | 381 | return False |
|
382 | 382 | |
|
383 | 383 | @contextmanager |
|
384 | 384 | def mute_warn(): |
|
385 | 385 | from IPython.utils import warn |
|
386 | 386 | save_warn = warn.warn |
|
387 | 387 | warn.warn = lambda *a, **kw: None |
|
388 | 388 | try: |
|
389 | 389 | yield |
|
390 | 390 | finally: |
|
391 | 391 | warn.warn = save_warn |
|
392 | 392 | |
|
393 | 393 | @contextmanager |
|
394 | 394 | def make_tempfile(name): |
|
395 | 395 | """ Create an empty, named, temporary file for the duration of the context. |
|
396 | 396 | """ |
|
397 | 397 | f = open(name, 'w') |
|
398 | 398 | f.close() |
|
399 | 399 | try: |
|
400 | 400 | yield |
|
401 | 401 | finally: |
|
402 | 402 | os.unlink(name) |
@@ -1,137 +1,137 b'' | |||
|
1 | 1 | #!/usr/bin/env python |
|
2 | 2 | |
|
3 | 3 | """An example of how to embed an IPython shell into a running program. |
|
4 | 4 | |
|
5 | 5 | Please see the documentation in the IPython.Shell module for more details. |
|
6 | 6 | |
|
7 | 7 | The accompanying file example-embed-short.py has quick code fragments for |
|
8 | 8 | embedding which you can cut and paste in your code once you understand how |
|
9 | 9 | things work. |
|
10 | 10 | |
|
11 | 11 | The code in this file is deliberately extra-verbose, meant for learning.""" |
|
12 | 12 | |
|
13 | 13 | # The basics to get you going: |
|
14 | 14 | |
|
15 | 15 | # IPython sets the __IPYTHON__ variable so you can know if you have nested |
|
16 | 16 | # copies running. |
|
17 | 17 | |
|
18 | 18 | # Try running this code both at the command line and from inside IPython (with |
|
19 | 19 | # %run example-embed.py) |
|
20 | 20 | from IPython.config.loader import Config |
|
21 | 21 | try: |
|
22 | 22 | get_ipython |
|
23 | 23 | except NameError: |
|
24 | 24 | nested = 0 |
|
25 | 25 | cfg = Config() |
|
26 | shell_config = cfg.InteractiveShellEmbed | |
|
27 |
|
|
|
28 |
|
|
|
29 |
|
|
|
26 | prompt_config = cfg.PromptManager | |
|
27 | prompt_config.in_template = 'In <\\#>: ' | |
|
28 | prompt_config.in2_template = ' .\\D.: ' | |
|
29 | prompt_config.out_template = 'Out<\\#>: ' | |
|
30 | 30 | else: |
|
31 | 31 | print "Running nested copies of IPython." |
|
32 | 32 | print "The prompts for the nested copy have been modified" |
|
33 | 33 | cfg = Config() |
|
34 | 34 | nested = 1 |
|
35 | 35 | |
|
36 | 36 | # First import the embeddable shell class |
|
37 | 37 | from IPython.frontend.terminal.embed import InteractiveShellEmbed |
|
38 | 38 | |
|
39 | 39 | # Now create an instance of the embeddable shell. The first argument is a |
|
40 | 40 | # string with options exactly as you would type them if you were starting |
|
41 | 41 | # IPython at the system command line. Any parameters you want to define for |
|
42 | 42 | # configuration can thus be specified here. |
|
43 | 43 | ipshell = InteractiveShellEmbed(config=cfg, |
|
44 | 44 | banner1 = 'Dropping into IPython', |
|
45 | 45 | exit_msg = 'Leaving Interpreter, back to program.') |
|
46 | 46 | |
|
47 | 47 | # Make a second instance, you can have as many as you want. |
|
48 | 48 | cfg2 = cfg.copy() |
|
49 | shell_config = cfg2.InteractiveShellEmbed | |
|
50 |
|
|
|
49 | prompt_config = cfg2.PromptManager | |
|
50 | prompt_config.in_template = 'In2<\\#>: ' | |
|
51 | 51 | if not nested: |
|
52 |
|
|
|
53 |
|
|
|
54 |
|
|
|
52 | prompt_config.in_template = 'In2<\\#>: ' | |
|
53 | prompt_config.in2_template = ' .\\D.: ' | |
|
54 | prompt_config.out_template = 'Out<\\#>: ' | |
|
55 | 55 | ipshell2 = InteractiveShellEmbed(config=cfg, |
|
56 | 56 | banner1 = 'Second IPython instance.') |
|
57 | 57 | |
|
58 | 58 | print '\nHello. This is printed from the main controller program.\n' |
|
59 | 59 | |
|
60 | 60 | # You can then call ipshell() anywhere you need it (with an optional |
|
61 | 61 | # message): |
|
62 | 62 | ipshell('***Called from top level. ' |
|
63 | 63 | 'Hit Ctrl-D to exit interpreter and continue program.\n' |
|
64 | 64 | 'Note that if you use %kill_embedded, you can fully deactivate\n' |
|
65 | 65 | 'This embedded instance so it will never turn on again') |
|
66 | 66 | |
|
67 | 67 | print '\nBack in caller program, moving along...\n' |
|
68 | 68 | |
|
69 | 69 | #--------------------------------------------------------------------------- |
|
70 | 70 | # More details: |
|
71 | 71 | |
|
72 | 72 | # InteractiveShellEmbed instances don't print the standard system banner and |
|
73 | 73 | # messages. The IPython banner (which actually may contain initialization |
|
74 | 74 | # messages) is available as get_ipython().banner in case you want it. |
|
75 | 75 | |
|
76 | 76 | # InteractiveShellEmbed instances print the following information everytime they |
|
77 | 77 | # start: |
|
78 | 78 | |
|
79 | 79 | # - A global startup banner. |
|
80 | 80 | |
|
81 | 81 | # - A call-specific header string, which you can use to indicate where in the |
|
82 | 82 | # execution flow the shell is starting. |
|
83 | 83 | |
|
84 | 84 | # They also print an exit message every time they exit. |
|
85 | 85 | |
|
86 | 86 | # Both the startup banner and the exit message default to None, and can be set |
|
87 | 87 | # either at the instance constructor or at any other time with the |
|
88 | 88 | # by setting the banner and exit_msg attributes. |
|
89 | 89 | |
|
90 | 90 | # The shell instance can be also put in 'dummy' mode globally or on a per-call |
|
91 | 91 | # basis. This gives you fine control for debugging without having to change |
|
92 | 92 | # code all over the place. |
|
93 | 93 | |
|
94 | 94 | # The code below illustrates all this. |
|
95 | 95 | |
|
96 | 96 | |
|
97 | 97 | # This is how the global banner and exit_msg can be reset at any point |
|
98 | 98 | ipshell.banner = 'Entering interpreter - New Banner' |
|
99 | 99 | ipshell.exit_msg = 'Leaving interpreter - New exit_msg' |
|
100 | 100 | |
|
101 | 101 | def foo(m): |
|
102 | 102 | s = 'spam' |
|
103 | 103 | ipshell('***In foo(). Try %whos, or print s or m:') |
|
104 | 104 | print 'foo says m = ',m |
|
105 | 105 | |
|
106 | 106 | def bar(n): |
|
107 | 107 | s = 'eggs' |
|
108 | 108 | ipshell('***In bar(). Try %whos, or print s or n:') |
|
109 | 109 | print 'bar says n = ',n |
|
110 | 110 | |
|
111 | 111 | # Some calls to the above functions which will trigger IPython: |
|
112 | 112 | print 'Main program calling foo("eggs")\n' |
|
113 | 113 | foo('eggs') |
|
114 | 114 | |
|
115 | 115 | # The shell can be put in 'dummy' mode where calls to it silently return. This |
|
116 | 116 | # allows you, for example, to globally turn off debugging for a program with a |
|
117 | 117 | # single call. |
|
118 | 118 | ipshell.dummy_mode = True |
|
119 | 119 | print '\nTrying to call IPython which is now "dummy":' |
|
120 | 120 | ipshell() |
|
121 | 121 | print 'Nothing happened...' |
|
122 | 122 | # The global 'dummy' mode can still be overridden for a single call |
|
123 | 123 | print '\nOverriding dummy mode manually:' |
|
124 | 124 | ipshell(dummy=False) |
|
125 | 125 | |
|
126 | 126 | # Reactivate the IPython shell |
|
127 | 127 | ipshell.dummy_mode = False |
|
128 | 128 | |
|
129 | 129 | print 'You can even have multiple embedded instances:' |
|
130 | 130 | ipshell2() |
|
131 | 131 | |
|
132 | 132 | print '\nMain program calling bar("spam")\n' |
|
133 | 133 | bar('spam') |
|
134 | 134 | |
|
135 | 135 | print 'Main program finished. Bye!' |
|
136 | 136 | |
|
137 | 137 | #********************** End of file <example-embed.py> *********************** |
@@ -1,1263 +1,1263 b'' | |||
|
1 | 1 | ================= |
|
2 | 2 | IPython reference |
|
3 | 3 | ================= |
|
4 | 4 | |
|
5 | 5 | .. _command_line_options: |
|
6 | 6 | |
|
7 | 7 | Command-line usage |
|
8 | 8 | ================== |
|
9 | 9 | |
|
10 | 10 | You start IPython with the command:: |
|
11 | 11 | |
|
12 | 12 | $ ipython [options] files |
|
13 | 13 | |
|
14 | 14 | .. note:: |
|
15 | 15 | |
|
16 | 16 | For IPython on Python 3, use ``ipython3`` in place of ``ipython``. |
|
17 | 17 | |
|
18 | 18 | If invoked with no options, it executes all the files listed in sequence |
|
19 | 19 | and drops you into the interpreter while still acknowledging any options |
|
20 | 20 | you may have set in your ipython_config.py. This behavior is different from |
|
21 | 21 | standard Python, which when called as python -i will only execute one |
|
22 | 22 | file and ignore your configuration setup. |
|
23 | 23 | |
|
24 | 24 | Please note that some of the configuration options are not available at |
|
25 | 25 | the command line, simply because they are not practical here. Look into |
|
26 | 26 | your configuration files for details on those. There are separate configuration |
|
27 | 27 | files for each profile, and the files look like "ipython_config.py" or |
|
28 | 28 | "ipython_config_<frontendname>.py". Profile directories look like |
|
29 | 29 | "profile_profilename" and are typically installed in the IPYTHON_DIR directory. |
|
30 | 30 | For Linux users, this will be $HOME/.config/ipython, and for other users it |
|
31 | 31 | will be $HOME/.ipython. For Windows users, $HOME resolves to C:\\Documents and |
|
32 | 32 | Settings\\YourUserName in most instances. |
|
33 | 33 | |
|
34 | 34 | |
|
35 | 35 | Eventloop integration |
|
36 | 36 | --------------------- |
|
37 | 37 | |
|
38 | 38 | Previously IPython had command line options for controlling GUI event loop |
|
39 | 39 | integration (-gthread, -qthread, -q4thread, -wthread, -pylab). As of IPython |
|
40 | 40 | version 0.11, these have been removed. Please see the new ``%gui`` |
|
41 | 41 | magic command or :ref:`this section <gui_support>` for details on the new |
|
42 | 42 | interface, or specify the gui at the commandline:: |
|
43 | 43 | |
|
44 | 44 | $ ipython --gui=qt |
|
45 | 45 | |
|
46 | 46 | |
|
47 | 47 | Regular Options |
|
48 | 48 | --------------- |
|
49 | 49 | |
|
50 | 50 | After the above threading options have been given, regular options can |
|
51 | 51 | follow in any order. All options can be abbreviated to their shortest |
|
52 | 52 | non-ambiguous form and are case-sensitive. |
|
53 | 53 | |
|
54 | 54 | Most options can also be set from your configuration file. See the provided |
|
55 | 55 | example for more details on what the options do. Options given at the command |
|
56 | 56 | line override the values set in the configuration file. |
|
57 | 57 | |
|
58 | 58 | All options with a [no] prepended can be specified in negated form |
|
59 | 59 | (--no-option instead of --option) to turn the feature off. |
|
60 | 60 | |
|
61 | 61 | ``-h, --help`` print a help message and exit. |
|
62 | 62 | |
|
63 | 63 | ``--pylab, pylab=<name>`` |
|
64 | 64 | See :ref:`Matplotlib support <matplotlib_support>` |
|
65 | 65 | for more details. |
|
66 | 66 | |
|
67 | 67 | ``--autocall=<val>`` |
|
68 | 68 | Make IPython automatically call any callable object even if you |
|
69 | 69 | didn't type explicit parentheses. For example, 'str 43' becomes |
|
70 | 70 | 'str(43)' automatically. The value can be '0' to disable the feature, |
|
71 | 71 | '1' for smart autocall, where it is not applied if there are no more |
|
72 | 72 | arguments on the line, and '2' for full autocall, where all callable |
|
73 | 73 | objects are automatically called (even if no arguments are |
|
74 | 74 | present). The default is '1'. |
|
75 | 75 | |
|
76 | 76 | ``--[no-]autoindent`` |
|
77 | 77 | Turn automatic indentation on/off. |
|
78 | 78 | |
|
79 | 79 | ``--[no-]automagic`` |
|
80 | 80 | make magic commands automatic (without needing their first character |
|
81 | 81 | to be %). Type %magic at the IPython prompt for more information. |
|
82 | 82 | |
|
83 | 83 | ``--[no-]autoedit_syntax`` |
|
84 | 84 | When a syntax error occurs after editing a file, automatically |
|
85 | 85 | open the file to the trouble causing line for convenient |
|
86 | 86 | fixing. |
|
87 | 87 | |
|
88 | 88 | ``--[no-]banner`` |
|
89 | 89 | Print the initial information banner (default on). |
|
90 | 90 | |
|
91 | 91 | ``-c <command>`` |
|
92 | 92 | execute the given command string. This is similar to the -c |
|
93 | 93 | option in the normal Python interpreter. |
|
94 | 94 | |
|
95 | 95 | ``--cache-size=<n>`` |
|
96 | 96 | size of the output cache (maximum number of entries to hold in |
|
97 | 97 | memory). The default is 1000, you can change it permanently in your |
|
98 | 98 | config file. Setting it to 0 completely disables the caching system, |
|
99 | 99 | and the minimum value accepted is 20 (if you provide a value less than |
|
100 | 100 | 20, it is reset to 0 and a warning is issued) This limit is defined |
|
101 | 101 | because otherwise you'll spend more time re-flushing a too small cache |
|
102 | 102 | than working. |
|
103 | 103 | |
|
104 | 104 | ``--classic`` |
|
105 | 105 | Gives IPython a similar feel to the classic Python |
|
106 | 106 | prompt. |
|
107 | 107 | |
|
108 | 108 | ``--colors=<scheme>`` |
|
109 | 109 | Color scheme for prompts and exception reporting. Currently |
|
110 | 110 | implemented: NoColor, Linux and LightBG. |
|
111 | 111 | |
|
112 | 112 | ``--[no-]color_info`` |
|
113 | 113 | IPython can display information about objects via a set of functions, |
|
114 | 114 | and optionally can use colors for this, syntax highlighting source |
|
115 | 115 | code and various other elements. However, because this information is |
|
116 | 116 | passed through a pager (like 'less') and many pagers get confused with |
|
117 | 117 | color codes, this option is off by default. You can test it and turn |
|
118 | 118 | it on permanently in your configuration file if it works for you. As a |
|
119 | 119 | reference, the 'less' pager supplied with Mandrake 8.2 works ok, but |
|
120 | 120 | that in RedHat 7.2 doesn't. |
|
121 | 121 | |
|
122 | 122 | Test it and turn it on permanently if it works with your |
|
123 | 123 | system. The magic function %color_info allows you to toggle this |
|
124 | 124 | interactively for testing. |
|
125 | 125 | |
|
126 | 126 | ``--[no-]debug`` |
|
127 | 127 | Show information about the loading process. Very useful to pin down |
|
128 | 128 | problems with your configuration files or to get details about |
|
129 | 129 | session restores. |
|
130 | 130 | |
|
131 | 131 | ``--[no-]deep_reload`` |
|
132 | 132 | IPython can use the deep_reload module which reloads changes in |
|
133 | 133 | modules recursively (it replaces the reload() function, so you don't |
|
134 | 134 | need to change anything to use it). deep_reload() forces a full |
|
135 | 135 | reload of modules whose code may have changed, which the default |
|
136 | 136 | reload() function does not. |
|
137 | 137 | |
|
138 | 138 | When deep_reload is off, IPython will use the normal reload(), |
|
139 | 139 | but deep_reload will still be available as dreload(). This |
|
140 | 140 | feature is off by default [which means that you have both |
|
141 | 141 | normal reload() and dreload()]. |
|
142 | 142 | |
|
143 | 143 | .. this isn't currently working |
|
144 | 144 | .. ``--editor=<name>`` |
|
145 | 145 | Which editor to use with the %edit command. By default, |
|
146 | 146 | IPython will honor your EDITOR environment variable (if not |
|
147 | 147 | set, vi is the Unix default and notepad the Windows one). |
|
148 | 148 | Since this editor is invoked on the fly by IPython and is |
|
149 | 149 | meant for editing small code snippets, you may want to use a |
|
150 | 150 | small, lightweight editor here (in case your default EDITOR is |
|
151 | 151 | something like Emacs). |
|
152 | 152 | |
|
153 | 153 | ``--ipython_dir=<name>`` |
|
154 | 154 | name of your IPython configuration directory IPYTHON_DIR. This |
|
155 | 155 | can also be specified through the environment variable |
|
156 | 156 | IPYTHON_DIR. |
|
157 | 157 | |
|
158 | 158 | ``--logfile=<name>`` |
|
159 | 159 | specify the name of your logfile. |
|
160 | 160 | |
|
161 | 161 | This implies ``%logstart`` at the beginning of your session |
|
162 | 162 | |
|
163 | 163 | generate a log file of all input. The file is named |
|
164 | 164 | ipython_log.py in your current directory (which prevents logs |
|
165 | 165 | from multiple IPython sessions from trampling each other). You |
|
166 | 166 | can use this to later restore a session by loading your |
|
167 | 167 | logfile with ``ipython -i ipython_log.py`` |
|
168 | 168 | |
|
169 | 169 | ``--logplay=<name>`` |
|
170 | 170 | |
|
171 | 171 | NOT AVAILABLE in 0.11 |
|
172 | 172 | |
|
173 | 173 | you can replay a previous log. For restoring a session as close as |
|
174 | 174 | possible to the state you left it in, use this option (don't just run |
|
175 | 175 | the logfile). With -logplay, IPython will try to reconstruct the |
|
176 | 176 | previous working environment in full, not just execute the commands in |
|
177 | 177 | the logfile. |
|
178 | 178 | |
|
179 | 179 | When a session is restored, logging is automatically turned on |
|
180 | 180 | again with the name of the logfile it was invoked with (it is |
|
181 | 181 | read from the log header). So once you've turned logging on for |
|
182 | 182 | a session, you can quit IPython and reload it as many times as |
|
183 | 183 | you want and it will continue to log its history and restore |
|
184 | 184 | from the beginning every time. |
|
185 | 185 | |
|
186 | 186 | Caveats: there are limitations in this option. The history |
|
187 | 187 | variables _i*,_* and _dh don't get restored properly. In the |
|
188 | 188 | future we will try to implement full session saving by writing |
|
189 | 189 | and retrieving a 'snapshot' of the memory state of IPython. But |
|
190 | 190 | our first attempts failed because of inherent limitations of |
|
191 | 191 | Python's Pickle module, so this may have to wait. |
|
192 | 192 | |
|
193 | 193 | ``--[no-]messages`` |
|
194 | 194 | Print messages which IPython collects about its startup |
|
195 | 195 | process (default on). |
|
196 | 196 | |
|
197 | 197 | ``--[no-]pdb`` |
|
198 | 198 | Automatically call the pdb debugger after every uncaught |
|
199 | 199 | exception. If you are used to debugging using pdb, this puts |
|
200 | 200 | you automatically inside of it after any call (either in |
|
201 | 201 | IPython or in code called by it) which triggers an exception |
|
202 | 202 | which goes uncaught. |
|
203 | 203 | |
|
204 | 204 | ``--[no-]pprint`` |
|
205 | 205 | ipython can optionally use the pprint (pretty printer) module |
|
206 | 206 | for displaying results. pprint tends to give a nicer display |
|
207 | 207 | of nested data structures. If you like it, you can turn it on |
|
208 | 208 | permanently in your config file (default off). |
|
209 | 209 | |
|
210 | 210 | ``--profile=<name>`` |
|
211 | 211 | |
|
212 | 212 | Select the IPython profile by name. |
|
213 | 213 | |
|
214 | 214 | This is a quick way to keep and load multiple |
|
215 | 215 | config files for different tasks, especially if you use the |
|
216 | 216 | include option of config files. You can keep a basic |
|
217 | 217 | :file:`IPYTHON_DIR/profile_default/ipython_config.py` file |
|
218 | 218 | and then have other 'profiles' which |
|
219 | 219 | include this one and load extra things for particular |
|
220 | 220 | tasks. For example: |
|
221 | 221 | |
|
222 | 222 | 1. $IPYTHON_DIR/profile_default : load basic things you always want. |
|
223 | 223 | 2. $IPYTHON_DIR/profile_math : load (1) and basic math-related modules. |
|
224 | 224 | 3. $IPYTHON_DIR/profile_numeric : load (1) and Numeric and plotting modules. |
|
225 | 225 | |
|
226 | 226 | Since it is possible to create an endless loop by having |
|
227 | 227 | circular file inclusions, IPython will stop if it reaches 15 |
|
228 | 228 | recursive inclusions. |
|
229 | 229 | |
|
230 | ``InteractiveShell.prompt_in1=<string>`` | |
|
230 | ``PromptManager.in_template=<string>`` | |
|
231 | 231 | |
|
232 | 232 | Specify the string used for input prompts. Note that if you are using |
|
233 | 233 | numbered prompts, the number is represented with a '\#' in the |
|
234 | 234 | string. Don't forget to quote strings with spaces embedded in |
|
235 | 235 | them. Default: 'In [\#]:'. The :ref:`prompts section <prompts>` |
|
236 | 236 | discusses in detail all the available escapes to customize your |
|
237 | 237 | prompts. |
|
238 | 238 | |
|
239 | ``InteractiveShell.prompt_in2=<string>`` | |
|
239 | ``PromptManager.in2_template=<string>`` | |
|
240 | 240 | Similar to the previous option, but used for the continuation |
|
241 | 241 | prompts. The special sequence '\D' is similar to '\#', but |
|
242 | 242 | with all digits replaced dots (so you can have your |
|
243 | 243 | continuation prompt aligned with your input prompt). Default: |
|
244 | 244 | ' .\D.:' (note three spaces at the start for alignment with |
|
245 | 245 | 'In [\#]'). |
|
246 | 246 | |
|
247 | ``InteractiveShell.prompt_out=<string>`` | |
|
247 | ``PromptManager.out_template=<string>`` | |
|
248 | 248 | String used for output prompts, also uses numbers like |
|
249 |
|
|
|
249 | in_template. Default: 'Out[\#]:' | |
|
250 | 250 | |
|
251 | 251 | ``--quick`` |
|
252 | 252 | start in bare bones mode (no config file loaded). |
|
253 | 253 | |
|
254 | 254 | ``config_file=<name>`` |
|
255 | 255 | name of your IPython resource configuration file. Normally |
|
256 | 256 | IPython loads ipython_config.py (from current directory) or |
|
257 | 257 | IPYTHON_DIR/profile_default. |
|
258 | 258 | |
|
259 | 259 | If the loading of your config file fails, IPython starts with |
|
260 | 260 | a bare bones configuration (no modules loaded at all). |
|
261 | 261 | |
|
262 | 262 | ``--[no-]readline`` |
|
263 | 263 | use the readline library, which is needed to support name |
|
264 | 264 | completion and command history, among other things. It is |
|
265 | 265 | enabled by default, but may cause problems for users of |
|
266 | 266 | X/Emacs in Python comint or shell buffers. |
|
267 | 267 | |
|
268 | 268 | Note that X/Emacs 'eterm' buffers (opened with M-x term) support |
|
269 | 269 | IPython's readline and syntax coloring fine, only 'emacs' (M-x |
|
270 | 270 | shell and C-c !) buffers do not. |
|
271 | 271 | |
|
272 | 272 | ``--TerminalInteractiveShell.screen_length=<n>`` |
|
273 | 273 | number of lines of your screen. This is used to control |
|
274 | 274 | printing of very long strings. Strings longer than this number |
|
275 | 275 | of lines will be sent through a pager instead of directly |
|
276 | 276 | printed. |
|
277 | 277 | |
|
278 | 278 | The default value for this is 0, which means IPython will |
|
279 | 279 | auto-detect your screen size every time it needs to print certain |
|
280 | 280 | potentially long strings (this doesn't change the behavior of the |
|
281 | 281 | 'print' keyword, it's only triggered internally). If for some |
|
282 | 282 | reason this isn't working well (it needs curses support), specify |
|
283 | 283 | it yourself. Otherwise don't change the default. |
|
284 | 284 | |
|
285 | 285 | ``--TerminalInteractiveShell.separate_in=<string>`` |
|
286 | 286 | |
|
287 | 287 | separator before input prompts. |
|
288 | 288 | Default: '\n' |
|
289 | 289 | |
|
290 | 290 | ``--TerminalInteractiveShell.separate_out=<string>`` |
|
291 | 291 | separator before output prompts. |
|
292 | 292 | Default: nothing. |
|
293 | 293 | |
|
294 | 294 | ``--TerminalInteractiveShell.separate_out2=<string>`` |
|
295 | 295 | separator after output prompts. |
|
296 | 296 | Default: nothing. |
|
297 | 297 | For these three options, use the value 0 to specify no separator. |
|
298 | 298 | |
|
299 | 299 | ``--nosep`` |
|
300 | 300 | shorthand for setting the above separators to empty strings. |
|
301 | 301 | |
|
302 | 302 | Simply removes all input/output separators. |
|
303 | 303 | |
|
304 | 304 | ``--init`` |
|
305 | 305 | allows you to initialize a profile dir for configuration when you |
|
306 | 306 | install a new version of IPython or want to use a new profile. |
|
307 | 307 | Since new versions may include new command line options or example |
|
308 | 308 | files, this copies updated config files. Note that you should probably |
|
309 | 309 | use %upgrade instead,it's a safer alternative. |
|
310 | 310 | |
|
311 | 311 | ``--version`` print version information and exit. |
|
312 | 312 | |
|
313 | 313 | ``--xmode=<modename>`` |
|
314 | 314 | |
|
315 | 315 | Mode for exception reporting. |
|
316 | 316 | |
|
317 | 317 | Valid modes: Plain, Context and Verbose. |
|
318 | 318 | |
|
319 | 319 | * Plain: similar to python's normal traceback printing. |
|
320 | 320 | * Context: prints 5 lines of context source code around each |
|
321 | 321 | line in the traceback. |
|
322 | 322 | * Verbose: similar to Context, but additionally prints the |
|
323 | 323 | variables currently visible where the exception happened |
|
324 | 324 | (shortening their strings if too long). This can potentially be |
|
325 | 325 | very slow, if you happen to have a huge data structure whose |
|
326 | 326 | string representation is complex to compute. Your computer may |
|
327 | 327 | appear to freeze for a while with cpu usage at 100%. If this |
|
328 | 328 | occurs, you can cancel the traceback with Ctrl-C (maybe hitting it |
|
329 | 329 | more than once). |
|
330 | 330 | |
|
331 | 331 | Interactive use |
|
332 | 332 | =============== |
|
333 | 333 | |
|
334 | 334 | IPython is meant to work as a drop-in replacement for the standard interactive |
|
335 | 335 | interpreter. As such, any code which is valid python should execute normally |
|
336 | 336 | under IPython (cases where this is not true should be reported as bugs). It |
|
337 | 337 | does, however, offer many features which are not available at a standard python |
|
338 | 338 | prompt. What follows is a list of these. |
|
339 | 339 | |
|
340 | 340 | |
|
341 | 341 | Caution for Windows users |
|
342 | 342 | ------------------------- |
|
343 | 343 | |
|
344 | 344 | Windows, unfortunately, uses the '\\' character as a path separator. This is a |
|
345 | 345 | terrible choice, because '\\' also represents the escape character in most |
|
346 | 346 | modern programming languages, including Python. For this reason, using '/' |
|
347 | 347 | character is recommended if you have problems with ``\``. However, in Windows |
|
348 | 348 | commands '/' flags options, so you can not use it for the root directory. This |
|
349 | 349 | means that paths beginning at the root must be typed in a contrived manner |
|
350 | 350 | like: ``%copy \opt/foo/bar.txt \tmp`` |
|
351 | 351 | |
|
352 | 352 | .. _magic: |
|
353 | 353 | |
|
354 | 354 | Magic command system |
|
355 | 355 | -------------------- |
|
356 | 356 | |
|
357 | 357 | IPython will treat any line whose first character is a % as a special |
|
358 | 358 | call to a 'magic' function. These allow you to control the behavior of |
|
359 | 359 | IPython itself, plus a lot of system-type features. They are all |
|
360 | 360 | prefixed with a % character, but parameters are given without |
|
361 | 361 | parentheses or quotes. |
|
362 | 362 | |
|
363 | 363 | Example: typing ``%cd mydir`` changes your working directory to 'mydir', if it |
|
364 | 364 | exists. |
|
365 | 365 | |
|
366 | 366 | If you have 'automagic' enabled (as it by default), you don't need |
|
367 | 367 | to type in the % explicitly. IPython will scan its internal list of |
|
368 | 368 | magic functions and call one if it exists. With automagic on you can |
|
369 | 369 | then just type ``cd mydir`` to go to directory 'mydir'. The automagic |
|
370 | 370 | system has the lowest possible precedence in name searches, so defining |
|
371 | 371 | an identifier with the same name as an existing magic function will |
|
372 | 372 | shadow it for automagic use. You can still access the shadowed magic |
|
373 | 373 | function by explicitly using the % character at the beginning of the line. |
|
374 | 374 | |
|
375 | 375 | An example (with automagic on) should clarify all this: |
|
376 | 376 | |
|
377 | 377 | .. sourcecode:: ipython |
|
378 | 378 | |
|
379 | 379 | In [1]: cd ipython # %cd is called by automagic |
|
380 | 380 | /home/fperez/ipython |
|
381 | 381 | |
|
382 | 382 | In [2]: cd=1 # now cd is just a variable |
|
383 | 383 | |
|
384 | 384 | In [3]: cd .. # and doesn't work as a function anymore |
|
385 | 385 | File "<ipython-input-3-9fedb3aff56c>", line 1 |
|
386 | 386 | cd .. |
|
387 | 387 | ^ |
|
388 | 388 | SyntaxError: invalid syntax |
|
389 | 389 | |
|
390 | 390 | |
|
391 | 391 | In [4]: %cd .. # but %cd always works |
|
392 | 392 | /home/fperez |
|
393 | 393 | |
|
394 | 394 | In [5]: del cd # if you remove the cd variable, automagic works again |
|
395 | 395 | |
|
396 | 396 | In [6]: cd ipython |
|
397 | 397 | |
|
398 | 398 | /home/fperez/ipython |
|
399 | 399 | |
|
400 | 400 | You can define your own magic functions to extend the system. The |
|
401 | 401 | following example defines a new magic command, %impall: |
|
402 | 402 | |
|
403 | 403 | .. sourcecode:: python |
|
404 | 404 | |
|
405 | 405 | ip = get_ipython() |
|
406 | 406 | |
|
407 | 407 | def doimp(self, arg): |
|
408 | 408 | ip = self.api |
|
409 | 409 | ip.ex("import %s; reload(%s); from %s import *" % (arg,arg,arg) ) |
|
410 | 410 | |
|
411 | 411 | ip.define_magic('impall', doimp) |
|
412 | 412 | |
|
413 | 413 | Type ``%magic`` for more information, including a list of all available magic |
|
414 | 414 | functions at any time and their docstrings. You can also type |
|
415 | 415 | ``%magic_function_name?`` (see :ref:`below <dynamic_object_info>` for information on |
|
416 | 416 | the '?' system) to get information about any particular magic function you are |
|
417 | 417 | interested in. |
|
418 | 418 | |
|
419 | 419 | The API documentation for the :mod:`IPython.core.magic` module contains the full |
|
420 | 420 | docstrings of all currently available magic commands. |
|
421 | 421 | |
|
422 | 422 | |
|
423 | 423 | Access to the standard Python help |
|
424 | 424 | ---------------------------------- |
|
425 | 425 | |
|
426 | 426 | Simply type ``help()`` to access Python's standard help system. You can |
|
427 | 427 | also type ``help(object)`` for information about a given object, or |
|
428 | 428 | ``help('keyword')`` for information on a keyword. You may need to configure your |
|
429 | 429 | PYTHONDOCS environment variable for this feature to work correctly. |
|
430 | 430 | |
|
431 | 431 | .. _dynamic_object_info: |
|
432 | 432 | |
|
433 | 433 | Dynamic object information |
|
434 | 434 | -------------------------- |
|
435 | 435 | |
|
436 | 436 | Typing ``?word`` or ``word?`` prints detailed information about an object. If |
|
437 | 437 | certain strings in the object are too long (e.g. function signatures) they get |
|
438 | 438 | snipped in the center for brevity. This system gives access variable types and |
|
439 | 439 | values, docstrings, function prototypes and other useful information. |
|
440 | 440 | |
|
441 | 441 | If the information will not fit in the terminal, it is displayed in a pager |
|
442 | 442 | (``less`` if available, otherwise a basic internal pager). |
|
443 | 443 | |
|
444 | 444 | Typing ``??word`` or ``word??`` gives access to the full information, including |
|
445 | 445 | the source code where possible. Long strings are not snipped. |
|
446 | 446 | |
|
447 | 447 | The following magic functions are particularly useful for gathering |
|
448 | 448 | information about your working environment. You can get more details by |
|
449 | 449 | typing ``%magic`` or querying them individually (``%function_name?``); |
|
450 | 450 | this is just a summary: |
|
451 | 451 | |
|
452 | 452 | * **%pdoc <object>**: Print (or run through a pager if too long) the |
|
453 | 453 | docstring for an object. If the given object is a class, it will |
|
454 | 454 | print both the class and the constructor docstrings. |
|
455 | 455 | * **%pdef <object>**: Print the definition header for any callable |
|
456 | 456 | object. If the object is a class, print the constructor information. |
|
457 | 457 | * **%psource <object>**: Print (or run through a pager if too long) |
|
458 | 458 | the source code for an object. |
|
459 | 459 | * **%pfile <object>**: Show the entire source file where an object was |
|
460 | 460 | defined via a pager, opening it at the line where the object |
|
461 | 461 | definition begins. |
|
462 | 462 | * **%who/%whos**: These functions give information about identifiers |
|
463 | 463 | you have defined interactively (not things you loaded or defined |
|
464 | 464 | in your configuration files). %who just prints a list of |
|
465 | 465 | identifiers and %whos prints a table with some basic details about |
|
466 | 466 | each identifier. |
|
467 | 467 | |
|
468 | 468 | Note that the dynamic object information functions (?/??, ``%pdoc``, |
|
469 | 469 | ``%pfile``, ``%pdef``, ``%psource``) work on object attributes, as well as |
|
470 | 470 | directly on variables. For example, after doing ``import os``, you can use |
|
471 | 471 | ``os.path.abspath??``. |
|
472 | 472 | |
|
473 | 473 | .. _readline: |
|
474 | 474 | |
|
475 | 475 | Readline-based features |
|
476 | 476 | ----------------------- |
|
477 | 477 | |
|
478 | 478 | These features require the GNU readline library, so they won't work if your |
|
479 | 479 | Python installation lacks readline support. We will first describe the default |
|
480 | 480 | behavior IPython uses, and then how to change it to suit your preferences. |
|
481 | 481 | |
|
482 | 482 | |
|
483 | 483 | Command line completion |
|
484 | 484 | +++++++++++++++++++++++ |
|
485 | 485 | |
|
486 | 486 | At any time, hitting TAB will complete any available python commands or |
|
487 | 487 | variable names, and show you a list of the possible completions if |
|
488 | 488 | there's no unambiguous one. It will also complete filenames in the |
|
489 | 489 | current directory if no python names match what you've typed so far. |
|
490 | 490 | |
|
491 | 491 | |
|
492 | 492 | Search command history |
|
493 | 493 | ++++++++++++++++++++++ |
|
494 | 494 | |
|
495 | 495 | IPython provides two ways for searching through previous input and thus |
|
496 | 496 | reduce the need for repetitive typing: |
|
497 | 497 | |
|
498 | 498 | 1. Start typing, and then use Ctrl-p (previous,up) and Ctrl-n |
|
499 | 499 | (next,down) to search through only the history items that match |
|
500 | 500 | what you've typed so far. If you use Ctrl-p/Ctrl-n at a blank |
|
501 | 501 | prompt, they just behave like normal arrow keys. |
|
502 | 502 | 2. Hit Ctrl-r: opens a search prompt. Begin typing and the system |
|
503 | 503 | searches your history for lines that contain what you've typed so |
|
504 | 504 | far, completing as much as it can. |
|
505 | 505 | |
|
506 | 506 | |
|
507 | 507 | Persistent command history across sessions |
|
508 | 508 | ++++++++++++++++++++++++++++++++++++++++++ |
|
509 | 509 | |
|
510 | 510 | IPython will save your input history when it leaves and reload it next |
|
511 | 511 | time you restart it. By default, the history file is named |
|
512 | 512 | $IPYTHON_DIR/profile_<name>/history.sqlite. This allows you to keep |
|
513 | 513 | separate histories related to various tasks: commands related to |
|
514 | 514 | numerical work will not be clobbered by a system shell history, for |
|
515 | 515 | example. |
|
516 | 516 | |
|
517 | 517 | |
|
518 | 518 | Autoindent |
|
519 | 519 | ++++++++++ |
|
520 | 520 | |
|
521 | 521 | IPython can recognize lines ending in ':' and indent the next line, |
|
522 | 522 | while also un-indenting automatically after 'raise' or 'return'. |
|
523 | 523 | |
|
524 | 524 | This feature uses the readline library, so it will honor your |
|
525 | 525 | :file:`~/.inputrc` configuration (or whatever file your INPUTRC variable points |
|
526 | 526 | to). Adding the following lines to your :file:`.inputrc` file can make |
|
527 | 527 | indenting/unindenting more convenient (M-i indents, M-u unindents):: |
|
528 | 528 | |
|
529 | 529 | $if Python |
|
530 | 530 | "\M-i": " " |
|
531 | 531 | "\M-u": "\d\d\d\d" |
|
532 | 532 | $endif |
|
533 | 533 | |
|
534 | 534 | Note that there are 4 spaces between the quote marks after "M-i" above. |
|
535 | 535 | |
|
536 | 536 | .. warning:: |
|
537 | 537 | |
|
538 | 538 | Setting the above indents will cause problems with unicode text entry in |
|
539 | 539 | the terminal. |
|
540 | 540 | |
|
541 | 541 | .. warning:: |
|
542 | 542 | |
|
543 | 543 | Autoindent is ON by default, but it can cause problems with the pasting of |
|
544 | 544 | multi-line indented code (the pasted code gets re-indented on each line). A |
|
545 | 545 | magic function %autoindent allows you to toggle it on/off at runtime. You |
|
546 | 546 | can also disable it permanently on in your :file:`ipython_config.py` file |
|
547 | 547 | (set TerminalInteractiveShell.autoindent=False). |
|
548 | 548 | |
|
549 | 549 | If you want to paste multiple lines in the terminal, it is recommended that |
|
550 | 550 | you use ``%paste``. |
|
551 | 551 | |
|
552 | 552 | |
|
553 | 553 | Customizing readline behavior |
|
554 | 554 | +++++++++++++++++++++++++++++ |
|
555 | 555 | |
|
556 | 556 | All these features are based on the GNU readline library, which has an |
|
557 | 557 | extremely customizable interface. Normally, readline is configured via a |
|
558 | 558 | file which defines the behavior of the library; the details of the |
|
559 | 559 | syntax for this can be found in the readline documentation available |
|
560 | 560 | with your system or on the Internet. IPython doesn't read this file (if |
|
561 | 561 | it exists) directly, but it does support passing to readline valid |
|
562 | 562 | options via a simple interface. In brief, you can customize readline by |
|
563 | 563 | setting the following options in your configuration file (note |
|
564 | 564 | that these options can not be specified at the command line): |
|
565 | 565 | |
|
566 | 566 | * **readline_parse_and_bind**: this holds a list of strings to be executed |
|
567 | 567 | via a readline.parse_and_bind() command. The syntax for valid commands |
|
568 | 568 | of this kind can be found by reading the documentation for the GNU |
|
569 | 569 | readline library, as these commands are of the kind which readline |
|
570 | 570 | accepts in its configuration file. |
|
571 | 571 | * **readline_remove_delims**: a string of characters to be removed |
|
572 | 572 | from the default word-delimiters list used by readline, so that |
|
573 | 573 | completions may be performed on strings which contain them. Do not |
|
574 | 574 | change the default value unless you know what you're doing. |
|
575 | 575 | |
|
576 | 576 | You will find the default values in your configuration file. |
|
577 | 577 | |
|
578 | 578 | |
|
579 | 579 | Session logging and restoring |
|
580 | 580 | ----------------------------- |
|
581 | 581 | |
|
582 | 582 | You can log all input from a session either by starting IPython with the |
|
583 | 583 | command line switch ``--logfile=foo.py`` (see :ref:`here <command_line_options>`) |
|
584 | 584 | or by activating the logging at any moment with the magic function %logstart. |
|
585 | 585 | |
|
586 | 586 | Log files can later be reloaded by running them as scripts and IPython |
|
587 | 587 | will attempt to 'replay' the log by executing all the lines in it, thus |
|
588 | 588 | restoring the state of a previous session. This feature is not quite |
|
589 | 589 | perfect, but can still be useful in many cases. |
|
590 | 590 | |
|
591 | 591 | The log files can also be used as a way to have a permanent record of |
|
592 | 592 | any code you wrote while experimenting. Log files are regular text files |
|
593 | 593 | which you can later open in your favorite text editor to extract code or |
|
594 | 594 | to 'clean them up' before using them to replay a session. |
|
595 | 595 | |
|
596 | 596 | The `%logstart` function for activating logging in mid-session is used as |
|
597 | 597 | follows:: |
|
598 | 598 | |
|
599 | 599 | %logstart [log_name [log_mode]] |
|
600 | 600 | |
|
601 | 601 | If no name is given, it defaults to a file named 'ipython_log.py' in your |
|
602 | 602 | current working directory, in 'rotate' mode (see below). |
|
603 | 603 | |
|
604 | 604 | '%logstart name' saves to file 'name' in 'backup' mode. It saves your |
|
605 | 605 | history up to that point and then continues logging. |
|
606 | 606 | |
|
607 | 607 | %logstart takes a second optional parameter: logging mode. This can be |
|
608 | 608 | one of (note that the modes are given unquoted): |
|
609 | 609 | |
|
610 | 610 | * [over:] overwrite existing log_name. |
|
611 | 611 | * [backup:] rename (if exists) to log_name~ and start log_name. |
|
612 | 612 | * [append:] well, that says it. |
|
613 | 613 | * [rotate:] create rotating logs log_name.1~, log_name.2~, etc. |
|
614 | 614 | |
|
615 | 615 | The %logoff and %logon functions allow you to temporarily stop and |
|
616 | 616 | resume logging to a file which had previously been started with |
|
617 | 617 | %logstart. They will fail (with an explanation) if you try to use them |
|
618 | 618 | before logging has been started. |
|
619 | 619 | |
|
620 | 620 | .. _system_shell_access: |
|
621 | 621 | |
|
622 | 622 | System shell access |
|
623 | 623 | ------------------- |
|
624 | 624 | |
|
625 | 625 | Any input line beginning with a ! character is passed verbatim (minus |
|
626 | 626 | the !, of course) to the underlying operating system. For example, |
|
627 | 627 | typing ``!ls`` will run 'ls' in the current directory. |
|
628 | 628 | |
|
629 | 629 | Manual capture of command output |
|
630 | 630 | -------------------------------- |
|
631 | 631 | |
|
632 | 632 | You can assign the result of a system command to a Python variable with the |
|
633 | 633 | syntax ``myfiles = !ls``. This gets machine readable output from stdout |
|
634 | 634 | (e.g. without colours), and splits on newlines. To explicitly get this sort of |
|
635 | 635 | output without assigning to a variable, use two exclamation marks (``!!ls``) or |
|
636 | 636 | the ``%sx`` magic command. |
|
637 | 637 | |
|
638 | 638 | The captured list has some convenience features. ``myfiles.n`` or ``myfiles.s`` |
|
639 | 639 | returns a string delimited by newlines or spaces, respectively. ``myfiles.p`` |
|
640 | 640 | produces `path objects <http://pypi.python.org/pypi/path.py>`_ from the list items. |
|
641 | 641 | See :ref:`string_lists` for details. |
|
642 | 642 | |
|
643 | 643 | IPython also allows you to expand the value of python variables when |
|
644 | 644 | making system calls. Wrap variables or expressions in {braces}:: |
|
645 | 645 | |
|
646 | 646 | In [1]: pyvar = 'Hello world' |
|
647 | 647 | In [2]: !echo "A python variable: {pyvar}" |
|
648 | 648 | A python variable: Hello world |
|
649 | 649 | In [3]: import math |
|
650 | 650 | In [4]: x = 8 |
|
651 | 651 | In [5]: !echo {math.factorial(x)} |
|
652 | 652 | 40320 |
|
653 | 653 | |
|
654 | 654 | For simple cases, you can alternatively prepend $ to a variable name:: |
|
655 | 655 | |
|
656 | 656 | In [6]: !echo $sys.argv |
|
657 | 657 | [/home/fperez/usr/bin/ipython] |
|
658 | 658 | In [7]: !echo "A system variable: $$HOME" # Use $$ for literal $ |
|
659 | 659 | A system variable: /home/fperez |
|
660 | 660 | |
|
661 | 661 | System command aliases |
|
662 | 662 | ---------------------- |
|
663 | 663 | |
|
664 | 664 | The %alias magic function allows you to define magic functions which are in fact |
|
665 | 665 | system shell commands. These aliases can have parameters. |
|
666 | 666 | |
|
667 | 667 | ``%alias alias_name cmd`` defines 'alias_name' as an alias for 'cmd' |
|
668 | 668 | |
|
669 | 669 | Then, typing ``alias_name params`` will execute the system command 'cmd |
|
670 | 670 | params' (from your underlying operating system). |
|
671 | 671 | |
|
672 | 672 | You can also define aliases with parameters using %s specifiers (one per |
|
673 | 673 | parameter). The following example defines the parts function as an |
|
674 | 674 | alias to the command 'echo first %s second %s' where each %s will be |
|
675 | 675 | replaced by a positional parameter to the call to %parts:: |
|
676 | 676 | |
|
677 | 677 | In [1]: %alias parts echo first %s second %s |
|
678 | 678 | In [2]: parts A B |
|
679 | 679 | first A second B |
|
680 | 680 | In [3]: parts A |
|
681 | 681 | ERROR: Alias <parts> requires 2 arguments, 1 given. |
|
682 | 682 | |
|
683 | 683 | If called with no parameters, %alias prints the table of currently |
|
684 | 684 | defined aliases. |
|
685 | 685 | |
|
686 | 686 | The %rehashx magic allows you to load your entire $PATH as |
|
687 | 687 | ipython aliases. See its docstring for further details. |
|
688 | 688 | |
|
689 | 689 | |
|
690 | 690 | .. _dreload: |
|
691 | 691 | |
|
692 | 692 | Recursive reload |
|
693 | 693 | ---------------- |
|
694 | 694 | |
|
695 | 695 | The :mod:`IPython.lib.deepreload` module allows you to recursively reload a |
|
696 | 696 | module: changes made to any of its dependencies will be reloaded without |
|
697 | 697 | having to exit. To start using it, do:: |
|
698 | 698 | |
|
699 | 699 | from IPython.lib.deepreload import reload as dreload |
|
700 | 700 | |
|
701 | 701 | |
|
702 | 702 | Verbose and colored exception traceback printouts |
|
703 | 703 | ------------------------------------------------- |
|
704 | 704 | |
|
705 | 705 | IPython provides the option to see very detailed exception tracebacks, |
|
706 | 706 | which can be especially useful when debugging large programs. You can |
|
707 | 707 | run any Python file with the %run function to benefit from these |
|
708 | 708 | detailed tracebacks. Furthermore, both normal and verbose tracebacks can |
|
709 | 709 | be colored (if your terminal supports it) which makes them much easier |
|
710 | 710 | to parse visually. |
|
711 | 711 | |
|
712 | 712 | See the magic xmode and colors functions for details (just type %magic). |
|
713 | 713 | |
|
714 | 714 | These features are basically a terminal version of Ka-Ping Yee's cgitb |
|
715 | 715 | module, now part of the standard Python library. |
|
716 | 716 | |
|
717 | 717 | |
|
718 | 718 | .. _input_caching: |
|
719 | 719 | |
|
720 | 720 | Input caching system |
|
721 | 721 | -------------------- |
|
722 | 722 | |
|
723 | 723 | IPython offers numbered prompts (In/Out) with input and output caching |
|
724 | 724 | (also referred to as 'input history'). All input is saved and can be |
|
725 | 725 | retrieved as variables (besides the usual arrow key recall), in |
|
726 | 726 | addition to the %rep magic command that brings a history entry |
|
727 | 727 | up for editing on the next command line. |
|
728 | 728 | |
|
729 | 729 | The following GLOBAL variables always exist (so don't overwrite them!): |
|
730 | 730 | |
|
731 | 731 | * _i, _ii, _iii: store previous, next previous and next-next previous inputs. |
|
732 | 732 | * In, _ih : a list of all inputs; _ih[n] is the input from line n. If you |
|
733 | 733 | overwrite In with a variable of your own, you can remake the assignment to the |
|
734 | 734 | internal list with a simple ``In=_ih``. |
|
735 | 735 | |
|
736 | 736 | Additionally, global variables named _i<n> are dynamically created (<n> |
|
737 | 737 | being the prompt counter), so ``_i<n> == _ih[<n>] == In[<n>]``. |
|
738 | 738 | |
|
739 | 739 | For example, what you typed at prompt 14 is available as _i14, _ih[14] |
|
740 | 740 | and In[14]. |
|
741 | 741 | |
|
742 | 742 | This allows you to easily cut and paste multi line interactive prompts |
|
743 | 743 | by printing them out: they print like a clean string, without prompt |
|
744 | 744 | characters. You can also manipulate them like regular variables (they |
|
745 | 745 | are strings), modify or exec them (typing ``exec _i9`` will re-execute the |
|
746 | 746 | contents of input prompt 9. |
|
747 | 747 | |
|
748 | 748 | You can also re-execute multiple lines of input easily by using the |
|
749 | 749 | magic %rerun or %macro functions. The macro system also allows you to re-execute |
|
750 | 750 | previous lines which include magic function calls (which require special |
|
751 | 751 | processing). Type %macro? for more details on the macro system. |
|
752 | 752 | |
|
753 | 753 | A history function %hist allows you to see any part of your input |
|
754 | 754 | history by printing a range of the _i variables. |
|
755 | 755 | |
|
756 | 756 | You can also search ('grep') through your history by typing |
|
757 | 757 | ``%hist -g somestring``. This is handy for searching for URLs, IP addresses, |
|
758 | 758 | etc. You can bring history entries listed by '%hist -g' up for editing |
|
759 | 759 | with the %recall command, or run them immediately with %rerun. |
|
760 | 760 | |
|
761 | 761 | .. _output_caching: |
|
762 | 762 | |
|
763 | 763 | Output caching system |
|
764 | 764 | --------------------- |
|
765 | 765 | |
|
766 | 766 | For output that is returned from actions, a system similar to the input |
|
767 | 767 | cache exists but using _ instead of _i. Only actions that produce a |
|
768 | 768 | result (NOT assignments, for example) are cached. If you are familiar |
|
769 | 769 | with Mathematica, IPython's _ variables behave exactly like |
|
770 | 770 | Mathematica's % variables. |
|
771 | 771 | |
|
772 | 772 | The following GLOBAL variables always exist (so don't overwrite them!): |
|
773 | 773 | |
|
774 | 774 | * [_] (a single underscore) : stores previous output, like Python's |
|
775 | 775 | default interpreter. |
|
776 | 776 | * [__] (two underscores): next previous. |
|
777 | 777 | * [___] (three underscores): next-next previous. |
|
778 | 778 | |
|
779 | 779 | Additionally, global variables named _<n> are dynamically created (<n> |
|
780 | 780 | being the prompt counter), such that the result of output <n> is always |
|
781 | 781 | available as _<n> (don't use the angle brackets, just the number, e.g. |
|
782 | 782 | _21). |
|
783 | 783 | |
|
784 | 784 | These variables are also stored in a global dictionary (not a |
|
785 | 785 | list, since it only has entries for lines which returned a result) |
|
786 | 786 | available under the names _oh and Out (similar to _ih and In). So the |
|
787 | 787 | output from line 12 can be obtained as _12, Out[12] or _oh[12]. If you |
|
788 | 788 | accidentally overwrite the Out variable you can recover it by typing |
|
789 | 789 | 'Out=_oh' at the prompt. |
|
790 | 790 | |
|
791 | 791 | This system obviously can potentially put heavy memory demands on your |
|
792 | 792 | system, since it prevents Python's garbage collector from removing any |
|
793 | 793 | previously computed results. You can control how many results are kept |
|
794 | 794 | in memory with the option (at the command line or in your configuration |
|
795 | 795 | file) cache_size. If you set it to 0, the whole system is completely |
|
796 | 796 | disabled and the prompts revert to the classic '>>>' of normal Python. |
|
797 | 797 | |
|
798 | 798 | |
|
799 | 799 | Directory history |
|
800 | 800 | ----------------- |
|
801 | 801 | |
|
802 | 802 | Your history of visited directories is kept in the global list _dh, and |
|
803 | 803 | the magic %cd command can be used to go to any entry in that list. The |
|
804 | 804 | %dhist command allows you to view this history. Do ``cd -<TAB>`` to |
|
805 | 805 | conveniently view the directory history. |
|
806 | 806 | |
|
807 | 807 | |
|
808 | 808 | Automatic parentheses and quotes |
|
809 | 809 | -------------------------------- |
|
810 | 810 | |
|
811 | 811 | These features were adapted from Nathan Gray's LazyPython. They are |
|
812 | 812 | meant to allow less typing for common situations. |
|
813 | 813 | |
|
814 | 814 | |
|
815 | 815 | Automatic parentheses |
|
816 | 816 | +++++++++++++++++++++ |
|
817 | 817 | |
|
818 | 818 | Callable objects (i.e. functions, methods, etc) can be invoked like this |
|
819 | 819 | (notice the commas between the arguments):: |
|
820 | 820 | |
|
821 | 821 | In [1]: callable_ob arg1, arg2, arg3 |
|
822 | 822 | ------> callable_ob(arg1, arg2, arg3) |
|
823 | 823 | |
|
824 | 824 | You can force automatic parentheses by using '/' as the first character |
|
825 | 825 | of a line. For example:: |
|
826 | 826 | |
|
827 | 827 | In [2]: /globals # becomes 'globals()' |
|
828 | 828 | |
|
829 | 829 | Note that the '/' MUST be the first character on the line! This won't work:: |
|
830 | 830 | |
|
831 | 831 | In [3]: print /globals # syntax error |
|
832 | 832 | |
|
833 | 833 | In most cases the automatic algorithm should work, so you should rarely |
|
834 | 834 | need to explicitly invoke /. One notable exception is if you are trying |
|
835 | 835 | to call a function with a list of tuples as arguments (the parenthesis |
|
836 | 836 | will confuse IPython):: |
|
837 | 837 | |
|
838 | 838 | In [4]: zip (1,2,3),(4,5,6) # won't work |
|
839 | 839 | |
|
840 | 840 | but this will work:: |
|
841 | 841 | |
|
842 | 842 | In [5]: /zip (1,2,3),(4,5,6) |
|
843 | 843 | ------> zip ((1,2,3),(4,5,6)) |
|
844 | 844 | Out[5]: [(1, 4), (2, 5), (3, 6)] |
|
845 | 845 | |
|
846 | 846 | IPython tells you that it has altered your command line by displaying |
|
847 | 847 | the new command line preceded by ->. e.g.:: |
|
848 | 848 | |
|
849 | 849 | In [6]: callable list |
|
850 | 850 | ------> callable(list) |
|
851 | 851 | |
|
852 | 852 | |
|
853 | 853 | Automatic quoting |
|
854 | 854 | +++++++++++++++++ |
|
855 | 855 | |
|
856 | 856 | You can force automatic quoting of a function's arguments by using ',' |
|
857 | 857 | or ';' as the first character of a line. For example:: |
|
858 | 858 | |
|
859 | 859 | In [1]: ,my_function /home/me # becomes my_function("/home/me") |
|
860 | 860 | |
|
861 | 861 | If you use ';' the whole argument is quoted as a single string, while ',' splits |
|
862 | 862 | on whitespace:: |
|
863 | 863 | |
|
864 | 864 | In [2]: ,my_function a b c # becomes my_function("a","b","c") |
|
865 | 865 | |
|
866 | 866 | In [3]: ;my_function a b c # becomes my_function("a b c") |
|
867 | 867 | |
|
868 | 868 | Note that the ',' or ';' MUST be the first character on the line! This |
|
869 | 869 | won't work:: |
|
870 | 870 | |
|
871 | 871 | In [4]: x = ,my_function /home/me # syntax error |
|
872 | 872 | |
|
873 | 873 | IPython as your default Python environment |
|
874 | 874 | ========================================== |
|
875 | 875 | |
|
876 | 876 | Python honors the environment variable PYTHONSTARTUP and will execute at |
|
877 | 877 | startup the file referenced by this variable. If you put the following code at |
|
878 | 878 | the end of that file, then IPython will be your working environment anytime you |
|
879 | 879 | start Python:: |
|
880 | 880 | |
|
881 | 881 | from IPython.frontend.terminal.ipapp import launch_new_instance |
|
882 | 882 | launch_new_instance() |
|
883 | 883 | raise SystemExit |
|
884 | 884 | |
|
885 | 885 | The ``raise SystemExit`` is needed to exit Python when |
|
886 | 886 | it finishes, otherwise you'll be back at the normal Python '>>>' |
|
887 | 887 | prompt. |
|
888 | 888 | |
|
889 | 889 | This is probably useful to developers who manage multiple Python |
|
890 | 890 | versions and don't want to have correspondingly multiple IPython |
|
891 | 891 | versions. Note that in this mode, there is no way to pass IPython any |
|
892 | 892 | command-line options, as those are trapped first by Python itself. |
|
893 | 893 | |
|
894 | 894 | .. _Embedding: |
|
895 | 895 | |
|
896 | 896 | Embedding IPython |
|
897 | 897 | ================= |
|
898 | 898 | |
|
899 | 899 | It is possible to start an IPython instance inside your own Python |
|
900 | 900 | programs. This allows you to evaluate dynamically the state of your |
|
901 | 901 | code, operate with your variables, analyze them, etc. Note however that |
|
902 | 902 | any changes you make to values while in the shell do not propagate back |
|
903 | 903 | to the running code, so it is safe to modify your values because you |
|
904 | 904 | won't break your code in bizarre ways by doing so. |
|
905 | 905 | |
|
906 | 906 | .. note:: |
|
907 | 907 | |
|
908 | 908 | At present, trying to embed IPython from inside IPython causes problems. Run |
|
909 | 909 | the code samples below outside IPython. |
|
910 | 910 | |
|
911 | 911 | This feature allows you to easily have a fully functional python |
|
912 | 912 | environment for doing object introspection anywhere in your code with a |
|
913 | 913 | simple function call. In some cases a simple print statement is enough, |
|
914 | 914 | but if you need to do more detailed analysis of a code fragment this |
|
915 | 915 | feature can be very valuable. |
|
916 | 916 | |
|
917 | 917 | It can also be useful in scientific computing situations where it is |
|
918 | 918 | common to need to do some automatic, computationally intensive part and |
|
919 | 919 | then stop to look at data, plots, etc. |
|
920 | 920 | Opening an IPython instance will give you full access to your data and |
|
921 | 921 | functions, and you can resume program execution once you are done with |
|
922 | 922 | the interactive part (perhaps to stop again later, as many times as |
|
923 | 923 | needed). |
|
924 | 924 | |
|
925 | 925 | The following code snippet is the bare minimum you need to include in |
|
926 | 926 | your Python programs for this to work (detailed examples follow later):: |
|
927 | 927 | |
|
928 | 928 | from IPython import embed |
|
929 | 929 | |
|
930 | 930 | embed() # this call anywhere in your program will start IPython |
|
931 | 931 | |
|
932 | 932 | You can run embedded instances even in code which is itself being run at |
|
933 | 933 | the IPython interactive prompt with '%run <filename>'. Since it's easy |
|
934 | 934 | to get lost as to where you are (in your top-level IPython or in your |
|
935 | 935 | embedded one), it's a good idea in such cases to set the in/out prompts |
|
936 | 936 | to something different for the embedded instances. The code examples |
|
937 | 937 | below illustrate this. |
|
938 | 938 | |
|
939 | 939 | You can also have multiple IPython instances in your program and open |
|
940 | 940 | them separately, for example with different options for data |
|
941 | 941 | presentation. If you close and open the same instance multiple times, |
|
942 | 942 | its prompt counters simply continue from each execution to the next. |
|
943 | 943 | |
|
944 | 944 | Please look at the docstrings in the :mod:`~IPython.frontend.terminal.embed` |
|
945 | 945 | module for more details on the use of this system. |
|
946 | 946 | |
|
947 | 947 | The following sample file illustrating how to use the embedding |
|
948 | 948 | functionality is provided in the examples directory as example-embed.py. |
|
949 | 949 | It should be fairly self-explanatory: |
|
950 | 950 | |
|
951 | 951 | .. literalinclude:: ../../examples/core/example-embed.py |
|
952 | 952 | :language: python |
|
953 | 953 | |
|
954 | 954 | Once you understand how the system functions, you can use the following |
|
955 | 955 | code fragments in your programs which are ready for cut and paste: |
|
956 | 956 | |
|
957 | 957 | .. literalinclude:: ../../examples/core/example-embed-short.py |
|
958 | 958 | :language: python |
|
959 | 959 | |
|
960 | 960 | Using the Python debugger (pdb) |
|
961 | 961 | =============================== |
|
962 | 962 | |
|
963 | 963 | Running entire programs via pdb |
|
964 | 964 | ------------------------------- |
|
965 | 965 | |
|
966 | 966 | pdb, the Python debugger, is a powerful interactive debugger which |
|
967 | 967 | allows you to step through code, set breakpoints, watch variables, |
|
968 | 968 | etc. IPython makes it very easy to start any script under the control |
|
969 | 969 | of pdb, regardless of whether you have wrapped it into a 'main()' |
|
970 | 970 | function or not. For this, simply type '%run -d myscript' at an |
|
971 | 971 | IPython prompt. See the %run command's documentation (via '%run?' or |
|
972 | 972 | in Sec. magic_ for more details, including how to control where pdb |
|
973 | 973 | will stop execution first. |
|
974 | 974 | |
|
975 | 975 | For more information on the use of the pdb debugger, read the included |
|
976 | 976 | pdb.doc file (part of the standard Python distribution). On a stock |
|
977 | 977 | Linux system it is located at /usr/lib/python2.3/pdb.doc, but the |
|
978 | 978 | easiest way to read it is by using the help() function of the pdb module |
|
979 | 979 | as follows (in an IPython prompt):: |
|
980 | 980 | |
|
981 | 981 | In [1]: import pdb |
|
982 | 982 | In [2]: pdb.help() |
|
983 | 983 | |
|
984 | 984 | This will load the pdb.doc document in a file viewer for you automatically. |
|
985 | 985 | |
|
986 | 986 | |
|
987 | 987 | Automatic invocation of pdb on exceptions |
|
988 | 988 | ----------------------------------------- |
|
989 | 989 | |
|
990 | 990 | IPython, if started with the ``--pdb`` option (or if the option is set in |
|
991 | 991 | your config file) can call the Python pdb debugger every time your code |
|
992 | 992 | triggers an uncaught exception. This feature |
|
993 | 993 | can also be toggled at any time with the %pdb magic command. This can be |
|
994 | 994 | extremely useful in order to find the origin of subtle bugs, because pdb |
|
995 | 995 | opens up at the point in your code which triggered the exception, and |
|
996 | 996 | while your program is at this point 'dead', all the data is still |
|
997 | 997 | available and you can walk up and down the stack frame and understand |
|
998 | 998 | the origin of the problem. |
|
999 | 999 | |
|
1000 | 1000 | Furthermore, you can use these debugging facilities both with the |
|
1001 | 1001 | embedded IPython mode and without IPython at all. For an embedded shell |
|
1002 | 1002 | (see sec. Embedding_), simply call the constructor with |
|
1003 | 1003 | ``--pdb`` in the argument string and pdb will automatically be called if an |
|
1004 | 1004 | uncaught exception is triggered by your code. |
|
1005 | 1005 | |
|
1006 | 1006 | For stand-alone use of the feature in your programs which do not use |
|
1007 | 1007 | IPython at all, put the following lines toward the top of your 'main' |
|
1008 | 1008 | routine:: |
|
1009 | 1009 | |
|
1010 | 1010 | import sys |
|
1011 | 1011 | from IPython.core import ultratb |
|
1012 | 1012 | sys.excepthook = ultratb.FormattedTB(mode='Verbose', |
|
1013 | 1013 | color_scheme='Linux', call_pdb=1) |
|
1014 | 1014 | |
|
1015 | 1015 | The mode keyword can be either 'Verbose' or 'Plain', giving either very |
|
1016 | 1016 | detailed or normal tracebacks respectively. The color_scheme keyword can |
|
1017 | 1017 | be one of 'NoColor', 'Linux' (default) or 'LightBG'. These are the same |
|
1018 | 1018 | options which can be set in IPython with ``--colors`` and ``--xmode``. |
|
1019 | 1019 | |
|
1020 | 1020 | This will give any of your programs detailed, colored tracebacks with |
|
1021 | 1021 | automatic invocation of pdb. |
|
1022 | 1022 | |
|
1023 | 1023 | |
|
1024 | 1024 | Extensions for syntax processing |
|
1025 | 1025 | ================================ |
|
1026 | 1026 | |
|
1027 | 1027 | This isn't for the faint of heart, because the potential for breaking |
|
1028 | 1028 | things is quite high. But it can be a very powerful and useful feature. |
|
1029 | 1029 | In a nutshell, you can redefine the way IPython processes the user input |
|
1030 | 1030 | line to accept new, special extensions to the syntax without needing to |
|
1031 | 1031 | change any of IPython's own code. |
|
1032 | 1032 | |
|
1033 | 1033 | In the IPython/extensions directory you will find some examples |
|
1034 | 1034 | supplied, which we will briefly describe now. These can be used 'as is' |
|
1035 | 1035 | (and both provide very useful functionality), or you can use them as a |
|
1036 | 1036 | starting point for writing your own extensions. |
|
1037 | 1037 | |
|
1038 | 1038 | .. _pasting_with_prompts: |
|
1039 | 1039 | |
|
1040 | 1040 | Pasting of code starting with Python or IPython prompts |
|
1041 | 1041 | ------------------------------------------------------- |
|
1042 | 1042 | |
|
1043 | 1043 | IPython is smart enough to filter out input prompts, be they plain Python ones |
|
1044 | 1044 | (``>>>`` and ``...``) or IPython ones (``In [N]:`` and `` ...:``). You can |
|
1045 | 1045 | therefore copy and paste from existing interactive sessions without worry. |
|
1046 | 1046 | |
|
1047 | 1047 | The following is a 'screenshot' of how things work, copying an example from the |
|
1048 | 1048 | standard Python tutorial:: |
|
1049 | 1049 | |
|
1050 | 1050 | In [1]: >>> # Fibonacci series: |
|
1051 | 1051 | |
|
1052 | 1052 | In [2]: ... # the sum of two elements defines the next |
|
1053 | 1053 | |
|
1054 | 1054 | In [3]: ... a, b = 0, 1 |
|
1055 | 1055 | |
|
1056 | 1056 | In [4]: >>> while b < 10: |
|
1057 | 1057 | ...: ... print b |
|
1058 | 1058 | ...: ... a, b = b, a+b |
|
1059 | 1059 | ...: |
|
1060 | 1060 | 1 |
|
1061 | 1061 | 1 |
|
1062 | 1062 | 2 |
|
1063 | 1063 | 3 |
|
1064 | 1064 | 5 |
|
1065 | 1065 | 8 |
|
1066 | 1066 | |
|
1067 | 1067 | And pasting from IPython sessions works equally well:: |
|
1068 | 1068 | |
|
1069 | 1069 | In [1]: In [5]: def f(x): |
|
1070 | 1070 | ...: ...: "A simple function" |
|
1071 | 1071 | ...: ...: return x**2 |
|
1072 | 1072 | ...: ...: |
|
1073 | 1073 | |
|
1074 | 1074 | In [2]: f(3) |
|
1075 | 1075 | Out[2]: 9 |
|
1076 | 1076 | |
|
1077 | 1077 | .. _gui_support: |
|
1078 | 1078 | |
|
1079 | 1079 | GUI event loop support |
|
1080 | 1080 | ====================== |
|
1081 | 1081 | |
|
1082 | 1082 | .. versionadded:: 0.11 |
|
1083 | 1083 | The ``%gui`` magic and :mod:`IPython.lib.inputhook`. |
|
1084 | 1084 | |
|
1085 | 1085 | IPython has excellent support for working interactively with Graphical User |
|
1086 | 1086 | Interface (GUI) toolkits, such as wxPython, PyQt4/PySide, PyGTK and Tk. This is |
|
1087 | 1087 | implemented using Python's builtin ``PyOSInputHook`` hook. This implementation |
|
1088 | 1088 | is extremely robust compared to our previous thread-based version. The |
|
1089 | 1089 | advantages of this are: |
|
1090 | 1090 | |
|
1091 | 1091 | * GUIs can be enabled and disabled dynamically at runtime. |
|
1092 | 1092 | * The active GUI can be switched dynamically at runtime. |
|
1093 | 1093 | * In some cases, multiple GUIs can run simultaneously with no problems. |
|
1094 | 1094 | * There is a developer API in :mod:`IPython.lib.inputhook` for customizing |
|
1095 | 1095 | all of these things. |
|
1096 | 1096 | |
|
1097 | 1097 | For users, enabling GUI event loop integration is simple. You simple use the |
|
1098 | 1098 | ``%gui`` magic as follows:: |
|
1099 | 1099 | |
|
1100 | 1100 | %gui [GUINAME] |
|
1101 | 1101 | |
|
1102 | 1102 | With no arguments, ``%gui`` removes all GUI support. Valid ``GUINAME`` |
|
1103 | 1103 | arguments are ``wx``, ``qt``, ``gtk`` and ``tk``. |
|
1104 | 1104 | |
|
1105 | 1105 | Thus, to use wxPython interactively and create a running :class:`wx.App` |
|
1106 | 1106 | object, do:: |
|
1107 | 1107 | |
|
1108 | 1108 | %gui wx |
|
1109 | 1109 | |
|
1110 | 1110 | For information on IPython's Matplotlib integration (and the ``pylab`` mode) |
|
1111 | 1111 | see :ref:`this section <matplotlib_support>`. |
|
1112 | 1112 | |
|
1113 | 1113 | For developers that want to use IPython's GUI event loop integration in the |
|
1114 | 1114 | form of a library, these capabilities are exposed in library form in the |
|
1115 | 1115 | :mod:`IPython.lib.inputhook` and :mod:`IPython.lib.guisupport` modules. |
|
1116 | 1116 | Interested developers should see the module docstrings for more information, |
|
1117 | 1117 | but there are a few points that should be mentioned here. |
|
1118 | 1118 | |
|
1119 | 1119 | First, the ``PyOSInputHook`` approach only works in command line settings |
|
1120 | 1120 | where readline is activated. The integration with various eventloops |
|
1121 | 1121 | is handled somewhat differently (and more simply) when using the standalone |
|
1122 | 1122 | kernel, as in the qtconsole and notebook. |
|
1123 | 1123 | |
|
1124 | 1124 | Second, when using the ``PyOSInputHook`` approach, a GUI application should |
|
1125 | 1125 | *not* start its event loop. Instead all of this is handled by the |
|
1126 | 1126 | ``PyOSInputHook``. This means that applications that are meant to be used both |
|
1127 | 1127 | in IPython and as standalone apps need to have special code to detects how the |
|
1128 | 1128 | application is being run. We highly recommend using IPython's support for this. |
|
1129 | 1129 | Since the details vary slightly between toolkits, we point you to the various |
|
1130 | 1130 | examples in our source directory :file:`docs/examples/lib` that demonstrate |
|
1131 | 1131 | these capabilities. |
|
1132 | 1132 | |
|
1133 | 1133 | .. warning:: |
|
1134 | 1134 | |
|
1135 | 1135 | The WX version of this is currently broken. While ``--pylab=wx`` works |
|
1136 | 1136 | fine, standalone WX apps do not. See |
|
1137 | 1137 | https://github.com/ipython/ipython/issues/645 for details of our progress on |
|
1138 | 1138 | this issue. |
|
1139 | 1139 | |
|
1140 | 1140 | |
|
1141 | 1141 | Third, unlike previous versions of IPython, we no longer "hijack" (replace |
|
1142 | 1142 | them with no-ops) the event loops. This is done to allow applications that |
|
1143 | 1143 | actually need to run the real event loops to do so. This is often needed to |
|
1144 | 1144 | process pending events at critical points. |
|
1145 | 1145 | |
|
1146 | 1146 | Finally, we also have a number of examples in our source directory |
|
1147 | 1147 | :file:`docs/examples/lib` that demonstrate these capabilities. |
|
1148 | 1148 | |
|
1149 | 1149 | PyQt and PySide |
|
1150 | 1150 | --------------- |
|
1151 | 1151 | |
|
1152 | 1152 | .. attempt at explanation of the complete mess that is Qt support |
|
1153 | 1153 | |
|
1154 | 1154 | When you use ``--gui=qt`` or ``--pylab=qt``, IPython can work with either |
|
1155 | 1155 | PyQt4 or PySide. There are three options for configuration here, because |
|
1156 | 1156 | PyQt4 has two APIs for QString and QVariant - v1, which is the default on |
|
1157 | 1157 | Python 2, and the more natural v2, which is the only API supported by PySide. |
|
1158 | 1158 | v2 is also the default for PyQt4 on Python 3. IPython's code for the QtConsole |
|
1159 | 1159 | uses v2, but you can still use any interface in your code, since the |
|
1160 | 1160 | Qt frontend is in a different process. |
|
1161 | 1161 | |
|
1162 | 1162 | The default will be to import PyQt4 without configuration of the APIs, thus |
|
1163 | 1163 | matching what most applications would expect. It will fall back of PySide if |
|
1164 | 1164 | PyQt4 is unavailable. |
|
1165 | 1165 | |
|
1166 | 1166 | If specified, IPython will respect the environment variable ``QT_API`` used |
|
1167 | 1167 | by ETS. ETS 4.0 also works with both PyQt4 and PySide, but it requires |
|
1168 | 1168 | PyQt4 to use its v2 API. So if ``QT_API=pyside`` PySide will be used, |
|
1169 | 1169 | and if ``QT_API=pyqt`` then PyQt4 will be used *with the v2 API* for |
|
1170 | 1170 | QString and QVariant, so ETS codes like MayaVi will also work with IPython. |
|
1171 | 1171 | |
|
1172 | 1172 | If you launch IPython in pylab mode with ``ipython --pylab=qt``, then IPython |
|
1173 | 1173 | will ask matplotlib which Qt library to use (only if QT_API is *not set*), via |
|
1174 | 1174 | the 'backend.qt4' rcParam. If matplotlib is version 1.0.1 or older, then |
|
1175 | 1175 | IPython will always use PyQt4 without setting the v2 APIs, since neither v2 |
|
1176 | 1176 | PyQt nor PySide work. |
|
1177 | 1177 | |
|
1178 | 1178 | .. warning:: |
|
1179 | 1179 | |
|
1180 | 1180 | Note that this means for ETS 4 to work with PyQt4, ``QT_API`` *must* be set |
|
1181 | 1181 | to work with IPython's qt integration, because otherwise PyQt4 will be |
|
1182 | 1182 | loaded in an incompatible mode. |
|
1183 | 1183 | |
|
1184 | 1184 | It also means that you must *not* have ``QT_API`` set if you want to |
|
1185 | 1185 | use ``--gui=qt`` with code that requires PyQt4 API v1. |
|
1186 | 1186 | |
|
1187 | 1187 | |
|
1188 | 1188 | .. _matplotlib_support: |
|
1189 | 1189 | |
|
1190 | 1190 | Plotting with matplotlib |
|
1191 | 1191 | ======================== |
|
1192 | 1192 | |
|
1193 | 1193 | `Matplotlib`_ provides high quality 2D and 3D plotting for Python. Matplotlib |
|
1194 | 1194 | can produce plots on screen using a variety of GUI toolkits, including Tk, |
|
1195 | 1195 | PyGTK, PyQt4 and wxPython. It also provides a number of commands useful for |
|
1196 | 1196 | scientific computing, all with a syntax compatible with that of the popular |
|
1197 | 1197 | Matlab program. |
|
1198 | 1198 | |
|
1199 | 1199 | To start IPython with matplotlib support, use the ``--pylab`` switch. If no |
|
1200 | 1200 | arguments are given, IPython will automatically detect your choice of |
|
1201 | 1201 | matplotlib backend. You can also request a specific backend with |
|
1202 | 1202 | ``--pylab=backend``, where ``backend`` must be one of: 'tk', 'qt', 'wx', 'gtk', |
|
1203 | 1203 | 'osx'. |
|
1204 | 1204 | |
|
1205 | 1205 | .. _Matplotlib: http://matplotlib.sourceforge.net |
|
1206 | 1206 | |
|
1207 | 1207 | .. _interactive_demos: |
|
1208 | 1208 | |
|
1209 | 1209 | Interactive demos with IPython |
|
1210 | 1210 | ============================== |
|
1211 | 1211 | |
|
1212 | 1212 | IPython ships with a basic system for running scripts interactively in |
|
1213 | 1213 | sections, useful when presenting code to audiences. A few tags embedded |
|
1214 | 1214 | in comments (so that the script remains valid Python code) divide a file |
|
1215 | 1215 | into separate blocks, and the demo can be run one block at a time, with |
|
1216 | 1216 | IPython printing (with syntax highlighting) the block before executing |
|
1217 | 1217 | it, and returning to the interactive prompt after each block. The |
|
1218 | 1218 | interactive namespace is updated after each block is run with the |
|
1219 | 1219 | contents of the demo's namespace. |
|
1220 | 1220 | |
|
1221 | 1221 | This allows you to show a piece of code, run it and then execute |
|
1222 | 1222 | interactively commands based on the variables just created. Once you |
|
1223 | 1223 | want to continue, you simply execute the next block of the demo. The |
|
1224 | 1224 | following listing shows the markup necessary for dividing a script into |
|
1225 | 1225 | sections for execution as a demo: |
|
1226 | 1226 | |
|
1227 | 1227 | .. literalinclude:: ../../examples/lib/example-demo.py |
|
1228 | 1228 | :language: python |
|
1229 | 1229 | |
|
1230 | 1230 | In order to run a file as a demo, you must first make a Demo object out |
|
1231 | 1231 | of it. If the file is named myscript.py, the following code will make a |
|
1232 | 1232 | demo:: |
|
1233 | 1233 | |
|
1234 | 1234 | from IPython.lib.demo import Demo |
|
1235 | 1235 | |
|
1236 | 1236 | mydemo = Demo('myscript.py') |
|
1237 | 1237 | |
|
1238 | 1238 | This creates the mydemo object, whose blocks you run one at a time by |
|
1239 | 1239 | simply calling the object with no arguments. If you have autocall active |
|
1240 | 1240 | in IPython (the default), all you need to do is type:: |
|
1241 | 1241 | |
|
1242 | 1242 | mydemo |
|
1243 | 1243 | |
|
1244 | 1244 | and IPython will call it, executing each block. Demo objects can be |
|
1245 | 1245 | restarted, you can move forward or back skipping blocks, re-execute the |
|
1246 | 1246 | last block, etc. Simply use the Tab key on a demo object to see its |
|
1247 | 1247 | methods, and call '?' on them to see their docstrings for more usage |
|
1248 | 1248 | details. In addition, the demo module itself contains a comprehensive |
|
1249 | 1249 | docstring, which you can access via:: |
|
1250 | 1250 | |
|
1251 | 1251 | from IPython.lib import demo |
|
1252 | 1252 | |
|
1253 | 1253 | demo? |
|
1254 | 1254 | |
|
1255 | 1255 | Limitations: It is important to note that these demos are limited to |
|
1256 | 1256 | fairly simple uses. In particular, you cannot break up sections within |
|
1257 | 1257 | indented code (loops, if statements, function definitions, etc.) |
|
1258 | 1258 | Supporting something like this would basically require tracking the |
|
1259 | 1259 | internal execution state of the Python interpreter, so only top-level |
|
1260 | 1260 | divisions are allowed. If you want to be able to open an IPython |
|
1261 | 1261 | instance at an arbitrary point in a program, you can use IPython's |
|
1262 | 1262 | embedding facilities, see :func:`IPython.embed` for details. |
|
1263 | 1263 |
@@ -1,293 +1,294 b'' | |||
|
1 | 1 | .. _ipython_as_shell: |
|
2 | 2 | |
|
3 | 3 | ========================= |
|
4 | 4 | IPython as a system shell |
|
5 | 5 | ========================= |
|
6 | 6 | |
|
7 | 7 | .. warning:: |
|
8 | 8 | |
|
9 | 9 | As of the 0.11 version of IPython, most of the APIs used by the shell |
|
10 | 10 | profile have been changed, so the profile currently does very little |
|
11 | 11 | beyond changing the IPython prompt. To help restore the shell |
|
12 | 12 | profile to past functionality described here, the old code is found in |
|
13 | 13 | :file:`IPython/deathrow`, which needs to be updated to use the |
|
14 | 14 | APIs in 0.11. |
|
15 | 15 | |
|
16 | 16 | Overview |
|
17 | 17 | ======== |
|
18 | 18 | |
|
19 | 19 | The 'sh' profile optimizes IPython for system shell usage. Apart from |
|
20 | 20 | certain job control functionality that is present in unix (ctrl+z does |
|
21 | 21 | "suspend"), the sh profile should provide you with most of the |
|
22 | 22 | functionality you use daily in system shell, and more. Invoke IPython |
|
23 | 23 | in 'sh' profile by doing 'ipython -p sh', or (in win32) by launching |
|
24 | 24 | the "pysh" shortcut in start menu. |
|
25 | 25 | |
|
26 | 26 | If you want to use the features of sh profile as your defaults (which |
|
27 | 27 | might be a good idea if you use other profiles a lot of the time but |
|
28 | 28 | still want the convenience of sh profile), add ``import ipy_profile_sh`` |
|
29 | 29 | to your $IPYTHON_DIR/ipy_user_conf.py. |
|
30 | 30 | |
|
31 | 31 | The 'sh' profile is different from the default profile in that: |
|
32 | 32 | |
|
33 | 33 | * Prompt shows the current directory |
|
34 | 34 | * Spacing between prompts and input is more compact (no padding with |
|
35 | 35 | empty lines). The startup banner is more compact as well. |
|
36 | 36 | * System commands are directly available (in alias table) without |
|
37 | 37 | requesting %rehashx - however, if you install new programs along |
|
38 | 38 | your PATH, you might want to run %rehashx to update the persistent |
|
39 | 39 | alias table |
|
40 | 40 | * Macros are stored in raw format by default. That is, instead of |
|
41 | 41 | '_ip.system("cat foo"), the macro will contain text 'cat foo') |
|
42 | 42 | * Autocall is in full mode |
|
43 | 43 | * Calling "up" does "cd .." |
|
44 | 44 | |
|
45 | 45 | The 'sh' profile is different from the now-obsolete (and unavailable) |
|
46 | 46 | 'pysh' profile in that the ``$$var = command`` and ``$var = command`` syntax is |
|
47 | 47 | not supported anymore. Use ``var = !command`` instead (which is available in all |
|
48 | 48 | IPython profiles). |
|
49 | 49 | |
|
50 | 50 | Aliases |
|
51 | 51 | ======= |
|
52 | 52 | |
|
53 | 53 | All of your $PATH has been loaded as IPython aliases, so you should be |
|
54 | 54 | able to type any normal system command and have it executed. See |
|
55 | 55 | %alias? and %unalias? for details on the alias facilities. See also |
|
56 | 56 | %rehashx? for details on the mechanism used to load $PATH. |
|
57 | 57 | |
|
58 | 58 | |
|
59 | 59 | Directory management |
|
60 | 60 | ==================== |
|
61 | 61 | |
|
62 | 62 | Since each command passed by ipython to the underlying system is executed |
|
63 | 63 | in a subshell which exits immediately, you can NOT use !cd to navigate |
|
64 | 64 | the filesystem. |
|
65 | 65 | |
|
66 | 66 | IPython provides its own builtin '%cd' magic command to move in the |
|
67 | 67 | filesystem (the % is not required with automagic on). It also maintains |
|
68 | 68 | a list of visited directories (use %dhist to see it) and allows direct |
|
69 | 69 | switching to any of them. Type 'cd?' for more details. |
|
70 | 70 | |
|
71 | 71 | %pushd, %popd and %dirs are provided for directory stack handling. |
|
72 | 72 | |
|
73 | 73 | |
|
74 | 74 | Enabled extensions |
|
75 | 75 | ================== |
|
76 | 76 | |
|
77 | 77 | Some extensions, listed below, are enabled as default in this profile. |
|
78 | 78 | |
|
79 | 79 | envpersist |
|
80 | 80 | ---------- |
|
81 | 81 | |
|
82 | 82 | %env can be used to "remember" environment variable manipulations. Examples:: |
|
83 | 83 | |
|
84 | 84 | %env - Show all environment variables |
|
85 | 85 | %env VISUAL=jed - set VISUAL to jed |
|
86 | 86 | %env PATH+=;/foo - append ;foo to PATH |
|
87 | 87 | %env PATH+=;/bar - also append ;bar to PATH |
|
88 | 88 | %env PATH-=/wbin; - prepend /wbin; to PATH |
|
89 | 89 | %env -d VISUAL - forget VISUAL persistent val |
|
90 | 90 | %env -p - print all persistent env modifications |
|
91 | 91 | |
|
92 | 92 | ipy_which |
|
93 | 93 | --------- |
|
94 | 94 | |
|
95 | 95 | %which magic command. Like 'which' in unix, but knows about ipython aliases. |
|
96 | 96 | |
|
97 | 97 | Example:: |
|
98 | 98 | |
|
99 | 99 | [C:/ipython]|14> %which st |
|
100 | 100 | st -> start . |
|
101 | 101 | [C:/ipython]|15> %which d |
|
102 | 102 | d -> dir /w /og /on |
|
103 | 103 | [C:/ipython]|16> %which cp |
|
104 | 104 | cp -> cp |
|
105 | 105 | == c:\bin\cp.exe |
|
106 | 106 | c:\bin\cp.exe |
|
107 | 107 | |
|
108 | 108 | ipy_app_completers |
|
109 | 109 | ------------------ |
|
110 | 110 | |
|
111 | 111 | Custom tab completers for some apps like svn, hg, bzr, apt-get. Try 'apt-get install <TAB>' in debian/ubuntu. |
|
112 | 112 | |
|
113 | 113 | ipy_rehashdir |
|
114 | 114 | ------------- |
|
115 | 115 | |
|
116 | 116 | Allows you to add system command aliases for commands that are not along your path. Let's say that you just installed Putty and want to be able to invoke it without adding it to path, you can create the alias for it with rehashdir:: |
|
117 | 117 | |
|
118 | 118 | [~]|22> cd c:/opt/PuTTY/ |
|
119 | 119 | [c:opt/PuTTY]|23> rehashdir . |
|
120 | 120 | <23> ['pageant', 'plink', 'pscp', 'psftp', 'putty', 'puttygen', 'unins000'] |
|
121 | 121 | |
|
122 | 122 | Now, you can execute any of those commams directly:: |
|
123 | 123 | |
|
124 | 124 | [c:opt/PuTTY]|24> cd |
|
125 | 125 | [~]|25> putty |
|
126 | 126 | |
|
127 | 127 | (the putty window opens). |
|
128 | 128 | |
|
129 | 129 | If you want to store the alias so that it will always be available, do '%store putty'. If you want to %store all these aliases persistently, just do it in a for loop:: |
|
130 | 130 | |
|
131 | 131 | [~]|27> for a in _23: |
|
132 | 132 | |..> %store $a |
|
133 | 133 | |..> |
|
134 | 134 | |..> |
|
135 | 135 | Alias stored: pageant (0, 'c:\\opt\\PuTTY\\pageant.exe') |
|
136 | 136 | Alias stored: plink (0, 'c:\\opt\\PuTTY\\plink.exe') |
|
137 | 137 | Alias stored: pscp (0, 'c:\\opt\\PuTTY\\pscp.exe') |
|
138 | 138 | Alias stored: psftp (0, 'c:\\opt\\PuTTY\\psftp.exe') |
|
139 | 139 | ... |
|
140 | 140 | |
|
141 | 141 | mglob |
|
142 | 142 | ----- |
|
143 | 143 | |
|
144 | 144 | Provide the magic function %mglob, which makes it easier (than the 'find' command) to collect (possibly recursive) file lists. Examples:: |
|
145 | 145 | |
|
146 | 146 | [c:/ipython]|9> mglob *.py |
|
147 | 147 | [c:/ipython]|10> mglob *.py rec:*.txt |
|
148 | 148 | [c:/ipython]|19> workfiles = %mglob !.svn/ !.hg/ !*_Data/ !*.bak rec:. |
|
149 | 149 | |
|
150 | 150 | Note that the first 2 calls will put the file list in result history (_, _9, _10), and the last one will assign it to 'workfiles'. |
|
151 | 151 | |
|
152 | 152 | |
|
153 | 153 | Prompt customization |
|
154 | 154 | ==================== |
|
155 | 155 | |
|
156 | 156 | The sh profile uses the following prompt configurations:: |
|
157 | 157 | |
|
158 | o.prompt_in1= r'\C_LightBlue[\C_LightCyan\Y2\C_LightBlue]\C_Green|\#>' | |
|
159 | o.prompt_in2= r'\C_Green|\C_LightGreen\D\C_Green>' | |
|
158 | c.PromptManager.in_template = r'{color.LightGreen}\u@\h{color.LightBlue}[{color.LightCyan}\Y1{color.LightBlue}]{color.Green}|\#> ' | |
|
159 | c.PromptManager.in2_template = r'{color.Green}|{color.LightGreen}\D{color.Green}> ' | |
|
160 | c.PromptManager.out_template = r'<\#> ' | |
|
160 | 161 | |
|
161 | 162 | You can change the prompt configuration to your liking by editing |
|
162 | 163 | ipython_config.py. |
|
163 | 164 | |
|
164 | 165 | .. _string_lists: |
|
165 | 166 | |
|
166 | 167 | String lists |
|
167 | 168 | ============ |
|
168 | 169 | |
|
169 | 170 | String lists (IPython.utils.text.SList) are handy way to process output |
|
170 | 171 | from system commands. They are produced by ``var = !cmd`` syntax. |
|
171 | 172 | |
|
172 | 173 | First, we acquire the output of 'ls -l':: |
|
173 | 174 | |
|
174 | 175 | [Q:doc/examples]|2> lines = !ls -l |
|
175 | 176 | == |
|
176 | 177 | ['total 23', |
|
177 | 178 | '-rw-rw-rw- 1 ville None 1163 Sep 30 2006 example-demo.py', |
|
178 | 179 | '-rw-rw-rw- 1 ville None 1927 Sep 30 2006 example-embed-short.py', |
|
179 | 180 | '-rwxrwxrwx 1 ville None 4606 Sep 1 17:15 example-embed.py', |
|
180 | 181 | '-rwxrwxrwx 1 ville None 1017 Sep 30 2006 example-gnuplot.py', |
|
181 | 182 | '-rwxrwxrwx 1 ville None 339 Jun 11 18:01 extension.py', |
|
182 | 183 | '-rwxrwxrwx 1 ville None 113 Dec 20 2006 seteditor.py', |
|
183 | 184 | '-rwxrwxrwx 1 ville None 245 Dec 12 2006 seteditor.pyc'] |
|
184 | 185 | |
|
185 | 186 | Now, let's take a look at the contents of 'lines' (the first number is |
|
186 | 187 | the list element number):: |
|
187 | 188 | |
|
188 | 189 | [Q:doc/examples]|3> lines |
|
189 | 190 | <3> SList (.p, .n, .l, .s, .grep(), .fields() available). Value: |
|
190 | 191 | |
|
191 | 192 | 0: total 23 |
|
192 | 193 | 1: -rw-rw-rw- 1 ville None 1163 Sep 30 2006 example-demo.py |
|
193 | 194 | 2: -rw-rw-rw- 1 ville None 1927 Sep 30 2006 example-embed-short.py |
|
194 | 195 | 3: -rwxrwxrwx 1 ville None 4606 Sep 1 17:15 example-embed.py |
|
195 | 196 | 4: -rwxrwxrwx 1 ville None 1017 Sep 30 2006 example-gnuplot.py |
|
196 | 197 | 5: -rwxrwxrwx 1 ville None 339 Jun 11 18:01 extension.py |
|
197 | 198 | 6: -rwxrwxrwx 1 ville None 113 Dec 20 2006 seteditor.py |
|
198 | 199 | 7: -rwxrwxrwx 1 ville None 245 Dec 12 2006 seteditor.pyc |
|
199 | 200 | |
|
200 | 201 | Now, let's filter out the 'embed' lines:: |
|
201 | 202 | |
|
202 | 203 | [Q:doc/examples]|4> l2 = lines.grep('embed',prune=1) |
|
203 | 204 | [Q:doc/examples]|5> l2 |
|
204 | 205 | <5> SList (.p, .n, .l, .s, .grep(), .fields() available). Value: |
|
205 | 206 | |
|
206 | 207 | 0: total 23 |
|
207 | 208 | 1: -rw-rw-rw- 1 ville None 1163 Sep 30 2006 example-demo.py |
|
208 | 209 | 2: -rwxrwxrwx 1 ville None 1017 Sep 30 2006 example-gnuplot.py |
|
209 | 210 | 3: -rwxrwxrwx 1 ville None 339 Jun 11 18:01 extension.py |
|
210 | 211 | 4: -rwxrwxrwx 1 ville None 113 Dec 20 2006 seteditor.py |
|
211 | 212 | 5: -rwxrwxrwx 1 ville None 245 Dec 12 2006 seteditor.pyc |
|
212 | 213 | |
|
213 | 214 | Now, we want strings having just file names and permissions:: |
|
214 | 215 | |
|
215 | 216 | [Q:doc/examples]|6> l2.fields(8,0) |
|
216 | 217 | <6> SList (.p, .n, .l, .s, .grep(), .fields() available). Value: |
|
217 | 218 | |
|
218 | 219 | 0: total |
|
219 | 220 | 1: example-demo.py -rw-rw-rw- |
|
220 | 221 | 2: example-gnuplot.py -rwxrwxrwx |
|
221 | 222 | 3: extension.py -rwxrwxrwx |
|
222 | 223 | 4: seteditor.py -rwxrwxrwx |
|
223 | 224 | 5: seteditor.pyc -rwxrwxrwx |
|
224 | 225 | |
|
225 | 226 | Note how the line with 'total' does not raise IndexError. |
|
226 | 227 | |
|
227 | 228 | If you want to split these (yielding lists), call fields() without |
|
228 | 229 | arguments:: |
|
229 | 230 | |
|
230 | 231 | [Q:doc/examples]|7> _.fields() |
|
231 | 232 | <7> |
|
232 | 233 | [['total'], |
|
233 | 234 | ['example-demo.py', '-rw-rw-rw-'], |
|
234 | 235 | ['example-gnuplot.py', '-rwxrwxrwx'], |
|
235 | 236 | ['extension.py', '-rwxrwxrwx'], |
|
236 | 237 | ['seteditor.py', '-rwxrwxrwx'], |
|
237 | 238 | ['seteditor.pyc', '-rwxrwxrwx']] |
|
238 | 239 | |
|
239 | 240 | If you want to pass these separated with spaces to a command (typical |
|
240 | 241 | for lists if files), use the .s property:: |
|
241 | 242 | |
|
242 | 243 | |
|
243 | 244 | [Q:doc/examples]|13> files = l2.fields(8).s |
|
244 | 245 | [Q:doc/examples]|14> files |
|
245 | 246 | <14> 'example-demo.py example-gnuplot.py extension.py seteditor.py seteditor.pyc' |
|
246 | 247 | [Q:doc/examples]|15> ls $files |
|
247 | 248 | example-demo.py example-gnuplot.py extension.py seteditor.py seteditor.pyc |
|
248 | 249 | |
|
249 | 250 | SLists are inherited from normal python lists, so every list method is |
|
250 | 251 | available:: |
|
251 | 252 | |
|
252 | 253 | [Q:doc/examples]|21> lines.append('hey') |
|
253 | 254 | |
|
254 | 255 | |
|
255 | 256 | Real world example: remove all files outside version control |
|
256 | 257 | ------------------------------------------------------------ |
|
257 | 258 | |
|
258 | 259 | First, capture output of "hg status":: |
|
259 | 260 | |
|
260 | 261 | [Q:/ipython]|28> out = !hg status |
|
261 | 262 | == |
|
262 | 263 | ['M IPython\\extensions\\ipy_kitcfg.py', |
|
263 | 264 | 'M IPython\\extensions\\ipy_rehashdir.py', |
|
264 | 265 | ... |
|
265 | 266 | '? build\\lib\\IPython\\Debugger.py', |
|
266 | 267 | '? build\\lib\\IPython\\extensions\\InterpreterExec.py', |
|
267 | 268 | '? build\\lib\\IPython\\extensions\\InterpreterPasteInput.py', |
|
268 | 269 | ... |
|
269 | 270 | |
|
270 | 271 | (lines starting with ? are not under version control). |
|
271 | 272 | |
|
272 | 273 | :: |
|
273 | 274 | |
|
274 | 275 | [Q:/ipython]|35> junk = out.grep(r'^\?').fields(1) |
|
275 | 276 | [Q:/ipython]|36> junk |
|
276 | 277 | <36> SList (.p, .n, .l, .s, .grep(), .fields() availab |
|
277 | 278 | ... |
|
278 | 279 | 10: build\bdist.win32\winexe\temp\_ctypes.py |
|
279 | 280 | 11: build\bdist.win32\winexe\temp\_hashlib.py |
|
280 | 281 | 12: build\bdist.win32\winexe\temp\_socket.py |
|
281 | 282 | |
|
282 | 283 | Now we can just remove these files by doing 'rm $junk.s'. |
|
283 | 284 | |
|
284 | 285 | The .s, .n, .p properties |
|
285 | 286 | ------------------------- |
|
286 | 287 | |
|
287 | 288 | The ``.s`` property returns one string where lines are separated by |
|
288 | 289 | single space (for convenient passing to system commands). The ``.n`` |
|
289 | 290 | property return one string where the lines are separated by a newline |
|
290 | 291 | (i.e. the original output of the function). If the items in string |
|
291 | 292 | list are file names, ``.p`` can be used to get a list of "path" objects |
|
292 | 293 | for convenient file manipulation. |
|
293 | 294 |
General Comments 0
You need to be logged in to leave comments.
Login now