Show More
@@ -1,274 +1,273 b'' | |||
|
1 | 1 | """hooks for IPython. |
|
2 | 2 | |
|
3 | 3 | In Python, it is possible to overwrite any method of any object if you really |
|
4 | 4 | want to. But IPython exposes a few 'hooks', methods which are _designed_ to |
|
5 | 5 | be overwritten by users for customization purposes. This module defines the |
|
6 | 6 | default versions of all such hooks, which get used by IPython if not |
|
7 | 7 | overridden by the user. |
|
8 | 8 | |
|
9 | 9 | hooks are simple functions, but they should be declared with 'self' as their |
|
10 | 10 | first argument, because when activated they are registered into IPython as |
|
11 | 11 | instance methods. The self argument will be the IPython running instance |
|
12 | 12 | itself, so hooks have full access to the entire IPython object. |
|
13 | 13 | |
|
14 | 14 | If you wish to define a new hook and activate it, you need to put the |
|
15 | 15 | necessary code into a python file which can be either imported or execfile()'d |
|
16 | 16 | from within your ipythonrc configuration. |
|
17 | 17 | |
|
18 | 18 | For example, suppose that you have a module called 'myiphooks' in your |
|
19 | 19 | PYTHONPATH, which contains the following definition: |
|
20 | 20 | |
|
21 | 21 | import os |
|
22 | 22 | from IPython.core import ipapi |
|
23 | 23 | ip = ipapi.get() |
|
24 | 24 | |
|
25 | 25 | def calljed(self,filename, linenum): |
|
26 | 26 | "My editor hook calls the jed editor directly." |
|
27 | 27 | print "Calling my own editor, jed ..." |
|
28 | 28 | if os.system('jed +%d %s' % (linenum,filename)) != 0: |
|
29 | 29 | raise TryNext() |
|
30 | 30 | |
|
31 | 31 | ip.set_hook('editor', calljed) |
|
32 | 32 | |
|
33 | 33 | You can then enable the functionality by doing 'import myiphooks' |
|
34 | 34 | somewhere in your configuration files or ipython command line. |
|
35 | 35 | """ |
|
36 | 36 | |
|
37 | 37 | #***************************************************************************** |
|
38 | 38 | # Copyright (C) 2005 Fernando Perez. <fperez@colorado.edu> |
|
39 | 39 | # |
|
40 | 40 | # Distributed under the terms of the BSD License. The full license is in |
|
41 | 41 | # the file COPYING, distributed as part of this software. |
|
42 | 42 | #***************************************************************************** |
|
43 | 43 | |
|
44 | 44 | import os, bisect |
|
45 | 45 | import sys |
|
46 | 46 | from IPython.utils.genutils import Term, shell |
|
47 | 47 | from pprint import PrettyPrinter |
|
48 | 48 | |
|
49 | 49 | from IPython.core.error import TryNext |
|
50 | 50 | |
|
51 | 51 | # List here all the default hooks. For now it's just the editor functions |
|
52 | 52 | # but over time we'll move here all the public API for user-accessible things. |
|
53 | 53 | |
|
54 | 54 | __all__ = ['editor', 'fix_error_editor', 'synchronize_with_editor', 'result_display', |
|
55 | 55 | 'input_prefilter', 'shutdown_hook', 'late_startup_hook', |
|
56 | 56 | 'generate_prompt', 'generate_output_prompt','shell_hook', |
|
57 | 57 | 'show_in_pager','pre_prompt_hook', 'pre_runcode_hook', |
|
58 | 58 | 'clipboard_get'] |
|
59 | 59 | |
|
60 | 60 | pformat = PrettyPrinter().pformat |
|
61 | 61 | |
|
62 | 62 | def editor(self,filename, linenum=None): |
|
63 | 63 | """Open the default editor at the given filename and linenumber. |
|
64 | 64 | |
|
65 | 65 | This is IPython's default editor hook, you can use it as an example to |
|
66 | 66 | write your own modified one. To set your own editor function as the |
|
67 | 67 | new editor hook, call ip.set_hook('editor',yourfunc).""" |
|
68 | 68 | |
|
69 | 69 | # IPython configures a default editor at startup by reading $EDITOR from |
|
70 | 70 | # the environment, and falling back on vi (unix) or notepad (win32). |
|
71 | 71 | editor = self.editor |
|
72 | 72 | |
|
73 | 73 | # marker for at which line to open the file (for existing objects) |
|
74 | 74 | if linenum is None or editor=='notepad': |
|
75 | 75 | linemark = '' |
|
76 | 76 | else: |
|
77 | 77 | linemark = '+%d' % int(linenum) |
|
78 | 78 | |
|
79 | 79 | # Enclose in quotes if necessary and legal |
|
80 | 80 | if ' ' in editor and os.path.isfile(editor) and editor[0] != '"': |
|
81 | 81 | editor = '"%s"' % editor |
|
82 | 82 | |
|
83 | 83 | # Call the actual editor |
|
84 | 84 | if os.system('%s %s %s' % (editor,linemark,filename)) != 0: |
|
85 | 85 | raise TryNext() |
|
86 | 86 | |
|
87 | 87 | import tempfile |
|
88 | 88 | def fix_error_editor(self,filename,linenum,column,msg): |
|
89 | 89 | """Open the editor at the given filename, linenumber, column and |
|
90 | 90 | show an error message. This is used for correcting syntax errors. |
|
91 | 91 | The current implementation only has special support for the VIM editor, |
|
92 | 92 | and falls back on the 'editor' hook if VIM is not used. |
|
93 | 93 | |
|
94 | 94 | Call ip.set_hook('fix_error_editor',youfunc) to use your own function, |
|
95 | 95 | """ |
|
96 | 96 | def vim_quickfix_file(): |
|
97 | 97 | t = tempfile.NamedTemporaryFile() |
|
98 | 98 | t.write('%s:%d:%d:%s\n' % (filename,linenum,column,msg)) |
|
99 | 99 | t.flush() |
|
100 | 100 | return t |
|
101 | 101 | if os.path.basename(self.editor) != 'vim': |
|
102 | 102 | self.hooks.editor(filename,linenum) |
|
103 | 103 | return |
|
104 | 104 | t = vim_quickfix_file() |
|
105 | 105 | try: |
|
106 | 106 | if os.system('vim --cmd "set errorformat=%f:%l:%c:%m" -q ' + t.name): |
|
107 | 107 | raise TryNext() |
|
108 | 108 | finally: |
|
109 | 109 | t.close() |
|
110 | 110 | |
|
111 | 111 | |
|
112 | 112 | def synchronize_with_editor(self, filename, linenum, column): |
|
113 | 113 | pass |
|
114 | 114 | |
|
115 | 115 | |
|
116 | 116 | class CommandChainDispatcher: |
|
117 | 117 | """ Dispatch calls to a chain of commands until some func can handle it |
|
118 | 118 | |
|
119 | 119 | Usage: instantiate, execute "add" to add commands (with optional |
|
120 | 120 | priority), execute normally via f() calling mechanism. |
|
121 | 121 | |
|
122 | 122 | """ |
|
123 | 123 | def __init__(self,commands=None): |
|
124 | 124 | if commands is None: |
|
125 | 125 | self.chain = [] |
|
126 | 126 | else: |
|
127 | 127 | self.chain = commands |
|
128 | 128 | |
|
129 | 129 | |
|
130 | 130 | def __call__(self,*args, **kw): |
|
131 | 131 | """ Command chain is called just like normal func. |
|
132 | 132 | |
|
133 | 133 | This will call all funcs in chain with the same args as were given to this |
|
134 | 134 | function, and return the result of first func that didn't raise |
|
135 | 135 | TryNext """ |
|
136 | 136 | |
|
137 | 137 | for prio,cmd in self.chain: |
|
138 | 138 | #print "prio",prio,"cmd",cmd #dbg |
|
139 | 139 | try: |
|
140 |
ret |
|
|
141 | return ret | |
|
140 | return cmd(*args, **kw) | |
|
142 | 141 | except TryNext, exc: |
|
143 | 142 | if exc.args or exc.kwargs: |
|
144 | 143 | args = exc.args |
|
145 | 144 | kw = exc.kwargs |
|
146 | 145 | # if no function will accept it, raise TryNext up to the caller |
|
147 | 146 | raise TryNext |
|
148 | 147 | |
|
149 | 148 | def __str__(self): |
|
150 | 149 | return str(self.chain) |
|
151 | 150 | |
|
152 | 151 | def add(self, func, priority=0): |
|
153 | 152 | """ Add a func to the cmd chain with given priority """ |
|
154 | 153 | bisect.insort(self.chain,(priority,func)) |
|
155 | 154 | |
|
156 | 155 | def __iter__(self): |
|
157 | 156 | """ Return all objects in chain. |
|
158 | 157 | |
|
159 | 158 | Handy if the objects are not callable. |
|
160 | 159 | """ |
|
161 | 160 | return iter(self.chain) |
|
162 | 161 | |
|
163 | 162 | |
|
164 | 163 | def result_display(self,arg): |
|
165 | 164 | """ Default display hook. |
|
166 | 165 | |
|
167 | 166 | Called for displaying the result to the user. |
|
168 | 167 | """ |
|
169 | 168 | |
|
170 | 169 | if self.pprint: |
|
171 | 170 | out = pformat(arg) |
|
172 | 171 | if '\n' in out: |
|
173 | 172 | # So that multi-line strings line up with the left column of |
|
174 | 173 | # the screen, instead of having the output prompt mess up |
|
175 | 174 | # their first line. |
|
176 | 175 | Term.cout.write('\n') |
|
177 | 176 | print >>Term.cout, out |
|
178 | 177 | else: |
|
179 | 178 | # By default, the interactive prompt uses repr() to display results, |
|
180 | 179 | # so we should honor this. Users who'd rather use a different |
|
181 | 180 | # mechanism can easily override this hook. |
|
182 | 181 | print >>Term.cout, repr(arg) |
|
183 | 182 | # the default display hook doesn't manipulate the value to put in history |
|
184 | 183 | return None |
|
185 | 184 | |
|
186 | 185 | |
|
187 | 186 | def input_prefilter(self,line): |
|
188 | 187 | """ Default input prefilter |
|
189 | 188 | |
|
190 | 189 | This returns the line as unchanged, so that the interpreter |
|
191 | 190 | knows that nothing was done and proceeds with "classic" prefiltering |
|
192 | 191 | (%magics, !shell commands etc.). |
|
193 | 192 | |
|
194 | 193 | Note that leading whitespace is not passed to this hook. Prefilter |
|
195 | 194 | can't alter indentation. |
|
196 | 195 | |
|
197 | 196 | """ |
|
198 | 197 | #print "attempt to rewrite",line #dbg |
|
199 | 198 | return line |
|
200 | 199 | |
|
201 | 200 | |
|
202 | 201 | def shutdown_hook(self): |
|
203 | 202 | """ default shutdown hook |
|
204 | 203 | |
|
205 | 204 | Typically, shotdown hooks should raise TryNext so all shutdown ops are done |
|
206 | 205 | """ |
|
207 | 206 | |
|
208 | 207 | #print "default shutdown hook ok" # dbg |
|
209 | 208 | return |
|
210 | 209 | |
|
211 | 210 | |
|
212 | 211 | def late_startup_hook(self): |
|
213 | 212 | """ Executed after ipython has been constructed and configured |
|
214 | 213 | |
|
215 | 214 | """ |
|
216 | 215 | #print "default startup hook ok" # dbg |
|
217 | 216 | |
|
218 | 217 | |
|
219 | 218 | def generate_prompt(self, is_continuation): |
|
220 | 219 | """ calculate and return a string with the prompt to display """ |
|
221 | 220 | if is_continuation: |
|
222 | 221 | return str(self.outputcache.prompt2) |
|
223 | 222 | return str(self.outputcache.prompt1) |
|
224 | 223 | |
|
225 | 224 | |
|
226 | 225 | def generate_output_prompt(self): |
|
227 | 226 | return str(self.outputcache.prompt_out) |
|
228 | 227 | |
|
229 | 228 | |
|
230 | 229 | def shell_hook(self,cmd): |
|
231 | 230 | """ Run system/shell command a'la os.system() """ |
|
232 | 231 | |
|
233 | 232 | shell(cmd, header=self.system_header, verbose=self.system_verbose) |
|
234 | 233 | |
|
235 | 234 | |
|
236 | 235 | def show_in_pager(self,s): |
|
237 | 236 | """ Run a string through pager """ |
|
238 | 237 | # raising TryNext here will use the default paging functionality |
|
239 | 238 | raise TryNext |
|
240 | 239 | |
|
241 | 240 | |
|
242 | 241 | def pre_prompt_hook(self): |
|
243 | 242 | """ Run before displaying the next prompt |
|
244 | 243 | |
|
245 | 244 | Use this e.g. to display output from asynchronous operations (in order |
|
246 | 245 | to not mess up text entry) |
|
247 | 246 | """ |
|
248 | 247 | |
|
249 | 248 | return None |
|
250 | 249 | |
|
251 | 250 | |
|
252 | 251 | def pre_runcode_hook(self): |
|
253 | 252 | """ Executed before running the (prefiltered) code in IPython """ |
|
254 | 253 | return None |
|
255 | 254 | |
|
256 | 255 | |
|
257 | 256 | def clipboard_get(self): |
|
258 | 257 | """ Get text from the clipboard. |
|
259 | 258 | """ |
|
260 | 259 | from IPython.lib.clipboard import ( |
|
261 | 260 | osx_clipboard_get, tkinter_clipboard_get, |
|
262 | 261 | win32_clipboard_get |
|
263 | 262 | ) |
|
264 | 263 | if sys.platform == 'win32': |
|
265 | 264 | chain = [win32_clipboard_get, tkinter_clipboard_get] |
|
266 | 265 | elif sys.platform == 'darwin': |
|
267 | 266 | chain = [osx_clipboard_get, tkinter_clipboard_get] |
|
268 | 267 | else: |
|
269 | 268 | chain = [tkinter_clipboard_get] |
|
270 | 269 | dispatcher = CommandChainDispatcher() |
|
271 | 270 | for func in chain: |
|
272 | 271 | dispatcher.add(func) |
|
273 | 272 | text = dispatcher() |
|
274 | 273 | return text |
@@ -1,2500 +1,2500 b'' | |||
|
1 | 1 | # -*- coding: utf-8 -*- |
|
2 | 2 | """ |
|
3 | 3 | Main IPython Component |
|
4 | 4 | """ |
|
5 | 5 | |
|
6 | 6 | #----------------------------------------------------------------------------- |
|
7 | 7 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> |
|
8 | 8 | # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu> |
|
9 | 9 | # Copyright (C) 2008-2009 The IPython Development Team |
|
10 | 10 | # |
|
11 | 11 | # Distributed under the terms of the BSD License. The full license is in |
|
12 | 12 | # the file COPYING, distributed as part of this software. |
|
13 | 13 | #----------------------------------------------------------------------------- |
|
14 | 14 | |
|
15 | 15 | #----------------------------------------------------------------------------- |
|
16 | 16 | # Imports |
|
17 | 17 | #----------------------------------------------------------------------------- |
|
18 | 18 | |
|
19 | 19 | from __future__ import with_statement |
|
20 | 20 | |
|
21 | 21 | import __builtin__ |
|
22 | 22 | import StringIO |
|
23 | 23 | import bdb |
|
24 | 24 | import codeop |
|
25 | 25 | import exceptions |
|
26 | 26 | import new |
|
27 | 27 | import os |
|
28 | 28 | import re |
|
29 | 29 | import string |
|
30 | 30 | import sys |
|
31 | 31 | import tempfile |
|
32 | 32 | from contextlib import nested |
|
33 | 33 | |
|
34 | 34 | from IPython.core import debugger, oinspect |
|
35 | 35 | from IPython.core import history as ipcorehist |
|
36 | 36 | from IPython.core import prefilter |
|
37 | 37 | from IPython.core import shadowns |
|
38 | 38 | from IPython.core import ultratb |
|
39 | 39 | from IPython.core.alias import AliasManager |
|
40 | 40 | from IPython.core.builtin_trap import BuiltinTrap |
|
41 | 41 | from IPython.core.component import Component |
|
42 | 42 | from IPython.core.display_trap import DisplayTrap |
|
43 | 43 | from IPython.core.error import TryNext, UsageError |
|
44 | 44 | from IPython.core.fakemodule import FakeModule, init_fakemod_dict |
|
45 | 45 | from IPython.core.logger import Logger |
|
46 | 46 | from IPython.core.magic import Magic |
|
47 | 47 | from IPython.core.prefilter import PrefilterManager |
|
48 | 48 | from IPython.core.prompts import CachedOutput |
|
49 | 49 | from IPython.core.pylabtools import pylab_activate |
|
50 | 50 | from IPython.core.usage import interactive_usage, default_banner |
|
51 | 51 | from IPython.external.Itpl import ItplNS |
|
52 | 52 | from IPython.lib.inputhook import enable_gui |
|
53 | 53 | from IPython.lib.backgroundjobs import BackgroundJobManager |
|
54 | 54 | from IPython.utils import PyColorize |
|
55 | 55 | from IPython.utils import pickleshare |
|
56 | 56 | from IPython.utils.genutils import get_ipython_dir |
|
57 | 57 | from IPython.utils.ipstruct import Struct |
|
58 | 58 | from IPython.utils.platutils import toggle_set_term_title, set_term_title |
|
59 | 59 | from IPython.utils.strdispatch import StrDispatch |
|
60 | 60 | from IPython.utils.syspathcontext import prepended_to_syspath |
|
61 | 61 | |
|
62 | 62 | # XXX - need to clean up this import * line |
|
63 | 63 | from IPython.utils.genutils import * |
|
64 | 64 | |
|
65 | 65 | # from IPython.utils import growl |
|
66 | 66 | # growl.start("IPython") |
|
67 | 67 | |
|
68 | 68 | from IPython.utils.traitlets import ( |
|
69 | 69 | Int, Str, CBool, CaselessStrEnum, Enum, List, Unicode |
|
70 | 70 | ) |
|
71 | 71 | |
|
72 | 72 | #----------------------------------------------------------------------------- |
|
73 | 73 | # Globals |
|
74 | 74 | #----------------------------------------------------------------------------- |
|
75 | 75 | |
|
76 | 76 | # store the builtin raw_input globally, and use this always, in case user code |
|
77 | 77 | # overwrites it (like wx.py.PyShell does) |
|
78 | 78 | raw_input_original = raw_input |
|
79 | 79 | |
|
80 | 80 | # compiled regexps for autoindent management |
|
81 | 81 | dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass') |
|
82 | 82 | |
|
83 | 83 | #----------------------------------------------------------------------------- |
|
84 | 84 | # Utilities |
|
85 | 85 | #----------------------------------------------------------------------------- |
|
86 | 86 | |
|
87 | 87 | ini_spaces_re = re.compile(r'^(\s+)') |
|
88 | 88 | |
|
89 | 89 | |
|
90 | 90 | def num_ini_spaces(strng): |
|
91 | 91 | """Return the number of initial spaces in a string""" |
|
92 | 92 | |
|
93 | 93 | ini_spaces = ini_spaces_re.match(strng) |
|
94 | 94 | if ini_spaces: |
|
95 | 95 | return ini_spaces.end() |
|
96 | 96 | else: |
|
97 | 97 | return 0 |
|
98 | 98 | |
|
99 | 99 | |
|
100 | 100 | def softspace(file, newvalue): |
|
101 | 101 | """Copied from code.py, to remove the dependency""" |
|
102 | 102 | |
|
103 | 103 | oldvalue = 0 |
|
104 | 104 | try: |
|
105 | 105 | oldvalue = file.softspace |
|
106 | 106 | except AttributeError: |
|
107 | 107 | pass |
|
108 | 108 | try: |
|
109 | 109 | file.softspace = newvalue |
|
110 | 110 | except (AttributeError, TypeError): |
|
111 | 111 | # "attribute-less object" or "read-only attributes" |
|
112 | 112 | pass |
|
113 | 113 | return oldvalue |
|
114 | 114 | |
|
115 | 115 | |
|
116 | 116 | class SpaceInInput(exceptions.Exception): pass |
|
117 | 117 | |
|
118 | 118 | class Bunch: pass |
|
119 | 119 | |
|
120 | 120 | class InputList(list): |
|
121 | 121 | """Class to store user input. |
|
122 | 122 | |
|
123 | 123 | It's basically a list, but slices return a string instead of a list, thus |
|
124 | 124 | allowing things like (assuming 'In' is an instance): |
|
125 | 125 | |
|
126 | 126 | exec In[4:7] |
|
127 | 127 | |
|
128 | 128 | or |
|
129 | 129 | |
|
130 | 130 | exec In[5:9] + In[14] + In[21:25]""" |
|
131 | 131 | |
|
132 | 132 | def __getslice__(self,i,j): |
|
133 | 133 | return ''.join(list.__getslice__(self,i,j)) |
|
134 | 134 | |
|
135 | 135 | |
|
136 | 136 | class SyntaxTB(ultratb.ListTB): |
|
137 | 137 | """Extension which holds some state: the last exception value""" |
|
138 | 138 | |
|
139 | 139 | def __init__(self,color_scheme = 'NoColor'): |
|
140 | 140 | ultratb.ListTB.__init__(self,color_scheme) |
|
141 | 141 | self.last_syntax_error = None |
|
142 | 142 | |
|
143 | 143 | def __call__(self, etype, value, elist): |
|
144 | 144 | self.last_syntax_error = value |
|
145 | 145 | ultratb.ListTB.__call__(self,etype,value,elist) |
|
146 | 146 | |
|
147 | 147 | def clear_err_state(self): |
|
148 | 148 | """Return the current error state and clear it""" |
|
149 | 149 | e = self.last_syntax_error |
|
150 | 150 | self.last_syntax_error = None |
|
151 | 151 | return e |
|
152 | 152 | |
|
153 | 153 | |
|
154 | 154 | def get_default_editor(): |
|
155 | 155 | try: |
|
156 | 156 | ed = os.environ['EDITOR'] |
|
157 | 157 | except KeyError: |
|
158 | 158 | if os.name == 'posix': |
|
159 | 159 | ed = 'vi' # the only one guaranteed to be there! |
|
160 | 160 | else: |
|
161 | 161 | ed = 'notepad' # same in Windows! |
|
162 | 162 | return ed |
|
163 | 163 | |
|
164 | 164 | |
|
165 | 165 | def get_default_colors(): |
|
166 | 166 | if sys.platform=='darwin': |
|
167 | 167 | return "LightBG" |
|
168 | 168 | elif os.name=='nt': |
|
169 | 169 | return 'Linux' |
|
170 | 170 | else: |
|
171 | 171 | return 'Linux' |
|
172 | 172 | |
|
173 | 173 | |
|
174 | 174 | class SeparateStr(Str): |
|
175 | 175 | """A Str subclass to validate separate_in, separate_out, etc. |
|
176 | 176 | |
|
177 | 177 | This is a Str based traitlet that converts '0'->'' and '\\n'->'\n'. |
|
178 | 178 | """ |
|
179 | 179 | |
|
180 | 180 | def validate(self, obj, value): |
|
181 | 181 | if value == '0': value = '' |
|
182 | 182 | value = value.replace('\\n','\n') |
|
183 | 183 | return super(SeparateStr, self).validate(obj, value) |
|
184 | 184 | |
|
185 | 185 | |
|
186 | 186 | #----------------------------------------------------------------------------- |
|
187 | 187 | # Main IPython class |
|
188 | 188 | #----------------------------------------------------------------------------- |
|
189 | 189 | |
|
190 | 190 | |
|
191 | 191 | class InteractiveShell(Component, Magic): |
|
192 | 192 | """An enhanced, interactive shell for Python.""" |
|
193 | 193 | |
|
194 | 194 | autocall = Enum((0,1,2), default_value=1, config=True) |
|
195 | 195 | autoedit_syntax = CBool(False, config=True) |
|
196 | 196 | autoindent = CBool(True, config=True) |
|
197 | 197 | automagic = CBool(True, config=True) |
|
198 | 198 | banner = Str('') |
|
199 | 199 | banner1 = Str(default_banner, config=True) |
|
200 | 200 | banner2 = Str('', config=True) |
|
201 | 201 | cache_size = Int(1000, config=True) |
|
202 | 202 | color_info = CBool(True, config=True) |
|
203 | 203 | colors = CaselessStrEnum(('NoColor','LightBG','Linux'), |
|
204 | 204 | default_value=get_default_colors(), config=True) |
|
205 | 205 | confirm_exit = CBool(True, config=True) |
|
206 | 206 | debug = CBool(False, config=True) |
|
207 | 207 | deep_reload = CBool(False, config=True) |
|
208 | 208 | # This display_banner only controls whether or not self.show_banner() |
|
209 | 209 | # is called when mainloop/interact are called. The default is False |
|
210 | 210 | # because for the terminal based application, the banner behavior |
|
211 | 211 | # is controlled by Global.display_banner, which IPythonApp looks at |
|
212 | 212 | # to determine if *it* should call show_banner() by hand or not. |
|
213 | 213 | display_banner = CBool(False) # This isn't configurable! |
|
214 | 214 | embedded = CBool(False) |
|
215 | 215 | embedded_active = CBool(False) |
|
216 | 216 | editor = Str(get_default_editor(), config=True) |
|
217 | 217 | filename = Str("<ipython console>") |
|
218 | 218 | ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__ |
|
219 | 219 | logstart = CBool(False, config=True) |
|
220 | 220 | logfile = Str('', config=True) |
|
221 | 221 | logappend = Str('', config=True) |
|
222 | 222 | object_info_string_level = Enum((0,1,2), default_value=0, |
|
223 | 223 | config=True) |
|
224 | 224 | pager = Str('less', config=True) |
|
225 | 225 | pdb = CBool(False, config=True) |
|
226 | 226 | pprint = CBool(True, config=True) |
|
227 | 227 | profile = Str('', config=True) |
|
228 | 228 | prompt_in1 = Str('In [\\#]: ', config=True) |
|
229 | 229 | prompt_in2 = Str(' .\\D.: ', config=True) |
|
230 | 230 | prompt_out = Str('Out[\\#]: ', config=True) |
|
231 | 231 | prompts_pad_left = CBool(True, config=True) |
|
232 | 232 | quiet = CBool(False, config=True) |
|
233 | 233 | |
|
234 | 234 | readline_use = CBool(True, config=True) |
|
235 | 235 | readline_merge_completions = CBool(True, config=True) |
|
236 | 236 | readline_omit__names = Enum((0,1,2), default_value=0, config=True) |
|
237 | 237 | readline_remove_delims = Str('-/~', config=True) |
|
238 | 238 | readline_parse_and_bind = List([ |
|
239 | 239 | 'tab: complete', |
|
240 | 240 | '"\C-l": possible-completions', |
|
241 | 241 | 'set show-all-if-ambiguous on', |
|
242 | 242 | '"\C-o": tab-insert', |
|
243 | 243 | '"\M-i": " "', |
|
244 | 244 | '"\M-o": "\d\d\d\d"', |
|
245 | 245 | '"\M-I": "\d\d\d\d"', |
|
246 | 246 | '"\C-r": reverse-search-history', |
|
247 | 247 | '"\C-s": forward-search-history', |
|
248 | 248 | '"\C-p": history-search-backward', |
|
249 | 249 | '"\C-n": history-search-forward', |
|
250 | 250 | '"\e[A": history-search-backward', |
|
251 | 251 | '"\e[B": history-search-forward', |
|
252 | 252 | '"\C-k": kill-line', |
|
253 | 253 | '"\C-u": unix-line-discard', |
|
254 | 254 | ], allow_none=False, config=True) |
|
255 | 255 | |
|
256 | 256 | screen_length = Int(0, config=True) |
|
257 | 257 | |
|
258 | 258 | # Use custom TraitletTypes that convert '0'->'' and '\\n'->'\n' |
|
259 | 259 | separate_in = SeparateStr('\n', config=True) |
|
260 | 260 | separate_out = SeparateStr('', config=True) |
|
261 | 261 | separate_out2 = SeparateStr('', config=True) |
|
262 | 262 | |
|
263 | 263 | system_header = Str('IPython system call: ', config=True) |
|
264 | 264 | system_verbose = CBool(False, config=True) |
|
265 | 265 | term_title = CBool(False, config=True) |
|
266 | 266 | wildcards_case_sensitive = CBool(True, config=True) |
|
267 | 267 | xmode = CaselessStrEnum(('Context','Plain', 'Verbose'), |
|
268 | 268 | default_value='Context', config=True) |
|
269 | 269 | |
|
270 | 270 | autoexec = List(allow_none=False) |
|
271 | 271 | |
|
272 | 272 | # class attribute to indicate whether the class supports threads or not. |
|
273 | 273 | # Subclasses with thread support should override this as needed. |
|
274 | 274 | isthreaded = False |
|
275 | 275 | |
|
276 | 276 | def __init__(self, parent=None, config=None, ipython_dir=None, usage=None, |
|
277 | 277 | user_ns=None, user_global_ns=None, |
|
278 | 278 | banner1=None, banner2=None, display_banner=None, |
|
279 | 279 | custom_exceptions=((),None)): |
|
280 | 280 | |
|
281 | 281 | # This is where traitlets with a config_key argument are updated |
|
282 | 282 | # from the values on config. |
|
283 | 283 | super(InteractiveShell, self).__init__(parent, config=config) |
|
284 | 284 | |
|
285 | 285 | # These are relatively independent and stateless |
|
286 | 286 | self.init_ipython_dir(ipython_dir) |
|
287 | 287 | self.init_instance_attrs() |
|
288 | 288 | self.init_term_title() |
|
289 | 289 | self.init_usage(usage) |
|
290 | 290 | self.init_banner(banner1, banner2, display_banner) |
|
291 | 291 | |
|
292 | 292 | # Create namespaces (user_ns, user_global_ns, etc.) |
|
293 | 293 | self.init_create_namespaces(user_ns, user_global_ns) |
|
294 | 294 | # This has to be done after init_create_namespaces because it uses |
|
295 | 295 | # something in self.user_ns, but before init_sys_modules, which |
|
296 | 296 | # is the first thing to modify sys. |
|
297 | 297 | self.save_sys_module_state() |
|
298 | 298 | self.init_sys_modules() |
|
299 | 299 | |
|
300 | 300 | self.init_history() |
|
301 | 301 | self.init_encoding() |
|
302 | 302 | self.init_prefilter() |
|
303 | 303 | |
|
304 | 304 | Magic.__init__(self, self) |
|
305 | 305 | |
|
306 | 306 | self.init_syntax_highlighting() |
|
307 | 307 | self.init_hooks() |
|
308 | 308 | self.init_pushd_popd_magic() |
|
309 | 309 | self.init_traceback_handlers(custom_exceptions) |
|
310 | 310 | self.init_user_ns() |
|
311 | 311 | self.init_logger() |
|
312 | 312 | self.init_alias() |
|
313 | 313 | self.init_builtins() |
|
314 | 314 | |
|
315 | 315 | # pre_config_initialization |
|
316 | 316 | self.init_shadow_hist() |
|
317 | 317 | |
|
318 | 318 | # The next section should contain averything that was in ipmaker. |
|
319 | 319 | self.init_logstart() |
|
320 | 320 | |
|
321 | 321 | # The following was in post_config_initialization |
|
322 | 322 | self.init_inspector() |
|
323 | 323 | self.init_readline() |
|
324 | 324 | self.init_prompts() |
|
325 | 325 | self.init_displayhook() |
|
326 | 326 | self.init_reload_doctest() |
|
327 | 327 | self.init_magics() |
|
328 | 328 | self.init_pdb() |
|
329 | 329 | self.hooks.late_startup_hook() |
|
330 | 330 | |
|
331 | 331 | def get_ipython(self): |
|
332 | 332 | return self |
|
333 | 333 | |
|
334 | 334 | #------------------------------------------------------------------------- |
|
335 | 335 | # Traitlet changed handlers |
|
336 | 336 | #------------------------------------------------------------------------- |
|
337 | 337 | |
|
338 | 338 | def _banner1_changed(self): |
|
339 | 339 | self.compute_banner() |
|
340 | 340 | |
|
341 | 341 | def _banner2_changed(self): |
|
342 | 342 | self.compute_banner() |
|
343 | 343 | |
|
344 | 344 | def _ipython_dir_changed(self, name, new): |
|
345 | 345 | if not os.path.isdir(new): |
|
346 | 346 | os.makedirs(new, mode = 0777) |
|
347 | 347 | if not os.path.isdir(self.ipython_extension_dir): |
|
348 | 348 | os.makedirs(self.ipython_extension_dir, mode = 0777) |
|
349 | 349 | |
|
350 | 350 | @property |
|
351 | 351 | def ipython_extension_dir(self): |
|
352 | 352 | return os.path.join(self.ipython_dir, 'extensions') |
|
353 | 353 | |
|
354 | 354 | @property |
|
355 | 355 | def usable_screen_length(self): |
|
356 | 356 | if self.screen_length == 0: |
|
357 | 357 | return 0 |
|
358 | 358 | else: |
|
359 | 359 | num_lines_bot = self.separate_in.count('\n')+1 |
|
360 | 360 | return self.screen_length - num_lines_bot |
|
361 | 361 | |
|
362 | 362 | def _term_title_changed(self, name, new_value): |
|
363 | 363 | self.init_term_title() |
|
364 | 364 | |
|
365 | 365 | def set_autoindent(self,value=None): |
|
366 | 366 | """Set the autoindent flag, checking for readline support. |
|
367 | 367 | |
|
368 | 368 | If called with no arguments, it acts as a toggle.""" |
|
369 | 369 | |
|
370 | 370 | if not self.has_readline: |
|
371 | 371 | if os.name == 'posix': |
|
372 | 372 | warn("The auto-indent feature requires the readline library") |
|
373 | 373 | self.autoindent = 0 |
|
374 | 374 | return |
|
375 | 375 | if value is None: |
|
376 | 376 | self.autoindent = not self.autoindent |
|
377 | 377 | else: |
|
378 | 378 | self.autoindent = value |
|
379 | 379 | |
|
380 | 380 | #------------------------------------------------------------------------- |
|
381 | 381 | # init_* methods called by __init__ |
|
382 | 382 | #------------------------------------------------------------------------- |
|
383 | 383 | |
|
384 | 384 | def init_ipython_dir(self, ipython_dir): |
|
385 | 385 | if ipython_dir is not None: |
|
386 | 386 | self.ipython_dir = ipython_dir |
|
387 | 387 | self.config.Global.ipython_dir = self.ipython_dir |
|
388 | 388 | return |
|
389 | 389 | |
|
390 | 390 | if hasattr(self.config.Global, 'ipython_dir'): |
|
391 | 391 | self.ipython_dir = self.config.Global.ipython_dir |
|
392 | 392 | else: |
|
393 | 393 | self.ipython_dir = get_ipython_dir() |
|
394 | 394 | |
|
395 | 395 | # All children can just read this |
|
396 | 396 | self.config.Global.ipython_dir = self.ipython_dir |
|
397 | 397 | |
|
398 | 398 | def init_instance_attrs(self): |
|
399 | 399 | self.jobs = BackgroundJobManager() |
|
400 | 400 | self.more = False |
|
401 | 401 | |
|
402 | 402 | # command compiler |
|
403 | 403 | self.compile = codeop.CommandCompiler() |
|
404 | 404 | |
|
405 | 405 | # User input buffer |
|
406 | 406 | self.buffer = [] |
|
407 | 407 | |
|
408 | 408 | # Make an empty namespace, which extension writers can rely on both |
|
409 | 409 | # existing and NEVER being used by ipython itself. This gives them a |
|
410 | 410 | # convenient location for storing additional information and state |
|
411 | 411 | # their extensions may require, without fear of collisions with other |
|
412 | 412 | # ipython names that may develop later. |
|
413 | 413 | self.meta = Struct() |
|
414 | 414 | |
|
415 | 415 | # Object variable to store code object waiting execution. This is |
|
416 | 416 | # used mainly by the multithreaded shells, but it can come in handy in |
|
417 | 417 | # other situations. No need to use a Queue here, since it's a single |
|
418 | 418 | # item which gets cleared once run. |
|
419 | 419 | self.code_to_run = None |
|
420 | 420 | |
|
421 | 421 | # Flag to mark unconditional exit |
|
422 | 422 | self.exit_now = False |
|
423 | 423 | |
|
424 | 424 | # Temporary files used for various purposes. Deleted at exit. |
|
425 | 425 | self.tempfiles = [] |
|
426 | 426 | |
|
427 | 427 | # Keep track of readline usage (later set by init_readline) |
|
428 | 428 | self.has_readline = False |
|
429 | 429 | |
|
430 | 430 | # keep track of where we started running (mainly for crash post-mortem) |
|
431 | 431 | # This is not being used anywhere currently. |
|
432 | 432 | self.starting_dir = os.getcwd() |
|
433 | 433 | |
|
434 | 434 | # Indentation management |
|
435 | 435 | self.indent_current_nsp = 0 |
|
436 | 436 | |
|
437 | 437 | def init_term_title(self): |
|
438 | 438 | # Enable or disable the terminal title. |
|
439 | 439 | if self.term_title: |
|
440 | 440 | toggle_set_term_title(True) |
|
441 | 441 | set_term_title('IPython: ' + abbrev_cwd()) |
|
442 | 442 | else: |
|
443 | 443 | toggle_set_term_title(False) |
|
444 | 444 | |
|
445 | 445 | def init_usage(self, usage=None): |
|
446 | 446 | if usage is None: |
|
447 | 447 | self.usage = interactive_usage |
|
448 | 448 | else: |
|
449 | 449 | self.usage = usage |
|
450 | 450 | |
|
451 | 451 | def init_encoding(self): |
|
452 | 452 | # Get system encoding at startup time. Certain terminals (like Emacs |
|
453 | 453 | # under Win32 have it set to None, and we need to have a known valid |
|
454 | 454 | # encoding to use in the raw_input() method |
|
455 | 455 | try: |
|
456 | 456 | self.stdin_encoding = sys.stdin.encoding or 'ascii' |
|
457 | 457 | except AttributeError: |
|
458 | 458 | self.stdin_encoding = 'ascii' |
|
459 | 459 | |
|
460 | 460 | def init_syntax_highlighting(self): |
|
461 | 461 | # Python source parser/formatter for syntax highlighting |
|
462 | 462 | pyformat = PyColorize.Parser().format |
|
463 | 463 | self.pycolorize = lambda src: pyformat(src,'str',self.colors) |
|
464 | 464 | |
|
465 | 465 | def init_pushd_popd_magic(self): |
|
466 | 466 | # for pushd/popd management |
|
467 | 467 | try: |
|
468 | 468 | self.home_dir = get_home_dir() |
|
469 | 469 | except HomeDirError, msg: |
|
470 | 470 | fatal(msg) |
|
471 | 471 | |
|
472 | 472 | self.dir_stack = [] |
|
473 | 473 | |
|
474 | 474 | def init_logger(self): |
|
475 | 475 | self.logger = Logger(self, logfname='ipython_log.py', logmode='rotate') |
|
476 | 476 | # local shortcut, this is used a LOT |
|
477 | 477 | self.log = self.logger.log |
|
478 | 478 | |
|
479 | 479 | def init_logstart(self): |
|
480 | 480 | if self.logappend: |
|
481 | 481 | self.magic_logstart(self.logappend + ' append') |
|
482 | 482 | elif self.logfile: |
|
483 | 483 | self.magic_logstart(self.logfile) |
|
484 | 484 | elif self.logstart: |
|
485 | 485 | self.magic_logstart() |
|
486 | 486 | |
|
487 | 487 | def init_builtins(self): |
|
488 | 488 | self.builtin_trap = BuiltinTrap(self) |
|
489 | 489 | |
|
490 | 490 | def init_inspector(self): |
|
491 | 491 | # Object inspector |
|
492 | 492 | self.inspector = oinspect.Inspector(oinspect.InspectColors, |
|
493 | 493 | PyColorize.ANSICodeColors, |
|
494 | 494 | 'NoColor', |
|
495 | 495 | self.object_info_string_level) |
|
496 | 496 | |
|
497 | 497 | def init_prompts(self): |
|
498 | 498 | # Initialize cache, set in/out prompts and printing system |
|
499 | 499 | self.outputcache = CachedOutput(self, |
|
500 | 500 | self.cache_size, |
|
501 | 501 | self.pprint, |
|
502 | 502 | input_sep = self.separate_in, |
|
503 | 503 | output_sep = self.separate_out, |
|
504 | 504 | output_sep2 = self.separate_out2, |
|
505 | 505 | ps1 = self.prompt_in1, |
|
506 | 506 | ps2 = self.prompt_in2, |
|
507 | 507 | ps_out = self.prompt_out, |
|
508 | 508 | pad_left = self.prompts_pad_left) |
|
509 | 509 | |
|
510 | 510 | # user may have over-ridden the default print hook: |
|
511 | 511 | try: |
|
512 | 512 | self.outputcache.__class__.display = self.hooks.display |
|
513 | 513 | except AttributeError: |
|
514 | 514 | pass |
|
515 | 515 | |
|
516 | 516 | def init_displayhook(self): |
|
517 | 517 | self.display_trap = DisplayTrap(self, self.outputcache) |
|
518 | 518 | |
|
519 | 519 | def init_reload_doctest(self): |
|
520 | 520 | # Do a proper resetting of doctest, including the necessary displayhook |
|
521 | 521 | # monkeypatching |
|
522 | 522 | try: |
|
523 | 523 | doctest_reload() |
|
524 | 524 | except ImportError: |
|
525 | 525 | warn("doctest module does not exist.") |
|
526 | 526 | |
|
527 | 527 | #------------------------------------------------------------------------- |
|
528 | 528 | # Things related to the banner |
|
529 | 529 | #------------------------------------------------------------------------- |
|
530 | 530 | |
|
531 | 531 | def init_banner(self, banner1, banner2, display_banner): |
|
532 | 532 | if banner1 is not None: |
|
533 | 533 | self.banner1 = banner1 |
|
534 | 534 | if banner2 is not None: |
|
535 | 535 | self.banner2 = banner2 |
|
536 | 536 | if display_banner is not None: |
|
537 | 537 | self.display_banner = display_banner |
|
538 | 538 | self.compute_banner() |
|
539 | 539 | |
|
540 | 540 | def show_banner(self, banner=None): |
|
541 | 541 | if banner is None: |
|
542 | 542 | banner = self.banner |
|
543 | 543 | self.write(banner) |
|
544 | 544 | |
|
545 | 545 | def compute_banner(self): |
|
546 | 546 | self.banner = self.banner1 + '\n' |
|
547 | 547 | if self.profile: |
|
548 | 548 | self.banner += '\nIPython profile: %s\n' % self.profile |
|
549 | 549 | if self.banner2: |
|
550 | 550 | self.banner += '\n' + self.banner2 + '\n' |
|
551 | 551 | |
|
552 | 552 | #------------------------------------------------------------------------- |
|
553 | 553 | # Things related to injections into the sys module |
|
554 | 554 | #------------------------------------------------------------------------- |
|
555 | 555 | |
|
556 | 556 | def save_sys_module_state(self): |
|
557 | 557 | """Save the state of hooks in the sys module. |
|
558 | 558 | |
|
559 | 559 | This has to be called after self.user_ns is created. |
|
560 | 560 | """ |
|
561 | 561 | self._orig_sys_module_state = {} |
|
562 | 562 | self._orig_sys_module_state['stdin'] = sys.stdin |
|
563 | 563 | self._orig_sys_module_state['stdout'] = sys.stdout |
|
564 | 564 | self._orig_sys_module_state['stderr'] = sys.stderr |
|
565 | 565 | self._orig_sys_module_state['excepthook'] = sys.excepthook |
|
566 | 566 | try: |
|
567 | 567 | self._orig_sys_modules_main_name = self.user_ns['__name__'] |
|
568 | 568 | except KeyError: |
|
569 | 569 | pass |
|
570 | 570 | |
|
571 | 571 | def restore_sys_module_state(self): |
|
572 | 572 | """Restore the state of the sys module.""" |
|
573 | 573 | try: |
|
574 | 574 | for k, v in self._orig_sys_module_state.items(): |
|
575 | 575 | setattr(sys, k, v) |
|
576 | 576 | except AttributeError: |
|
577 | 577 | pass |
|
578 | 578 | try: |
|
579 | 579 | delattr(sys, 'ipcompleter') |
|
580 | 580 | except AttributeError: |
|
581 | 581 | pass |
|
582 | 582 | # Reset what what done in self.init_sys_modules |
|
583 | 583 | try: |
|
584 | 584 | sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name |
|
585 | 585 | except (AttributeError, KeyError): |
|
586 | 586 | pass |
|
587 | 587 | |
|
588 | 588 | #------------------------------------------------------------------------- |
|
589 | 589 | # Things related to hooks |
|
590 | 590 | #------------------------------------------------------------------------- |
|
591 | 591 | |
|
592 | 592 | def init_hooks(self): |
|
593 | 593 | # hooks holds pointers used for user-side customizations |
|
594 | 594 | self.hooks = Struct() |
|
595 | 595 | |
|
596 | 596 | self.strdispatchers = {} |
|
597 | 597 | |
|
598 | 598 | # Set all default hooks, defined in the IPython.hooks module. |
|
599 | 599 | import IPython.core.hooks |
|
600 | 600 | hooks = IPython.core.hooks |
|
601 | 601 | for hook_name in hooks.__all__: |
|
602 | 602 | # default hooks have priority 100, i.e. low; user hooks should have |
|
603 | 603 | # 0-100 priority |
|
604 | 604 | self.set_hook(hook_name,getattr(hooks,hook_name), 100) |
|
605 | 605 | |
|
606 | 606 | def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None): |
|
607 | 607 | """set_hook(name,hook) -> sets an internal IPython hook. |
|
608 | 608 | |
|
609 | 609 | IPython exposes some of its internal API as user-modifiable hooks. By |
|
610 | 610 | adding your function to one of these hooks, you can modify IPython's |
|
611 | 611 | behavior to call at runtime your own routines.""" |
|
612 | 612 | |
|
613 | 613 | # At some point in the future, this should validate the hook before it |
|
614 | 614 | # accepts it. Probably at least check that the hook takes the number |
|
615 | 615 | # of args it's supposed to. |
|
616 | 616 | |
|
617 | 617 | f = new.instancemethod(hook,self,self.__class__) |
|
618 | 618 | |
|
619 | 619 | # check if the hook is for strdispatcher first |
|
620 | 620 | if str_key is not None: |
|
621 | 621 | sdp = self.strdispatchers.get(name, StrDispatch()) |
|
622 | 622 | sdp.add_s(str_key, f, priority ) |
|
623 | 623 | self.strdispatchers[name] = sdp |
|
624 | 624 | return |
|
625 | 625 | if re_key is not None: |
|
626 | 626 | sdp = self.strdispatchers.get(name, StrDispatch()) |
|
627 | 627 | sdp.add_re(re.compile(re_key), f, priority ) |
|
628 | 628 | self.strdispatchers[name] = sdp |
|
629 | 629 | return |
|
630 | 630 | |
|
631 | 631 | dp = getattr(self.hooks, name, None) |
|
632 | 632 | if name not in IPython.core.hooks.__all__: |
|
633 | 633 | print "Warning! Hook '%s' is not one of %s" % (name, IPython.core.hooks.__all__ ) |
|
634 | 634 | if not dp: |
|
635 | 635 | dp = IPython.core.hooks.CommandChainDispatcher() |
|
636 | 636 | |
|
637 | 637 | try: |
|
638 | 638 | dp.add(f,priority) |
|
639 | 639 | except AttributeError: |
|
640 | 640 | # it was not commandchain, plain old func - replace |
|
641 | 641 | dp = f |
|
642 | 642 | |
|
643 | 643 | setattr(self.hooks,name, dp) |
|
644 | 644 | |
|
645 | 645 | #------------------------------------------------------------------------- |
|
646 | 646 | # Things related to the "main" module |
|
647 | 647 | #------------------------------------------------------------------------- |
|
648 | 648 | |
|
649 | 649 | def new_main_mod(self,ns=None): |
|
650 | 650 | """Return a new 'main' module object for user code execution. |
|
651 | 651 | """ |
|
652 | 652 | main_mod = self._user_main_module |
|
653 | 653 | init_fakemod_dict(main_mod,ns) |
|
654 | 654 | return main_mod |
|
655 | 655 | |
|
656 | 656 | def cache_main_mod(self,ns,fname): |
|
657 | 657 | """Cache a main module's namespace. |
|
658 | 658 | |
|
659 | 659 | When scripts are executed via %run, we must keep a reference to the |
|
660 | 660 | namespace of their __main__ module (a FakeModule instance) around so |
|
661 | 661 | that Python doesn't clear it, rendering objects defined therein |
|
662 | 662 | useless. |
|
663 | 663 | |
|
664 | 664 | This method keeps said reference in a private dict, keyed by the |
|
665 | 665 | absolute path of the module object (which corresponds to the script |
|
666 | 666 | path). This way, for multiple executions of the same script we only |
|
667 | 667 | keep one copy of the namespace (the last one), thus preventing memory |
|
668 | 668 | leaks from old references while allowing the objects from the last |
|
669 | 669 | execution to be accessible. |
|
670 | 670 | |
|
671 | 671 | Note: we can not allow the actual FakeModule instances to be deleted, |
|
672 | 672 | because of how Python tears down modules (it hard-sets all their |
|
673 | 673 | references to None without regard for reference counts). This method |
|
674 | 674 | must therefore make a *copy* of the given namespace, to allow the |
|
675 | 675 | original module's __dict__ to be cleared and reused. |
|
676 | 676 | |
|
677 | 677 | |
|
678 | 678 | Parameters |
|
679 | 679 | ---------- |
|
680 | 680 | ns : a namespace (a dict, typically) |
|
681 | 681 | |
|
682 | 682 | fname : str |
|
683 | 683 | Filename associated with the namespace. |
|
684 | 684 | |
|
685 | 685 | Examples |
|
686 | 686 | -------- |
|
687 | 687 | |
|
688 | 688 | In [10]: import IPython |
|
689 | 689 | |
|
690 | 690 | In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__) |
|
691 | 691 | |
|
692 | 692 | In [12]: IPython.__file__ in _ip._main_ns_cache |
|
693 | 693 | Out[12]: True |
|
694 | 694 | """ |
|
695 | 695 | self._main_ns_cache[os.path.abspath(fname)] = ns.copy() |
|
696 | 696 | |
|
697 | 697 | def clear_main_mod_cache(self): |
|
698 | 698 | """Clear the cache of main modules. |
|
699 | 699 | |
|
700 | 700 | Mainly for use by utilities like %reset. |
|
701 | 701 | |
|
702 | 702 | Examples |
|
703 | 703 | -------- |
|
704 | 704 | |
|
705 | 705 | In [15]: import IPython |
|
706 | 706 | |
|
707 | 707 | In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__) |
|
708 | 708 | |
|
709 | 709 | In [17]: len(_ip._main_ns_cache) > 0 |
|
710 | 710 | Out[17]: True |
|
711 | 711 | |
|
712 | 712 | In [18]: _ip.clear_main_mod_cache() |
|
713 | 713 | |
|
714 | 714 | In [19]: len(_ip._main_ns_cache) == 0 |
|
715 | 715 | Out[19]: True |
|
716 | 716 | """ |
|
717 | 717 | self._main_ns_cache.clear() |
|
718 | 718 | |
|
719 | 719 | #------------------------------------------------------------------------- |
|
720 | 720 | # Things related to debugging |
|
721 | 721 | #------------------------------------------------------------------------- |
|
722 | 722 | |
|
723 | 723 | def init_pdb(self): |
|
724 | 724 | # Set calling of pdb on exceptions |
|
725 | 725 | # self.call_pdb is a property |
|
726 | 726 | self.call_pdb = self.pdb |
|
727 | 727 | |
|
728 | 728 | def _get_call_pdb(self): |
|
729 | 729 | return self._call_pdb |
|
730 | 730 | |
|
731 | 731 | def _set_call_pdb(self,val): |
|
732 | 732 | |
|
733 | 733 | if val not in (0,1,False,True): |
|
734 | 734 | raise ValueError,'new call_pdb value must be boolean' |
|
735 | 735 | |
|
736 | 736 | # store value in instance |
|
737 | 737 | self._call_pdb = val |
|
738 | 738 | |
|
739 | 739 | # notify the actual exception handlers |
|
740 | 740 | self.InteractiveTB.call_pdb = val |
|
741 | 741 | if self.isthreaded: |
|
742 | 742 | try: |
|
743 | 743 | self.sys_excepthook.call_pdb = val |
|
744 | 744 | except: |
|
745 | 745 | warn('Failed to activate pdb for threaded exception handler') |
|
746 | 746 | |
|
747 | 747 | call_pdb = property(_get_call_pdb,_set_call_pdb,None, |
|
748 | 748 | 'Control auto-activation of pdb at exceptions') |
|
749 | 749 | |
|
750 | 750 | def debugger(self,force=False): |
|
751 | 751 | """Call the pydb/pdb debugger. |
|
752 | 752 | |
|
753 | 753 | Keywords: |
|
754 | 754 | |
|
755 | 755 | - force(False): by default, this routine checks the instance call_pdb |
|
756 | 756 | flag and does not actually invoke the debugger if the flag is false. |
|
757 | 757 | The 'force' option forces the debugger to activate even if the flag |
|
758 | 758 | is false. |
|
759 | 759 | """ |
|
760 | 760 | |
|
761 | 761 | if not (force or self.call_pdb): |
|
762 | 762 | return |
|
763 | 763 | |
|
764 | 764 | if not hasattr(sys,'last_traceback'): |
|
765 | 765 | error('No traceback has been produced, nothing to debug.') |
|
766 | 766 | return |
|
767 | 767 | |
|
768 | 768 | # use pydb if available |
|
769 | 769 | if debugger.has_pydb: |
|
770 | 770 | from pydb import pm |
|
771 | 771 | else: |
|
772 | 772 | # fallback to our internal debugger |
|
773 | 773 | pm = lambda : self.InteractiveTB.debugger(force=True) |
|
774 | 774 | self.history_saving_wrapper(pm)() |
|
775 | 775 | |
|
776 | 776 | #------------------------------------------------------------------------- |
|
777 | 777 | # Things related to IPython's various namespaces |
|
778 | 778 | #------------------------------------------------------------------------- |
|
779 | 779 | |
|
780 | 780 | def init_create_namespaces(self, user_ns=None, user_global_ns=None): |
|
781 | 781 | # Create the namespace where the user will operate. user_ns is |
|
782 | 782 | # normally the only one used, and it is passed to the exec calls as |
|
783 | 783 | # the locals argument. But we do carry a user_global_ns namespace |
|
784 | 784 | # given as the exec 'globals' argument, This is useful in embedding |
|
785 | 785 | # situations where the ipython shell opens in a context where the |
|
786 | 786 | # distinction between locals and globals is meaningful. For |
|
787 | 787 | # non-embedded contexts, it is just the same object as the user_ns dict. |
|
788 | 788 | |
|
789 | 789 | # FIXME. For some strange reason, __builtins__ is showing up at user |
|
790 | 790 | # level as a dict instead of a module. This is a manual fix, but I |
|
791 | 791 | # should really track down where the problem is coming from. Alex |
|
792 | 792 | # Schmolck reported this problem first. |
|
793 | 793 | |
|
794 | 794 | # A useful post by Alex Martelli on this topic: |
|
795 | 795 | # Re: inconsistent value from __builtins__ |
|
796 | 796 | # Von: Alex Martelli <aleaxit@yahoo.com> |
|
797 | 797 | # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends |
|
798 | 798 | # Gruppen: comp.lang.python |
|
799 | 799 | |
|
800 | 800 | # Michael Hohn <hohn@hooknose.lbl.gov> wrote: |
|
801 | 801 | # > >>> print type(builtin_check.get_global_binding('__builtins__')) |
|
802 | 802 | # > <type 'dict'> |
|
803 | 803 | # > >>> print type(__builtins__) |
|
804 | 804 | # > <type 'module'> |
|
805 | 805 | # > Is this difference in return value intentional? |
|
806 | 806 | |
|
807 | 807 | # Well, it's documented that '__builtins__' can be either a dictionary |
|
808 | 808 | # or a module, and it's been that way for a long time. Whether it's |
|
809 | 809 | # intentional (or sensible), I don't know. In any case, the idea is |
|
810 | 810 | # that if you need to access the built-in namespace directly, you |
|
811 | 811 | # should start with "import __builtin__" (note, no 's') which will |
|
812 | 812 | # definitely give you a module. Yeah, it's somewhat confusing:-(. |
|
813 | 813 | |
|
814 | 814 | # These routines return properly built dicts as needed by the rest of |
|
815 | 815 | # the code, and can also be used by extension writers to generate |
|
816 | 816 | # properly initialized namespaces. |
|
817 | 817 | user_ns, user_global_ns = self.make_user_namespaces(user_ns, |
|
818 | 818 | user_global_ns) |
|
819 | 819 | |
|
820 | 820 | # Assign namespaces |
|
821 | 821 | # This is the namespace where all normal user variables live |
|
822 | 822 | self.user_ns = user_ns |
|
823 | 823 | self.user_global_ns = user_global_ns |
|
824 | 824 | |
|
825 | 825 | # An auxiliary namespace that checks what parts of the user_ns were |
|
826 | 826 | # loaded at startup, so we can list later only variables defined in |
|
827 | 827 | # actual interactive use. Since it is always a subset of user_ns, it |
|
828 | 828 | # doesn't need to be seaparately tracked in the ns_table |
|
829 | 829 | self.user_config_ns = {} |
|
830 | 830 | |
|
831 | 831 | # A namespace to keep track of internal data structures to prevent |
|
832 | 832 | # them from cluttering user-visible stuff. Will be updated later |
|
833 | 833 | self.internal_ns = {} |
|
834 | 834 | |
|
835 | 835 | # Now that FakeModule produces a real module, we've run into a nasty |
|
836 | 836 | # problem: after script execution (via %run), the module where the user |
|
837 | 837 | # code ran is deleted. Now that this object is a true module (needed |
|
838 | 838 | # so docetst and other tools work correctly), the Python module |
|
839 | 839 | # teardown mechanism runs over it, and sets to None every variable |
|
840 | 840 | # present in that module. Top-level references to objects from the |
|
841 | 841 | # script survive, because the user_ns is updated with them. However, |
|
842 | 842 | # calling functions defined in the script that use other things from |
|
843 | 843 | # the script will fail, because the function's closure had references |
|
844 | 844 | # to the original objects, which are now all None. So we must protect |
|
845 | 845 | # these modules from deletion by keeping a cache. |
|
846 | 846 | # |
|
847 | 847 | # To avoid keeping stale modules around (we only need the one from the |
|
848 | 848 | # last run), we use a dict keyed with the full path to the script, so |
|
849 | 849 | # only the last version of the module is held in the cache. Note, |
|
850 | 850 | # however, that we must cache the module *namespace contents* (their |
|
851 | 851 | # __dict__). Because if we try to cache the actual modules, old ones |
|
852 | 852 | # (uncached) could be destroyed while still holding references (such as |
|
853 | 853 | # those held by GUI objects that tend to be long-lived)> |
|
854 | 854 | # |
|
855 | 855 | # The %reset command will flush this cache. See the cache_main_mod() |
|
856 | 856 | # and clear_main_mod_cache() methods for details on use. |
|
857 | 857 | |
|
858 | 858 | # This is the cache used for 'main' namespaces |
|
859 | 859 | self._main_ns_cache = {} |
|
860 | 860 | # And this is the single instance of FakeModule whose __dict__ we keep |
|
861 | 861 | # copying and clearing for reuse on each %run |
|
862 | 862 | self._user_main_module = FakeModule() |
|
863 | 863 | |
|
864 | 864 | # A table holding all the namespaces IPython deals with, so that |
|
865 | 865 | # introspection facilities can search easily. |
|
866 | 866 | self.ns_table = {'user':user_ns, |
|
867 | 867 | 'user_global':user_global_ns, |
|
868 | 868 | 'internal':self.internal_ns, |
|
869 | 869 | 'builtin':__builtin__.__dict__ |
|
870 | 870 | } |
|
871 | 871 | |
|
872 | 872 | # Similarly, track all namespaces where references can be held and that |
|
873 | 873 | # we can safely clear (so it can NOT include builtin). This one can be |
|
874 | 874 | # a simple list. |
|
875 | 875 | self.ns_refs_table = [ user_ns, user_global_ns, self.user_config_ns, |
|
876 | 876 | self.internal_ns, self._main_ns_cache ] |
|
877 | 877 | |
|
878 | 878 | def init_sys_modules(self): |
|
879 | 879 | # We need to insert into sys.modules something that looks like a |
|
880 | 880 | # module but which accesses the IPython namespace, for shelve and |
|
881 | 881 | # pickle to work interactively. Normally they rely on getting |
|
882 | 882 | # everything out of __main__, but for embedding purposes each IPython |
|
883 | 883 | # instance has its own private namespace, so we can't go shoving |
|
884 | 884 | # everything into __main__. |
|
885 | 885 | |
|
886 | 886 | # note, however, that we should only do this for non-embedded |
|
887 | 887 | # ipythons, which really mimic the __main__.__dict__ with their own |
|
888 | 888 | # namespace. Embedded instances, on the other hand, should not do |
|
889 | 889 | # this because they need to manage the user local/global namespaces |
|
890 | 890 | # only, but they live within a 'normal' __main__ (meaning, they |
|
891 | 891 | # shouldn't overtake the execution environment of the script they're |
|
892 | 892 | # embedded in). |
|
893 | 893 | |
|
894 | 894 | # This is overridden in the InteractiveShellEmbed subclass to a no-op. |
|
895 | 895 | |
|
896 | 896 | try: |
|
897 | 897 | main_name = self.user_ns['__name__'] |
|
898 | 898 | except KeyError: |
|
899 | 899 | raise KeyError('user_ns dictionary MUST have a "__name__" key') |
|
900 | 900 | else: |
|
901 | 901 | sys.modules[main_name] = FakeModule(self.user_ns) |
|
902 | 902 | |
|
903 | 903 | def make_user_namespaces(self, user_ns=None, user_global_ns=None): |
|
904 | 904 | """Return a valid local and global user interactive namespaces. |
|
905 | 905 | |
|
906 | 906 | This builds a dict with the minimal information needed to operate as a |
|
907 | 907 | valid IPython user namespace, which you can pass to the various |
|
908 | 908 | embedding classes in ipython. The default implementation returns the |
|
909 | 909 | same dict for both the locals and the globals to allow functions to |
|
910 | 910 | refer to variables in the namespace. Customized implementations can |
|
911 | 911 | return different dicts. The locals dictionary can actually be anything |
|
912 | 912 | following the basic mapping protocol of a dict, but the globals dict |
|
913 | 913 | must be a true dict, not even a subclass. It is recommended that any |
|
914 | 914 | custom object for the locals namespace synchronize with the globals |
|
915 | 915 | dict somehow. |
|
916 | 916 | |
|
917 | 917 | Raises TypeError if the provided globals namespace is not a true dict. |
|
918 | 918 | |
|
919 | 919 | :Parameters: |
|
920 | 920 | user_ns : dict-like, optional |
|
921 | 921 | The current user namespace. The items in this namespace should |
|
922 | 922 | be included in the output. If None, an appropriate blank |
|
923 | 923 | namespace should be created. |
|
924 | 924 | user_global_ns : dict, optional |
|
925 | 925 | The current user global namespace. The items in this namespace |
|
926 | 926 | should be included in the output. If None, an appropriate |
|
927 | 927 | blank namespace should be created. |
|
928 | 928 | |
|
929 | 929 | :Returns: |
|
930 | 930 | A tuple pair of dictionary-like object to be used as the local namespace |
|
931 | 931 | of the interpreter and a dict to be used as the global namespace. |
|
932 | 932 | """ |
|
933 | 933 | |
|
934 | 934 | if user_ns is None: |
|
935 | 935 | # Set __name__ to __main__ to better match the behavior of the |
|
936 | 936 | # normal interpreter. |
|
937 | 937 | user_ns = {'__name__' :'__main__', |
|
938 | 938 | '__builtins__' : __builtin__, |
|
939 | 939 | } |
|
940 | 940 | else: |
|
941 | 941 | user_ns.setdefault('__name__','__main__') |
|
942 | 942 | user_ns.setdefault('__builtins__',__builtin__) |
|
943 | 943 | |
|
944 | 944 | if user_global_ns is None: |
|
945 | 945 | user_global_ns = user_ns |
|
946 | 946 | if type(user_global_ns) is not dict: |
|
947 | 947 | raise TypeError("user_global_ns must be a true dict; got %r" |
|
948 | 948 | % type(user_global_ns)) |
|
949 | 949 | |
|
950 | 950 | return user_ns, user_global_ns |
|
951 | 951 | |
|
952 | 952 | def init_user_ns(self): |
|
953 | 953 | """Initialize all user-visible namespaces to their minimum defaults. |
|
954 | 954 | |
|
955 | 955 | Certain history lists are also initialized here, as they effectively |
|
956 | 956 | act as user namespaces. |
|
957 | 957 | |
|
958 | 958 | Notes |
|
959 | 959 | ----- |
|
960 | 960 | All data structures here are only filled in, they are NOT reset by this |
|
961 | 961 | method. If they were not empty before, data will simply be added to |
|
962 | 962 | therm. |
|
963 | 963 | """ |
|
964 | 964 | # Store myself as the public api!!! |
|
965 | 965 | self.user_ns['get_ipython'] = self.get_ipython |
|
966 | 966 | |
|
967 | 967 | # make global variables for user access to the histories |
|
968 | 968 | self.user_ns['_ih'] = self.input_hist |
|
969 | 969 | self.user_ns['_oh'] = self.output_hist |
|
970 | 970 | self.user_ns['_dh'] = self.dir_hist |
|
971 | 971 | |
|
972 | 972 | # user aliases to input and output histories |
|
973 | 973 | self.user_ns['In'] = self.input_hist |
|
974 | 974 | self.user_ns['Out'] = self.output_hist |
|
975 | 975 | |
|
976 | 976 | self.user_ns['_sh'] = shadowns |
|
977 | 977 | |
|
978 | 978 | # Put 'help' in the user namespace |
|
979 | 979 | try: |
|
980 | 980 | from site import _Helper |
|
981 | 981 | self.user_ns['help'] = _Helper() |
|
982 | 982 | except ImportError: |
|
983 | 983 | warn('help() not available - check site.py') |
|
984 | 984 | |
|
985 | 985 | def reset(self): |
|
986 | 986 | """Clear all internal namespaces. |
|
987 | 987 | |
|
988 | 988 | Note that this is much more aggressive than %reset, since it clears |
|
989 | 989 | fully all namespaces, as well as all input/output lists. |
|
990 | 990 | """ |
|
991 | 991 | for ns in self.ns_refs_table: |
|
992 | 992 | ns.clear() |
|
993 | 993 | |
|
994 | 994 | self.alias_manager.clear_aliases() |
|
995 | 995 | |
|
996 | 996 | # Clear input and output histories |
|
997 | 997 | self.input_hist[:] = [] |
|
998 | 998 | self.input_hist_raw[:] = [] |
|
999 | 999 | self.output_hist.clear() |
|
1000 | 1000 | |
|
1001 | 1001 | # Restore the user namespaces to minimal usability |
|
1002 | 1002 | self.init_user_ns() |
|
1003 | 1003 | |
|
1004 | 1004 | # Restore the default and user aliases |
|
1005 | 1005 | self.alias_manager.init_aliases() |
|
1006 | 1006 | |
|
1007 | 1007 | def push(self, variables, interactive=True): |
|
1008 | 1008 | """Inject a group of variables into the IPython user namespace. |
|
1009 | 1009 | |
|
1010 | 1010 | Parameters |
|
1011 | 1011 | ---------- |
|
1012 | 1012 | variables : dict, str or list/tuple of str |
|
1013 | 1013 | The variables to inject into the user's namespace. If a dict, |
|
1014 | 1014 | a simple update is done. If a str, the string is assumed to |
|
1015 | 1015 | have variable names separated by spaces. A list/tuple of str |
|
1016 | 1016 | can also be used to give the variable names. If just the variable |
|
1017 | 1017 | names are give (list/tuple/str) then the variable values looked |
|
1018 | 1018 | up in the callers frame. |
|
1019 | 1019 | interactive : bool |
|
1020 | 1020 | If True (default), the variables will be listed with the ``who`` |
|
1021 | 1021 | magic. |
|
1022 | 1022 | """ |
|
1023 | 1023 | vdict = None |
|
1024 | 1024 | |
|
1025 | 1025 | # We need a dict of name/value pairs to do namespace updates. |
|
1026 | 1026 | if isinstance(variables, dict): |
|
1027 | 1027 | vdict = variables |
|
1028 | 1028 | elif isinstance(variables, (basestring, list, tuple)): |
|
1029 | 1029 | if isinstance(variables, basestring): |
|
1030 | 1030 | vlist = variables.split() |
|
1031 | 1031 | else: |
|
1032 | 1032 | vlist = variables |
|
1033 | 1033 | vdict = {} |
|
1034 | 1034 | cf = sys._getframe(1) |
|
1035 | 1035 | for name in vlist: |
|
1036 | 1036 | try: |
|
1037 | 1037 | vdict[name] = eval(name, cf.f_globals, cf.f_locals) |
|
1038 | 1038 | except: |
|
1039 | 1039 | print ('Could not get variable %s from %s' % |
|
1040 | 1040 | (name,cf.f_code.co_name)) |
|
1041 | 1041 | else: |
|
1042 | 1042 | raise ValueError('variables must be a dict/str/list/tuple') |
|
1043 | 1043 | |
|
1044 | 1044 | # Propagate variables to user namespace |
|
1045 | 1045 | self.user_ns.update(vdict) |
|
1046 | 1046 | |
|
1047 | 1047 | # And configure interactive visibility |
|
1048 | 1048 | config_ns = self.user_config_ns |
|
1049 | 1049 | if interactive: |
|
1050 | 1050 | for name, val in vdict.iteritems(): |
|
1051 | 1051 | config_ns.pop(name, None) |
|
1052 | 1052 | else: |
|
1053 | 1053 | for name,val in vdict.iteritems(): |
|
1054 | 1054 | config_ns[name] = val |
|
1055 | 1055 | |
|
1056 | 1056 | #------------------------------------------------------------------------- |
|
1057 | 1057 | # Things related to history management |
|
1058 | 1058 | #------------------------------------------------------------------------- |
|
1059 | 1059 | |
|
1060 | 1060 | def init_history(self): |
|
1061 | 1061 | # List of input with multi-line handling. |
|
1062 | 1062 | self.input_hist = InputList() |
|
1063 | 1063 | # This one will hold the 'raw' input history, without any |
|
1064 | 1064 | # pre-processing. This will allow users to retrieve the input just as |
|
1065 | 1065 | # it was exactly typed in by the user, with %hist -r. |
|
1066 | 1066 | self.input_hist_raw = InputList() |
|
1067 | 1067 | |
|
1068 | 1068 | # list of visited directories |
|
1069 | 1069 | try: |
|
1070 | 1070 | self.dir_hist = [os.getcwd()] |
|
1071 | 1071 | except OSError: |
|
1072 | 1072 | self.dir_hist = [] |
|
1073 | 1073 | |
|
1074 | 1074 | # dict of output history |
|
1075 | 1075 | self.output_hist = {} |
|
1076 | 1076 | |
|
1077 | 1077 | # Now the history file |
|
1078 | 1078 | if self.profile: |
|
1079 | 1079 | histfname = 'history-%s' % self.profile |
|
1080 | 1080 | else: |
|
1081 | 1081 | histfname = 'history' |
|
1082 | 1082 | self.histfile = os.path.join(self.ipython_dir, histfname) |
|
1083 | 1083 | |
|
1084 | 1084 | # Fill the history zero entry, user counter starts at 1 |
|
1085 | 1085 | self.input_hist.append('\n') |
|
1086 | 1086 | self.input_hist_raw.append('\n') |
|
1087 | 1087 | |
|
1088 | 1088 | def init_shadow_hist(self): |
|
1089 | 1089 | try: |
|
1090 | 1090 | self.db = pickleshare.PickleShareDB(self.ipython_dir + "/db") |
|
1091 | 1091 | except exceptions.UnicodeDecodeError: |
|
1092 | 1092 | print "Your ipython_dir can't be decoded to unicode!" |
|
1093 | 1093 | print "Please set HOME environment variable to something that" |
|
1094 | 1094 | print r"only has ASCII characters, e.g. c:\home" |
|
1095 | 1095 | print "Now it is", self.ipython_dir |
|
1096 | 1096 | sys.exit() |
|
1097 | 1097 | self.shadowhist = ipcorehist.ShadowHist(self.db) |
|
1098 | 1098 | |
|
1099 | 1099 | def savehist(self): |
|
1100 | 1100 | """Save input history to a file (via readline library).""" |
|
1101 | 1101 | |
|
1102 | 1102 | if not self.has_readline: |
|
1103 | 1103 | return |
|
1104 | 1104 | |
|
1105 | 1105 | try: |
|
1106 | 1106 | self.readline.write_history_file(self.histfile) |
|
1107 | 1107 | except: |
|
1108 | 1108 | print 'Unable to save IPython command history to file: ' + \ |
|
1109 | 1109 | `self.histfile` |
|
1110 | 1110 | |
|
1111 | 1111 | def reloadhist(self): |
|
1112 | 1112 | """Reload the input history from disk file.""" |
|
1113 | 1113 | |
|
1114 | 1114 | if self.has_readline: |
|
1115 | 1115 | try: |
|
1116 | 1116 | self.readline.clear_history() |
|
1117 | 1117 | self.readline.read_history_file(self.shell.histfile) |
|
1118 | 1118 | except AttributeError: |
|
1119 | 1119 | pass |
|
1120 | 1120 | |
|
1121 | 1121 | def history_saving_wrapper(self, func): |
|
1122 | 1122 | """ Wrap func for readline history saving |
|
1123 | 1123 | |
|
1124 | 1124 | Convert func into callable that saves & restores |
|
1125 | 1125 | history around the call """ |
|
1126 | 1126 | |
|
1127 | 1127 | if not self.has_readline: |
|
1128 | 1128 | return func |
|
1129 | 1129 | |
|
1130 | 1130 | def wrapper(): |
|
1131 | 1131 | self.savehist() |
|
1132 | 1132 | try: |
|
1133 | 1133 | func() |
|
1134 | 1134 | finally: |
|
1135 | 1135 | readline.read_history_file(self.histfile) |
|
1136 | 1136 | return wrapper |
|
1137 | 1137 | |
|
1138 | 1138 | #------------------------------------------------------------------------- |
|
1139 | 1139 | # Things related to exception handling and tracebacks (not debugging) |
|
1140 | 1140 | #------------------------------------------------------------------------- |
|
1141 | 1141 | |
|
1142 | 1142 | def init_traceback_handlers(self, custom_exceptions): |
|
1143 | 1143 | # Syntax error handler. |
|
1144 | 1144 | self.SyntaxTB = SyntaxTB(color_scheme='NoColor') |
|
1145 | 1145 | |
|
1146 | 1146 | # The interactive one is initialized with an offset, meaning we always |
|
1147 | 1147 | # want to remove the topmost item in the traceback, which is our own |
|
1148 | 1148 | # internal code. Valid modes: ['Plain','Context','Verbose'] |
|
1149 | 1149 | self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain', |
|
1150 | 1150 | color_scheme='NoColor', |
|
1151 | 1151 | tb_offset = 1) |
|
1152 | 1152 | |
|
1153 | 1153 | # IPython itself shouldn't crash. This will produce a detailed |
|
1154 | 1154 | # post-mortem if it does. But we only install the crash handler for |
|
1155 | 1155 | # non-threaded shells, the threaded ones use a normal verbose reporter |
|
1156 | 1156 | # and lose the crash handler. This is because exceptions in the main |
|
1157 | 1157 | # thread (such as in GUI code) propagate directly to sys.excepthook, |
|
1158 | 1158 | # and there's no point in printing crash dumps for every user exception. |
|
1159 | 1159 | if self.isthreaded: |
|
1160 | 1160 | ipCrashHandler = ultratb.FormattedTB() |
|
1161 | 1161 | else: |
|
1162 | 1162 | from IPython.core import crashhandler |
|
1163 | 1163 | ipCrashHandler = crashhandler.IPythonCrashHandler(self) |
|
1164 | 1164 | self.set_crash_handler(ipCrashHandler) |
|
1165 | 1165 | |
|
1166 | 1166 | # and add any custom exception handlers the user may have specified |
|
1167 | 1167 | self.set_custom_exc(*custom_exceptions) |
|
1168 | 1168 | |
|
1169 | 1169 | def set_crash_handler(self, crashHandler): |
|
1170 | 1170 | """Set the IPython crash handler. |
|
1171 | 1171 | |
|
1172 | 1172 | This must be a callable with a signature suitable for use as |
|
1173 | 1173 | sys.excepthook.""" |
|
1174 | 1174 | |
|
1175 | 1175 | # Install the given crash handler as the Python exception hook |
|
1176 | 1176 | sys.excepthook = crashHandler |
|
1177 | 1177 | |
|
1178 | 1178 | # The instance will store a pointer to this, so that runtime code |
|
1179 | 1179 | # (such as magics) can access it. This is because during the |
|
1180 | 1180 | # read-eval loop, it gets temporarily overwritten (to deal with GUI |
|
1181 | 1181 | # frameworks). |
|
1182 | 1182 | self.sys_excepthook = sys.excepthook |
|
1183 | 1183 | |
|
1184 | 1184 | def set_custom_exc(self,exc_tuple,handler): |
|
1185 | 1185 | """set_custom_exc(exc_tuple,handler) |
|
1186 | 1186 | |
|
1187 | 1187 | Set a custom exception handler, which will be called if any of the |
|
1188 | 1188 | exceptions in exc_tuple occur in the mainloop (specifically, in the |
|
1189 | 1189 | runcode() method. |
|
1190 | 1190 | |
|
1191 | 1191 | Inputs: |
|
1192 | 1192 | |
|
1193 | 1193 | - exc_tuple: a *tuple* of valid exceptions to call the defined |
|
1194 | 1194 | handler for. It is very important that you use a tuple, and NOT A |
|
1195 | 1195 | LIST here, because of the way Python's except statement works. If |
|
1196 | 1196 | you only want to trap a single exception, use a singleton tuple: |
|
1197 | 1197 | |
|
1198 | 1198 | exc_tuple == (MyCustomException,) |
|
1199 | 1199 | |
|
1200 | 1200 | - handler: this must be defined as a function with the following |
|
1201 | 1201 | basic interface: def my_handler(self,etype,value,tb). |
|
1202 | 1202 | |
|
1203 | 1203 | This will be made into an instance method (via new.instancemethod) |
|
1204 | 1204 | of IPython itself, and it will be called if any of the exceptions |
|
1205 | 1205 | listed in the exc_tuple are caught. If the handler is None, an |
|
1206 | 1206 | internal basic one is used, which just prints basic info. |
|
1207 | 1207 | |
|
1208 | 1208 | WARNING: by putting in your own exception handler into IPython's main |
|
1209 | 1209 | execution loop, you run a very good chance of nasty crashes. This |
|
1210 | 1210 | facility should only be used if you really know what you are doing.""" |
|
1211 | 1211 | |
|
1212 | 1212 | assert type(exc_tuple)==type(()) , \ |
|
1213 | 1213 | "The custom exceptions must be given AS A TUPLE." |
|
1214 | 1214 | |
|
1215 | 1215 | def dummy_handler(self,etype,value,tb): |
|
1216 | 1216 | print '*** Simple custom exception handler ***' |
|
1217 | 1217 | print 'Exception type :',etype |
|
1218 | 1218 | print 'Exception value:',value |
|
1219 | 1219 | print 'Traceback :',tb |
|
1220 | 1220 | print 'Source code :','\n'.join(self.buffer) |
|
1221 | 1221 | |
|
1222 | 1222 | if handler is None: handler = dummy_handler |
|
1223 | 1223 | |
|
1224 | 1224 | self.CustomTB = new.instancemethod(handler,self,self.__class__) |
|
1225 | 1225 | self.custom_exceptions = exc_tuple |
|
1226 | 1226 | |
|
1227 | 1227 | def excepthook(self, etype, value, tb): |
|
1228 | 1228 | """One more defense for GUI apps that call sys.excepthook. |
|
1229 | 1229 | |
|
1230 | 1230 | GUI frameworks like wxPython trap exceptions and call |
|
1231 | 1231 | sys.excepthook themselves. I guess this is a feature that |
|
1232 | 1232 | enables them to keep running after exceptions that would |
|
1233 | 1233 | otherwise kill their mainloop. This is a bother for IPython |
|
1234 | 1234 | which excepts to catch all of the program exceptions with a try: |
|
1235 | 1235 | except: statement. |
|
1236 | 1236 | |
|
1237 | 1237 | Normally, IPython sets sys.excepthook to a CrashHandler instance, so if |
|
1238 | 1238 | any app directly invokes sys.excepthook, it will look to the user like |
|
1239 | 1239 | IPython crashed. In order to work around this, we can disable the |
|
1240 | 1240 | CrashHandler and replace it with this excepthook instead, which prints a |
|
1241 | 1241 | regular traceback using our InteractiveTB. In this fashion, apps which |
|
1242 | 1242 | call sys.excepthook will generate a regular-looking exception from |
|
1243 | 1243 | IPython, and the CrashHandler will only be triggered by real IPython |
|
1244 | 1244 | crashes. |
|
1245 | 1245 | |
|
1246 | 1246 | This hook should be used sparingly, only in places which are not likely |
|
1247 | 1247 | to be true IPython errors. |
|
1248 | 1248 | """ |
|
1249 | 1249 | self.showtraceback((etype,value,tb),tb_offset=0) |
|
1250 | 1250 | |
|
1251 | 1251 | def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None): |
|
1252 | 1252 | """Display the exception that just occurred. |
|
1253 | 1253 | |
|
1254 | 1254 | If nothing is known about the exception, this is the method which |
|
1255 | 1255 | should be used throughout the code for presenting user tracebacks, |
|
1256 | 1256 | rather than directly invoking the InteractiveTB object. |
|
1257 | 1257 | |
|
1258 | 1258 | A specific showsyntaxerror() also exists, but this method can take |
|
1259 | 1259 | care of calling it if needed, so unless you are explicitly catching a |
|
1260 | 1260 | SyntaxError exception, don't try to analyze the stack manually and |
|
1261 | 1261 | simply call this method.""" |
|
1262 | 1262 | |
|
1263 | 1263 | |
|
1264 | 1264 | # Though this won't be called by syntax errors in the input line, |
|
1265 | 1265 | # there may be SyntaxError cases whith imported code. |
|
1266 | 1266 | |
|
1267 | 1267 | try: |
|
1268 | 1268 | if exc_tuple is None: |
|
1269 | 1269 | etype, value, tb = sys.exc_info() |
|
1270 | 1270 | else: |
|
1271 | 1271 | etype, value, tb = exc_tuple |
|
1272 | 1272 | |
|
1273 | 1273 | if etype is SyntaxError: |
|
1274 | 1274 | self.showsyntaxerror(filename) |
|
1275 | 1275 | elif etype is UsageError: |
|
1276 | 1276 | print "UsageError:", value |
|
1277 | 1277 | else: |
|
1278 | 1278 | # WARNING: these variables are somewhat deprecated and not |
|
1279 | 1279 | # necessarily safe to use in a threaded environment, but tools |
|
1280 | 1280 | # like pdb depend on their existence, so let's set them. If we |
|
1281 | 1281 | # find problems in the field, we'll need to revisit their use. |
|
1282 | 1282 | sys.last_type = etype |
|
1283 | 1283 | sys.last_value = value |
|
1284 | 1284 | sys.last_traceback = tb |
|
1285 | 1285 | |
|
1286 | 1286 | if etype in self.custom_exceptions: |
|
1287 | 1287 | self.CustomTB(etype,value,tb) |
|
1288 | 1288 | else: |
|
1289 | 1289 | self.InteractiveTB(etype,value,tb,tb_offset=tb_offset) |
|
1290 | 1290 | if self.InteractiveTB.call_pdb and self.has_readline: |
|
1291 | 1291 | # pdb mucks up readline, fix it back |
|
1292 | 1292 | self.set_completer() |
|
1293 | 1293 | except KeyboardInterrupt: |
|
1294 | 1294 | self.write("\nKeyboardInterrupt\n") |
|
1295 | 1295 | |
|
1296 | 1296 | def showsyntaxerror(self, filename=None): |
|
1297 | 1297 | """Display the syntax error that just occurred. |
|
1298 | 1298 | |
|
1299 | 1299 | This doesn't display a stack trace because there isn't one. |
|
1300 | 1300 | |
|
1301 | 1301 | If a filename is given, it is stuffed in the exception instead |
|
1302 | 1302 | of what was there before (because Python's parser always uses |
|
1303 | 1303 | "<string>" when reading from a string). |
|
1304 | 1304 | """ |
|
1305 | 1305 | etype, value, last_traceback = sys.exc_info() |
|
1306 | 1306 | |
|
1307 | 1307 | # See note about these variables in showtraceback() below |
|
1308 | 1308 | sys.last_type = etype |
|
1309 | 1309 | sys.last_value = value |
|
1310 | 1310 | sys.last_traceback = last_traceback |
|
1311 | 1311 | |
|
1312 | 1312 | if filename and etype is SyntaxError: |
|
1313 | 1313 | # Work hard to stuff the correct filename in the exception |
|
1314 | 1314 | try: |
|
1315 | 1315 | msg, (dummy_filename, lineno, offset, line) = value |
|
1316 | 1316 | except: |
|
1317 | 1317 | # Not the format we expect; leave it alone |
|
1318 | 1318 | pass |
|
1319 | 1319 | else: |
|
1320 | 1320 | # Stuff in the right filename |
|
1321 | 1321 | try: |
|
1322 | 1322 | # Assume SyntaxError is a class exception |
|
1323 | 1323 | value = SyntaxError(msg, (filename, lineno, offset, line)) |
|
1324 | 1324 | except: |
|
1325 | 1325 | # If that failed, assume SyntaxError is a string |
|
1326 | 1326 | value = msg, (filename, lineno, offset, line) |
|
1327 | 1327 | self.SyntaxTB(etype,value,[]) |
|
1328 | 1328 | |
|
1329 | 1329 | def edit_syntax_error(self): |
|
1330 | 1330 | """The bottom half of the syntax error handler called in the main loop. |
|
1331 | 1331 | |
|
1332 | 1332 | Loop until syntax error is fixed or user cancels. |
|
1333 | 1333 | """ |
|
1334 | 1334 | |
|
1335 | 1335 | while self.SyntaxTB.last_syntax_error: |
|
1336 | 1336 | # copy and clear last_syntax_error |
|
1337 | 1337 | err = self.SyntaxTB.clear_err_state() |
|
1338 | 1338 | if not self._should_recompile(err): |
|
1339 | 1339 | return |
|
1340 | 1340 | try: |
|
1341 | 1341 | # may set last_syntax_error again if a SyntaxError is raised |
|
1342 | 1342 | self.safe_execfile(err.filename,self.user_ns) |
|
1343 | 1343 | except: |
|
1344 | 1344 | self.showtraceback() |
|
1345 | 1345 | else: |
|
1346 | 1346 | try: |
|
1347 | 1347 | f = file(err.filename) |
|
1348 | 1348 | try: |
|
1349 | 1349 | # This should be inside a display_trap block and I |
|
1350 | 1350 | # think it is. |
|
1351 | 1351 | sys.displayhook(f.read()) |
|
1352 | 1352 | finally: |
|
1353 | 1353 | f.close() |
|
1354 | 1354 | except: |
|
1355 | 1355 | self.showtraceback() |
|
1356 | 1356 | |
|
1357 | 1357 | def _should_recompile(self,e): |
|
1358 | 1358 | """Utility routine for edit_syntax_error""" |
|
1359 | 1359 | |
|
1360 | 1360 | if e.filename in ('<ipython console>','<input>','<string>', |
|
1361 | 1361 | '<console>','<BackgroundJob compilation>', |
|
1362 | 1362 | None): |
|
1363 | 1363 | |
|
1364 | 1364 | return False |
|
1365 | 1365 | try: |
|
1366 | 1366 | if (self.autoedit_syntax and |
|
1367 | 1367 | not self.ask_yes_no('Return to editor to correct syntax error? ' |
|
1368 | 1368 | '[Y/n] ','y')): |
|
1369 | 1369 | return False |
|
1370 | 1370 | except EOFError: |
|
1371 | 1371 | return False |
|
1372 | 1372 | |
|
1373 | 1373 | def int0(x): |
|
1374 | 1374 | try: |
|
1375 | 1375 | return int(x) |
|
1376 | 1376 | except TypeError: |
|
1377 | 1377 | return 0 |
|
1378 | 1378 | # always pass integer line and offset values to editor hook |
|
1379 | 1379 | try: |
|
1380 | 1380 | self.hooks.fix_error_editor(e.filename, |
|
1381 | 1381 | int0(e.lineno),int0(e.offset),e.msg) |
|
1382 | 1382 | except TryNext: |
|
1383 | 1383 | warn('Could not open editor') |
|
1384 | 1384 | return False |
|
1385 | 1385 | return True |
|
1386 | 1386 | |
|
1387 | 1387 | #------------------------------------------------------------------------- |
|
1388 | 1388 | # Things related to tab completion |
|
1389 | 1389 | #------------------------------------------------------------------------- |
|
1390 | 1390 | |
|
1391 | 1391 | def complete(self, text): |
|
1392 | 1392 | """Return a sorted list of all possible completions on text. |
|
1393 | 1393 | |
|
1394 | 1394 | Inputs: |
|
1395 | 1395 | |
|
1396 | 1396 | - text: a string of text to be completed on. |
|
1397 | 1397 | |
|
1398 | 1398 | This is a wrapper around the completion mechanism, similar to what |
|
1399 | 1399 | readline does at the command line when the TAB key is hit. By |
|
1400 | 1400 | exposing it as a method, it can be used by other non-readline |
|
1401 | 1401 | environments (such as GUIs) for text completion. |
|
1402 | 1402 | |
|
1403 | 1403 | Simple usage example: |
|
1404 | 1404 | |
|
1405 | 1405 | In [7]: x = 'hello' |
|
1406 | 1406 | |
|
1407 | 1407 | In [8]: x |
|
1408 | 1408 | Out[8]: 'hello' |
|
1409 | 1409 | |
|
1410 | 1410 | In [9]: print x |
|
1411 | 1411 | hello |
|
1412 | 1412 | |
|
1413 | 1413 | In [10]: _ip.complete('x.l') |
|
1414 | 1414 | Out[10]: ['x.ljust', 'x.lower', 'x.lstrip'] |
|
1415 | 1415 | """ |
|
1416 | 1416 | |
|
1417 | 1417 | # Inject names into __builtin__ so we can complete on the added names. |
|
1418 | 1418 | with self.builtin_trap: |
|
1419 | 1419 | complete = self.Completer.complete |
|
1420 | 1420 | state = 0 |
|
1421 | 1421 | # use a dict so we get unique keys, since ipyhton's multiple |
|
1422 | 1422 | # completers can return duplicates. When we make 2.4 a requirement, |
|
1423 | 1423 | # start using sets instead, which are faster. |
|
1424 | 1424 | comps = {} |
|
1425 | 1425 | while True: |
|
1426 | 1426 | newcomp = complete(text,state,line_buffer=text) |
|
1427 | 1427 | if newcomp is None: |
|
1428 | 1428 | break |
|
1429 | 1429 | comps[newcomp] = 1 |
|
1430 | 1430 | state += 1 |
|
1431 | 1431 | outcomps = comps.keys() |
|
1432 | 1432 | outcomps.sort() |
|
1433 | 1433 | #print "T:",text,"OC:",outcomps # dbg |
|
1434 | 1434 | #print "vars:",self.user_ns.keys() |
|
1435 | 1435 | return outcomps |
|
1436 | 1436 | |
|
1437 | 1437 | def set_custom_completer(self,completer,pos=0): |
|
1438 | 1438 | """Adds a new custom completer function. |
|
1439 | 1439 | |
|
1440 | 1440 | The position argument (defaults to 0) is the index in the completers |
|
1441 | 1441 | list where you want the completer to be inserted.""" |
|
1442 | 1442 | |
|
1443 | 1443 | newcomp = new.instancemethod(completer,self.Completer, |
|
1444 | 1444 | self.Completer.__class__) |
|
1445 | 1445 | self.Completer.matchers.insert(pos,newcomp) |
|
1446 | 1446 | |
|
1447 | 1447 | def set_completer(self): |
|
1448 | 1448 | """Reset readline's completer to be our own.""" |
|
1449 | 1449 | self.readline.set_completer(self.Completer.complete) |
|
1450 | 1450 | |
|
1451 | 1451 | def set_completer_frame(self, frame=None): |
|
1452 | 1452 | """Set the frame of the completer.""" |
|
1453 | 1453 | if frame: |
|
1454 | 1454 | self.Completer.namespace = frame.f_locals |
|
1455 | 1455 | self.Completer.global_namespace = frame.f_globals |
|
1456 | 1456 | else: |
|
1457 | 1457 | self.Completer.namespace = self.user_ns |
|
1458 | 1458 | self.Completer.global_namespace = self.user_global_ns |
|
1459 | 1459 | |
|
1460 | 1460 | #------------------------------------------------------------------------- |
|
1461 | 1461 | # Things related to readline |
|
1462 | 1462 | #------------------------------------------------------------------------- |
|
1463 | 1463 | |
|
1464 | 1464 | def init_readline(self): |
|
1465 | 1465 | """Command history completion/saving/reloading.""" |
|
1466 | 1466 | |
|
1467 | 1467 | self.rl_next_input = None |
|
1468 | 1468 | self.rl_do_indent = False |
|
1469 | 1469 | |
|
1470 | 1470 | if not self.readline_use: |
|
1471 | 1471 | return |
|
1472 | 1472 | |
|
1473 | 1473 | import IPython.utils.rlineimpl as readline |
|
1474 | 1474 | |
|
1475 | 1475 | if not readline.have_readline: |
|
1476 | 1476 | self.has_readline = 0 |
|
1477 | 1477 | self.readline = None |
|
1478 | 1478 | # no point in bugging windows users with this every time: |
|
1479 | 1479 | warn('Readline services not available on this platform.') |
|
1480 | 1480 | else: |
|
1481 | 1481 | sys.modules['readline'] = readline |
|
1482 | 1482 | import atexit |
|
1483 | 1483 | from IPython.core.completer import IPCompleter |
|
1484 | 1484 | self.Completer = IPCompleter(self, |
|
1485 | 1485 | self.user_ns, |
|
1486 | 1486 | self.user_global_ns, |
|
1487 | 1487 | self.readline_omit__names, |
|
1488 | 1488 | self.alias_manager.alias_table) |
|
1489 | 1489 | sdisp = self.strdispatchers.get('complete_command', StrDispatch()) |
|
1490 | 1490 | self.strdispatchers['complete_command'] = sdisp |
|
1491 | 1491 | self.Completer.custom_completers = sdisp |
|
1492 | 1492 | # Platform-specific configuration |
|
1493 | 1493 | if os.name == 'nt': |
|
1494 | 1494 | self.readline_startup_hook = readline.set_pre_input_hook |
|
1495 | 1495 | else: |
|
1496 | 1496 | self.readline_startup_hook = readline.set_startup_hook |
|
1497 | 1497 | |
|
1498 | 1498 | # Load user's initrc file (readline config) |
|
1499 | 1499 | # Or if libedit is used, load editrc. |
|
1500 | 1500 | inputrc_name = os.environ.get('INPUTRC') |
|
1501 | 1501 | if inputrc_name is None: |
|
1502 | 1502 | home_dir = get_home_dir() |
|
1503 | 1503 | if home_dir is not None: |
|
1504 | 1504 | inputrc_name = '.inputrc' |
|
1505 | 1505 | if readline.uses_libedit: |
|
1506 | 1506 | inputrc_name = '.editrc' |
|
1507 | 1507 | inputrc_name = os.path.join(home_dir, inputrc_name) |
|
1508 | 1508 | if os.path.isfile(inputrc_name): |
|
1509 | 1509 | try: |
|
1510 | 1510 | readline.read_init_file(inputrc_name) |
|
1511 | 1511 | except: |
|
1512 | 1512 | warn('Problems reading readline initialization file <%s>' |
|
1513 | 1513 | % inputrc_name) |
|
1514 | 1514 | |
|
1515 | 1515 | self.has_readline = 1 |
|
1516 | 1516 | self.readline = readline |
|
1517 | 1517 | # save this in sys so embedded copies can restore it properly |
|
1518 | 1518 | sys.ipcompleter = self.Completer.complete |
|
1519 | 1519 | self.set_completer() |
|
1520 | 1520 | |
|
1521 | 1521 | # Configure readline according to user's prefs |
|
1522 | 1522 | # This is only done if GNU readline is being used. If libedit |
|
1523 | 1523 | # is being used (as on Leopard) the readline config is |
|
1524 | 1524 | # not run as the syntax for libedit is different. |
|
1525 | 1525 | if not readline.uses_libedit: |
|
1526 | 1526 | for rlcommand in self.readline_parse_and_bind: |
|
1527 | 1527 | #print "loading rl:",rlcommand # dbg |
|
1528 | 1528 | readline.parse_and_bind(rlcommand) |
|
1529 | 1529 | |
|
1530 | 1530 | # Remove some chars from the delimiters list. If we encounter |
|
1531 | 1531 | # unicode chars, discard them. |
|
1532 | 1532 | delims = readline.get_completer_delims().encode("ascii", "ignore") |
|
1533 | 1533 | delims = delims.translate(string._idmap, |
|
1534 | 1534 | self.readline_remove_delims) |
|
1535 | 1535 | readline.set_completer_delims(delims) |
|
1536 | 1536 | # otherwise we end up with a monster history after a while: |
|
1537 | 1537 | readline.set_history_length(1000) |
|
1538 | 1538 | try: |
|
1539 | 1539 | #print '*** Reading readline history' # dbg |
|
1540 | 1540 | readline.read_history_file(self.histfile) |
|
1541 | 1541 | except IOError: |
|
1542 | 1542 | pass # It doesn't exist yet. |
|
1543 | 1543 | |
|
1544 | 1544 | atexit.register(self.atexit_operations) |
|
1545 | 1545 | del atexit |
|
1546 | 1546 | |
|
1547 | 1547 | # Configure auto-indent for all platforms |
|
1548 | 1548 | self.set_autoindent(self.autoindent) |
|
1549 | 1549 | |
|
1550 | 1550 | def set_next_input(self, s): |
|
1551 | 1551 | """ Sets the 'default' input string for the next command line. |
|
1552 | 1552 | |
|
1553 | 1553 | Requires readline. |
|
1554 | 1554 | |
|
1555 | 1555 | Example: |
|
1556 | 1556 | |
|
1557 | 1557 | [D:\ipython]|1> _ip.set_next_input("Hello Word") |
|
1558 | 1558 | [D:\ipython]|2> Hello Word_ # cursor is here |
|
1559 | 1559 | """ |
|
1560 | 1560 | |
|
1561 | 1561 | self.rl_next_input = s |
|
1562 | 1562 | |
|
1563 | 1563 | def pre_readline(self): |
|
1564 | 1564 | """readline hook to be used at the start of each line. |
|
1565 | 1565 | |
|
1566 | 1566 | Currently it handles auto-indent only.""" |
|
1567 | 1567 | |
|
1568 | 1568 | #debugx('self.indent_current_nsp','pre_readline:') |
|
1569 | 1569 | |
|
1570 | 1570 | if self.rl_do_indent: |
|
1571 | 1571 | self.readline.insert_text(self._indent_current_str()) |
|
1572 | 1572 | if self.rl_next_input is not None: |
|
1573 | 1573 | self.readline.insert_text(self.rl_next_input) |
|
1574 | 1574 | self.rl_next_input = None |
|
1575 | 1575 | |
|
1576 | 1576 | def _indent_current_str(self): |
|
1577 | 1577 | """return the current level of indentation as a string""" |
|
1578 | 1578 | return self.indent_current_nsp * ' ' |
|
1579 | 1579 | |
|
1580 | 1580 | #------------------------------------------------------------------------- |
|
1581 | 1581 | # Things related to magics |
|
1582 | 1582 | #------------------------------------------------------------------------- |
|
1583 | 1583 | |
|
1584 | 1584 | def init_magics(self): |
|
1585 | 1585 | # Set user colors (don't do it in the constructor above so that it |
|
1586 | 1586 | # doesn't crash if colors option is invalid) |
|
1587 | 1587 | self.magic_colors(self.colors) |
|
1588 | 1588 | |
|
1589 | 1589 | def magic(self,arg_s): |
|
1590 | 1590 | """Call a magic function by name. |
|
1591 | 1591 | |
|
1592 | 1592 | Input: a string containing the name of the magic function to call and any |
|
1593 | 1593 | additional arguments to be passed to the magic. |
|
1594 | 1594 | |
|
1595 | 1595 | magic('name -opt foo bar') is equivalent to typing at the ipython |
|
1596 | 1596 | prompt: |
|
1597 | 1597 | |
|
1598 | 1598 | In[1]: %name -opt foo bar |
|
1599 | 1599 | |
|
1600 | 1600 | To call a magic without arguments, simply use magic('name'). |
|
1601 | 1601 | |
|
1602 | 1602 | This provides a proper Python function to call IPython's magics in any |
|
1603 | 1603 | valid Python code you can type at the interpreter, including loops and |
|
1604 | 1604 | compound statements. |
|
1605 | 1605 | """ |
|
1606 | 1606 | |
|
1607 | 1607 | args = arg_s.split(' ',1) |
|
1608 | 1608 | magic_name = args[0] |
|
1609 | 1609 | magic_name = magic_name.lstrip(prefilter.ESC_MAGIC) |
|
1610 | 1610 | |
|
1611 | 1611 | try: |
|
1612 | 1612 | magic_args = args[1] |
|
1613 | 1613 | except IndexError: |
|
1614 | 1614 | magic_args = '' |
|
1615 | 1615 | fn = getattr(self,'magic_'+magic_name,None) |
|
1616 | 1616 | if fn is None: |
|
1617 | 1617 | error("Magic function `%s` not found." % magic_name) |
|
1618 | 1618 | else: |
|
1619 | 1619 | magic_args = self.var_expand(magic_args,1) |
|
1620 | 1620 | with nested(self.builtin_trap,): |
|
1621 | 1621 | result = fn(magic_args) |
|
1622 | 1622 | return result |
|
1623 | 1623 | |
|
1624 | 1624 | def define_magic(self, magicname, func): |
|
1625 | 1625 | """Expose own function as magic function for ipython |
|
1626 | 1626 | |
|
1627 | 1627 | def foo_impl(self,parameter_s=''): |
|
1628 | 1628 | 'My very own magic!. (Use docstrings, IPython reads them).' |
|
1629 | 1629 | print 'Magic function. Passed parameter is between < >:' |
|
1630 | 1630 | print '<%s>' % parameter_s |
|
1631 | 1631 | print 'The self object is:',self |
|
1632 | 1632 | |
|
1633 | 1633 | self.define_magic('foo',foo_impl) |
|
1634 | 1634 | """ |
|
1635 | 1635 | |
|
1636 | 1636 | import new |
|
1637 | 1637 | im = new.instancemethod(func,self, self.__class__) |
|
1638 | 1638 | old = getattr(self, "magic_" + magicname, None) |
|
1639 | 1639 | setattr(self, "magic_" + magicname, im) |
|
1640 | 1640 | return old |
|
1641 | 1641 | |
|
1642 | 1642 | #------------------------------------------------------------------------- |
|
1643 | 1643 | # Things related to macros |
|
1644 | 1644 | #------------------------------------------------------------------------- |
|
1645 | 1645 | |
|
1646 | 1646 | def define_macro(self, name, themacro): |
|
1647 | 1647 | """Define a new macro |
|
1648 | 1648 | |
|
1649 | 1649 | Parameters |
|
1650 | 1650 | ---------- |
|
1651 | 1651 | name : str |
|
1652 | 1652 | The name of the macro. |
|
1653 | 1653 | themacro : str or Macro |
|
1654 | 1654 | The action to do upon invoking the macro. If a string, a new |
|
1655 | 1655 | Macro object is created by passing the string to it. |
|
1656 | 1656 | """ |
|
1657 | 1657 | |
|
1658 | 1658 | from IPython.core import macro |
|
1659 | 1659 | |
|
1660 | 1660 | if isinstance(themacro, basestring): |
|
1661 | 1661 | themacro = macro.Macro(themacro) |
|
1662 | 1662 | if not isinstance(themacro, macro.Macro): |
|
1663 | 1663 | raise ValueError('A macro must be a string or a Macro instance.') |
|
1664 | 1664 | self.user_ns[name] = themacro |
|
1665 | 1665 | |
|
1666 | 1666 | #------------------------------------------------------------------------- |
|
1667 | 1667 | # Things related to the running of system commands |
|
1668 | 1668 | #------------------------------------------------------------------------- |
|
1669 | 1669 | |
|
1670 | 1670 | def system(self, cmd): |
|
1671 | 1671 | """Make a system call, using IPython.""" |
|
1672 | 1672 | return self.hooks.shell_hook(self.var_expand(cmd, depth=2)) |
|
1673 | 1673 | |
|
1674 | 1674 | #------------------------------------------------------------------------- |
|
1675 | 1675 | # Things related to aliases |
|
1676 | 1676 | #------------------------------------------------------------------------- |
|
1677 | 1677 | |
|
1678 | 1678 | def init_alias(self): |
|
1679 | 1679 | self.alias_manager = AliasManager(self, config=self.config) |
|
1680 | 1680 | self.ns_table['alias'] = self.alias_manager.alias_table, |
|
1681 | 1681 | |
|
1682 | 1682 | #------------------------------------------------------------------------- |
|
1683 | 1683 | # Things related to the running of code |
|
1684 | 1684 | #------------------------------------------------------------------------- |
|
1685 | 1685 | |
|
1686 | 1686 | def ex(self, cmd): |
|
1687 | 1687 | """Execute a normal python statement in user namespace.""" |
|
1688 | 1688 | with nested(self.builtin_trap,): |
|
1689 | 1689 | exec cmd in self.user_global_ns, self.user_ns |
|
1690 | 1690 | |
|
1691 | 1691 | def ev(self, expr): |
|
1692 | 1692 | """Evaluate python expression expr in user namespace. |
|
1693 | 1693 | |
|
1694 | 1694 | Returns the result of evaluation |
|
1695 | 1695 | """ |
|
1696 | 1696 | with nested(self.builtin_trap,): |
|
1697 | 1697 | return eval(expr, self.user_global_ns, self.user_ns) |
|
1698 | 1698 | |
|
1699 | 1699 | def mainloop(self, display_banner=None): |
|
1700 | 1700 | """Start the mainloop. |
|
1701 | 1701 | |
|
1702 | 1702 | If an optional banner argument is given, it will override the |
|
1703 | 1703 | internally created default banner. |
|
1704 | 1704 | """ |
|
1705 | 1705 | |
|
1706 | 1706 | with nested(self.builtin_trap, self.display_trap): |
|
1707 | 1707 | |
|
1708 | 1708 | # if you run stuff with -c <cmd>, raw hist is not updated |
|
1709 | 1709 | # ensure that it's in sync |
|
1710 | 1710 | if len(self.input_hist) != len (self.input_hist_raw): |
|
1711 | 1711 | self.input_hist_raw = InputList(self.input_hist) |
|
1712 | 1712 | |
|
1713 | 1713 | while 1: |
|
1714 | 1714 | try: |
|
1715 | 1715 | self.interact(display_banner=display_banner) |
|
1716 | 1716 | #self.interact_with_readline() |
|
1717 | 1717 | # XXX for testing of a readline-decoupled repl loop, call |
|
1718 | 1718 | # interact_with_readline above |
|
1719 | 1719 | break |
|
1720 | 1720 | except KeyboardInterrupt: |
|
1721 | 1721 | # this should not be necessary, but KeyboardInterrupt |
|
1722 | 1722 | # handling seems rather unpredictable... |
|
1723 | 1723 | self.write("\nKeyboardInterrupt in interact()\n") |
|
1724 | 1724 | |
|
1725 | 1725 | def interact_prompt(self): |
|
1726 | 1726 | """ Print the prompt (in read-eval-print loop) |
|
1727 | 1727 | |
|
1728 | 1728 | Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not |
|
1729 | 1729 | used in standard IPython flow. |
|
1730 | 1730 | """ |
|
1731 | 1731 | if self.more: |
|
1732 | 1732 | try: |
|
1733 | 1733 | prompt = self.hooks.generate_prompt(True) |
|
1734 | 1734 | except: |
|
1735 | 1735 | self.showtraceback() |
|
1736 | 1736 | if self.autoindent: |
|
1737 | 1737 | self.rl_do_indent = True |
|
1738 | 1738 | |
|
1739 | 1739 | else: |
|
1740 | 1740 | try: |
|
1741 | 1741 | prompt = self.hooks.generate_prompt(False) |
|
1742 | 1742 | except: |
|
1743 | 1743 | self.showtraceback() |
|
1744 | 1744 | self.write(prompt) |
|
1745 | 1745 | |
|
1746 | 1746 | def interact_handle_input(self,line): |
|
1747 | 1747 | """ Handle the input line (in read-eval-print loop) |
|
1748 | 1748 | |
|
1749 | 1749 | Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not |
|
1750 | 1750 | used in standard IPython flow. |
|
1751 | 1751 | """ |
|
1752 | 1752 | if line.lstrip() == line: |
|
1753 | 1753 | self.shadowhist.add(line.strip()) |
|
1754 | 1754 | lineout = self.prefilter_manager.prefilter_lines(line,self.more) |
|
1755 | 1755 | |
|
1756 | 1756 | if line.strip(): |
|
1757 | 1757 | if self.more: |
|
1758 | 1758 | self.input_hist_raw[-1] += '%s\n' % line |
|
1759 | 1759 | else: |
|
1760 | 1760 | self.input_hist_raw.append('%s\n' % line) |
|
1761 | 1761 | |
|
1762 | 1762 | |
|
1763 | 1763 | self.more = self.push_line(lineout) |
|
1764 | 1764 | if (self.SyntaxTB.last_syntax_error and |
|
1765 | 1765 | self.autoedit_syntax): |
|
1766 | 1766 | self.edit_syntax_error() |
|
1767 | 1767 | |
|
1768 | 1768 | def interact_with_readline(self): |
|
1769 | 1769 | """ Demo of using interact_handle_input, interact_prompt |
|
1770 | 1770 | |
|
1771 | 1771 | This is the main read-eval-print loop. If you need to implement your own (e.g. for GUI), |
|
1772 | 1772 | it should work like this. |
|
1773 | 1773 | """ |
|
1774 | 1774 | self.readline_startup_hook(self.pre_readline) |
|
1775 | 1775 | while not self.exit_now: |
|
1776 | 1776 | self.interact_prompt() |
|
1777 | 1777 | if self.more: |
|
1778 | 1778 | self.rl_do_indent = True |
|
1779 | 1779 | else: |
|
1780 | 1780 | self.rl_do_indent = False |
|
1781 | 1781 | line = raw_input_original().decode(self.stdin_encoding) |
|
1782 | 1782 | self.interact_handle_input(line) |
|
1783 | 1783 | |
|
1784 | 1784 | def interact(self, display_banner=None): |
|
1785 | 1785 | """Closely emulate the interactive Python console.""" |
|
1786 | 1786 | |
|
1787 | 1787 | # batch run -> do not interact |
|
1788 | 1788 | if self.exit_now: |
|
1789 | 1789 | return |
|
1790 | 1790 | |
|
1791 | 1791 | if display_banner is None: |
|
1792 | 1792 | display_banner = self.display_banner |
|
1793 | 1793 | if display_banner: |
|
1794 | 1794 | self.show_banner() |
|
1795 | 1795 | |
|
1796 | 1796 | more = 0 |
|
1797 | 1797 | |
|
1798 | 1798 | # Mark activity in the builtins |
|
1799 | 1799 | __builtin__.__dict__['__IPYTHON__active'] += 1 |
|
1800 | 1800 | |
|
1801 | 1801 | if self.has_readline: |
|
1802 | 1802 | self.readline_startup_hook(self.pre_readline) |
|
1803 | 1803 | # exit_now is set by a call to %Exit or %Quit, through the |
|
1804 | 1804 | # ask_exit callback. |
|
1805 | 1805 | |
|
1806 | 1806 | while not self.exit_now: |
|
1807 | 1807 | self.hooks.pre_prompt_hook() |
|
1808 | 1808 | if more: |
|
1809 | 1809 | try: |
|
1810 | 1810 | prompt = self.hooks.generate_prompt(True) |
|
1811 | 1811 | except: |
|
1812 | 1812 | self.showtraceback() |
|
1813 | 1813 | if self.autoindent: |
|
1814 | 1814 | self.rl_do_indent = True |
|
1815 | 1815 | |
|
1816 | 1816 | else: |
|
1817 | 1817 | try: |
|
1818 | 1818 | prompt = self.hooks.generate_prompt(False) |
|
1819 | 1819 | except: |
|
1820 | 1820 | self.showtraceback() |
|
1821 | 1821 | try: |
|
1822 | 1822 | line = self.raw_input(prompt, more) |
|
1823 | 1823 | if self.exit_now: |
|
1824 | 1824 | # quick exit on sys.std[in|out] close |
|
1825 | 1825 | break |
|
1826 | 1826 | if self.autoindent: |
|
1827 | 1827 | self.rl_do_indent = False |
|
1828 | 1828 | |
|
1829 | 1829 | except KeyboardInterrupt: |
|
1830 | 1830 | #double-guard against keyboardinterrupts during kbdint handling |
|
1831 | 1831 | try: |
|
1832 | 1832 | self.write('\nKeyboardInterrupt\n') |
|
1833 | 1833 | self.resetbuffer() |
|
1834 | 1834 | # keep cache in sync with the prompt counter: |
|
1835 | 1835 | self.outputcache.prompt_count -= 1 |
|
1836 | 1836 | |
|
1837 | 1837 | if self.autoindent: |
|
1838 | 1838 | self.indent_current_nsp = 0 |
|
1839 | 1839 | more = 0 |
|
1840 | 1840 | except KeyboardInterrupt: |
|
1841 | 1841 | pass |
|
1842 | 1842 | except EOFError: |
|
1843 | 1843 | if self.autoindent: |
|
1844 | 1844 | self.rl_do_indent = False |
|
1845 | 1845 | self.readline_startup_hook(None) |
|
1846 | 1846 | self.write('\n') |
|
1847 | 1847 | self.exit() |
|
1848 | 1848 | except bdb.BdbQuit: |
|
1849 | 1849 | warn('The Python debugger has exited with a BdbQuit exception.\n' |
|
1850 | 1850 | 'Because of how pdb handles the stack, it is impossible\n' |
|
1851 | 1851 | 'for IPython to properly format this particular exception.\n' |
|
1852 | 1852 | 'IPython will resume normal operation.') |
|
1853 | 1853 | except: |
|
1854 | 1854 | # exceptions here are VERY RARE, but they can be triggered |
|
1855 | 1855 | # asynchronously by signal handlers, for example. |
|
1856 | 1856 | self.showtraceback() |
|
1857 | 1857 | else: |
|
1858 | 1858 | more = self.push_line(line) |
|
1859 | 1859 | if (self.SyntaxTB.last_syntax_error and |
|
1860 | 1860 | self.autoedit_syntax): |
|
1861 | 1861 | self.edit_syntax_error() |
|
1862 | 1862 | |
|
1863 | 1863 | # We are off again... |
|
1864 | 1864 | __builtin__.__dict__['__IPYTHON__active'] -= 1 |
|
1865 | 1865 | |
|
1866 | 1866 | def safe_execfile(self, fname, *where, **kw): |
|
1867 | 1867 | """A safe version of the builtin execfile(). |
|
1868 | 1868 | |
|
1869 | 1869 | This version will never throw an exception, but instead print |
|
1870 | 1870 | helpful error messages to the screen. This only works on pure |
|
1871 | 1871 | Python files with the .py extension. |
|
1872 | 1872 | |
|
1873 | 1873 | Parameters |
|
1874 | 1874 | ---------- |
|
1875 | 1875 | fname : string |
|
1876 | 1876 | The name of the file to be executed. |
|
1877 | 1877 | where : tuple |
|
1878 | 1878 | One or two namespaces, passed to execfile() as (globals,locals). |
|
1879 | 1879 | If only one is given, it is passed as both. |
|
1880 | 1880 | exit_ignore : bool (False) |
|
1881 | 1881 | If True, then don't print errors for non-zero exit statuses. |
|
1882 | 1882 | """ |
|
1883 | 1883 | kw.setdefault('exit_ignore', False) |
|
1884 | 1884 | |
|
1885 | 1885 | fname = os.path.abspath(os.path.expanduser(fname)) |
|
1886 | 1886 | |
|
1887 | 1887 | # Make sure we have a .py file |
|
1888 | 1888 | if not fname.endswith('.py'): |
|
1889 | 1889 | warn('File must end with .py to be run using execfile: <%s>' % fname) |
|
1890 | 1890 | |
|
1891 | 1891 | # Make sure we can open the file |
|
1892 | 1892 | try: |
|
1893 | 1893 | with open(fname) as thefile: |
|
1894 | 1894 | pass |
|
1895 | 1895 | except: |
|
1896 | 1896 | warn('Could not open file <%s> for safe execution.' % fname) |
|
1897 | 1897 | return |
|
1898 | 1898 | |
|
1899 | 1899 | # Find things also in current directory. This is needed to mimic the |
|
1900 | 1900 | # behavior of running a script from the system command line, where |
|
1901 | 1901 | # Python inserts the script's directory into sys.path |
|
1902 | 1902 | dname = os.path.dirname(fname) |
|
1903 | 1903 | |
|
1904 | 1904 | with prepended_to_syspath(dname): |
|
1905 | 1905 | try: |
|
1906 | 1906 | if sys.platform == 'win32' and sys.version_info < (2,5,1): |
|
1907 | 1907 | # Work around a bug in Python for Windows. The bug was |
|
1908 | 1908 | # fixed in in Python 2.5 r54159 and 54158, but that's still |
|
1909 | 1909 | # SVN Python as of March/07. For details, see: |
|
1910 | 1910 | # http://projects.scipy.org/ipython/ipython/ticket/123 |
|
1911 | 1911 | try: |
|
1912 | 1912 | globs,locs = where[0:2] |
|
1913 | 1913 | except: |
|
1914 | 1914 | try: |
|
1915 | 1915 | globs = locs = where[0] |
|
1916 | 1916 | except: |
|
1917 | 1917 | globs = locs = globals() |
|
1918 | 1918 | exec file(fname) in globs,locs |
|
1919 | 1919 | else: |
|
1920 | 1920 | execfile(fname,*where) |
|
1921 | 1921 | except SyntaxError: |
|
1922 | 1922 | self.showsyntaxerror() |
|
1923 | 1923 | warn('Failure executing file: <%s>' % fname) |
|
1924 | 1924 | except SystemExit, status: |
|
1925 | 1925 | # Code that correctly sets the exit status flag to success (0) |
|
1926 | 1926 | # shouldn't be bothered with a traceback. Note that a plain |
|
1927 | 1927 | # sys.exit() does NOT set the message to 0 (it's empty) so that |
|
1928 | 1928 | # will still get a traceback. Note that the structure of the |
|
1929 | 1929 | # SystemExit exception changed between Python 2.4 and 2.5, so |
|
1930 | 1930 | # the checks must be done in a version-dependent way. |
|
1931 | 1931 | show = False |
|
1932 | 1932 | if status.args[0]==0 and not kw['exit_ignore']: |
|
1933 | 1933 | show = True |
|
1934 | 1934 | if show: |
|
1935 | 1935 | self.showtraceback() |
|
1936 | 1936 | warn('Failure executing file: <%s>' % fname) |
|
1937 | 1937 | except: |
|
1938 | 1938 | self.showtraceback() |
|
1939 | 1939 | warn('Failure executing file: <%s>' % fname) |
|
1940 | 1940 | |
|
1941 | 1941 | def safe_execfile_ipy(self, fname): |
|
1942 | 1942 | """Like safe_execfile, but for .ipy files with IPython syntax. |
|
1943 | 1943 | |
|
1944 | 1944 | Parameters |
|
1945 | 1945 | ---------- |
|
1946 | 1946 | fname : str |
|
1947 | 1947 | The name of the file to execute. The filename must have a |
|
1948 | 1948 | .ipy extension. |
|
1949 | 1949 | """ |
|
1950 | 1950 | fname = os.path.abspath(os.path.expanduser(fname)) |
|
1951 | 1951 | |
|
1952 | 1952 | # Make sure we have a .py file |
|
1953 | 1953 | if not fname.endswith('.ipy'): |
|
1954 | 1954 | warn('File must end with .py to be run using execfile: <%s>' % fname) |
|
1955 | 1955 | |
|
1956 | 1956 | # Make sure we can open the file |
|
1957 | 1957 | try: |
|
1958 | 1958 | with open(fname) as thefile: |
|
1959 | 1959 | pass |
|
1960 | 1960 | except: |
|
1961 | 1961 | warn('Could not open file <%s> for safe execution.' % fname) |
|
1962 | 1962 | return |
|
1963 | 1963 | |
|
1964 | 1964 | # Find things also in current directory. This is needed to mimic the |
|
1965 | 1965 | # behavior of running a script from the system command line, where |
|
1966 | 1966 | # Python inserts the script's directory into sys.path |
|
1967 | 1967 | dname = os.path.dirname(fname) |
|
1968 | 1968 | |
|
1969 | 1969 | with prepended_to_syspath(dname): |
|
1970 | 1970 | try: |
|
1971 | 1971 | with open(fname) as thefile: |
|
1972 | 1972 | script = thefile.read() |
|
1973 | 1973 | # self.runlines currently captures all exceptions |
|
1974 | 1974 | # raise in user code. It would be nice if there were |
|
1975 | 1975 | # versions of runlines, execfile that did raise, so |
|
1976 | 1976 | # we could catch the errors. |
|
1977 | 1977 | self.runlines(script, clean=True) |
|
1978 | 1978 | except: |
|
1979 | 1979 | self.showtraceback() |
|
1980 | 1980 | warn('Unknown failure executing file: <%s>' % fname) |
|
1981 | 1981 | |
|
1982 | 1982 | def _is_secondary_block_start(self, s): |
|
1983 | 1983 | if not s.endswith(':'): |
|
1984 | 1984 | return False |
|
1985 | 1985 | if (s.startswith('elif') or |
|
1986 | 1986 | s.startswith('else') or |
|
1987 | 1987 | s.startswith('except') or |
|
1988 | 1988 | s.startswith('finally')): |
|
1989 | 1989 | return True |
|
1990 | 1990 | |
|
1991 | 1991 | def cleanup_ipy_script(self, script): |
|
1992 | 1992 | """Make a script safe for self.runlines() |
|
1993 | 1993 | |
|
1994 | 1994 | Currently, IPython is lines based, with blocks being detected by |
|
1995 | 1995 | empty lines. This is a problem for block based scripts that may |
|
1996 | 1996 | not have empty lines after blocks. This script adds those empty |
|
1997 | 1997 | lines to make scripts safe for running in the current line based |
|
1998 | 1998 | IPython. |
|
1999 | 1999 | """ |
|
2000 | 2000 | res = [] |
|
2001 | 2001 | lines = script.splitlines() |
|
2002 | 2002 | level = 0 |
|
2003 | 2003 | |
|
2004 | 2004 | for l in lines: |
|
2005 | 2005 | lstripped = l.lstrip() |
|
2006 | 2006 | stripped = l.strip() |
|
2007 | 2007 | if not stripped: |
|
2008 | 2008 | continue |
|
2009 | 2009 | newlevel = len(l) - len(lstripped) |
|
2010 | 2010 | if level > 0 and newlevel == 0 and \ |
|
2011 | 2011 | not self._is_secondary_block_start(stripped): |
|
2012 | 2012 | # add empty line |
|
2013 | 2013 | res.append('') |
|
2014 | 2014 | res.append(l) |
|
2015 | 2015 | level = newlevel |
|
2016 | 2016 | |
|
2017 | 2017 | return '\n'.join(res) + '\n' |
|
2018 | 2018 | |
|
2019 | 2019 | def runlines(self, lines, clean=False): |
|
2020 | 2020 | """Run a string of one or more lines of source. |
|
2021 | 2021 | |
|
2022 | 2022 | This method is capable of running a string containing multiple source |
|
2023 | 2023 | lines, as if they had been entered at the IPython prompt. Since it |
|
2024 | 2024 | exposes IPython's processing machinery, the given strings can contain |
|
2025 | 2025 | magic calls (%magic), special shell access (!cmd), etc. |
|
2026 | 2026 | """ |
|
2027 | 2027 | |
|
2028 | 2028 | if isinstance(lines, (list, tuple)): |
|
2029 | 2029 | lines = '\n'.join(lines) |
|
2030 | 2030 | |
|
2031 | 2031 | if clean: |
|
2032 | 2032 | lines = self.cleanup_ipy_script(lines) |
|
2033 | 2033 | |
|
2034 | 2034 | # We must start with a clean buffer, in case this is run from an |
|
2035 | 2035 | # interactive IPython session (via a magic, for example). |
|
2036 | 2036 | self.resetbuffer() |
|
2037 | 2037 | lines = lines.splitlines() |
|
2038 | 2038 | more = 0 |
|
2039 | 2039 | |
|
2040 | 2040 | with nested(self.builtin_trap, self.display_trap): |
|
2041 | 2041 | for line in lines: |
|
2042 | 2042 | # skip blank lines so we don't mess up the prompt counter, but do |
|
2043 | 2043 | # NOT skip even a blank line if we are in a code block (more is |
|
2044 | 2044 | # true) |
|
2045 | 2045 | |
|
2046 | 2046 | if line or more: |
|
2047 | 2047 | # push to raw history, so hist line numbers stay in sync |
|
2048 | 2048 | self.input_hist_raw.append("# " + line + "\n") |
|
2049 | 2049 | prefiltered = self.prefilter_manager.prefilter_lines(line,more) |
|
2050 | 2050 | more = self.push_line(prefiltered) |
|
2051 | 2051 | # IPython's runsource returns None if there was an error |
|
2052 | 2052 | # compiling the code. This allows us to stop processing right |
|
2053 | 2053 | # away, so the user gets the error message at the right place. |
|
2054 | 2054 | if more is None: |
|
2055 | 2055 | break |
|
2056 | 2056 | else: |
|
2057 | 2057 | self.input_hist_raw.append("\n") |
|
2058 | 2058 | # final newline in case the input didn't have it, so that the code |
|
2059 | 2059 | # actually does get executed |
|
2060 | 2060 | if more: |
|
2061 | 2061 | self.push_line('\n') |
|
2062 | 2062 | |
|
2063 | 2063 | def runsource(self, source, filename='<input>', symbol='single'): |
|
2064 | 2064 | """Compile and run some source in the interpreter. |
|
2065 | 2065 | |
|
2066 | 2066 | Arguments are as for compile_command(). |
|
2067 | 2067 | |
|
2068 | 2068 | One several things can happen: |
|
2069 | 2069 | |
|
2070 | 2070 | 1) The input is incorrect; compile_command() raised an |
|
2071 | 2071 | exception (SyntaxError or OverflowError). A syntax traceback |
|
2072 | 2072 | will be printed by calling the showsyntaxerror() method. |
|
2073 | 2073 | |
|
2074 | 2074 | 2) The input is incomplete, and more input is required; |
|
2075 | 2075 | compile_command() returned None. Nothing happens. |
|
2076 | 2076 | |
|
2077 | 2077 | 3) The input is complete; compile_command() returned a code |
|
2078 | 2078 | object. The code is executed by calling self.runcode() (which |
|
2079 | 2079 | also handles run-time exceptions, except for SystemExit). |
|
2080 | 2080 | |
|
2081 | 2081 | The return value is: |
|
2082 | 2082 | |
|
2083 | 2083 | - True in case 2 |
|
2084 | 2084 | |
|
2085 | 2085 | - False in the other cases, unless an exception is raised, where |
|
2086 | 2086 | None is returned instead. This can be used by external callers to |
|
2087 | 2087 | know whether to continue feeding input or not. |
|
2088 | 2088 | |
|
2089 | 2089 | The return value can be used to decide whether to use sys.ps1 or |
|
2090 | 2090 | sys.ps2 to prompt the next line.""" |
|
2091 | 2091 | |
|
2092 | 2092 | # if the source code has leading blanks, add 'if 1:\n' to it |
|
2093 | 2093 | # this allows execution of indented pasted code. It is tempting |
|
2094 | 2094 | # to add '\n' at the end of source to run commands like ' a=1' |
|
2095 | 2095 | # directly, but this fails for more complicated scenarios |
|
2096 | 2096 | source=source.encode(self.stdin_encoding) |
|
2097 | 2097 | if source[:1] in [' ', '\t']: |
|
2098 | 2098 | source = 'if 1:\n%s' % source |
|
2099 | 2099 | |
|
2100 | 2100 | try: |
|
2101 | 2101 | code = self.compile(source,filename,symbol) |
|
2102 | 2102 | except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError): |
|
2103 | 2103 | # Case 1 |
|
2104 | 2104 | self.showsyntaxerror(filename) |
|
2105 | 2105 | return None |
|
2106 | 2106 | |
|
2107 | 2107 | if code is None: |
|
2108 | 2108 | # Case 2 |
|
2109 | 2109 | return True |
|
2110 | 2110 | |
|
2111 | 2111 | # Case 3 |
|
2112 | 2112 | # We store the code object so that threaded shells and |
|
2113 | 2113 | # custom exception handlers can access all this info if needed. |
|
2114 | 2114 | # The source corresponding to this can be obtained from the |
|
2115 | 2115 | # buffer attribute as '\n'.join(self.buffer). |
|
2116 | 2116 | self.code_to_run = code |
|
2117 | 2117 | # now actually execute the code object |
|
2118 | 2118 | if self.runcode(code) == 0: |
|
2119 | 2119 | return False |
|
2120 | 2120 | else: |
|
2121 | 2121 | return None |
|
2122 | 2122 | |
|
2123 | 2123 | def runcode(self,code_obj): |
|
2124 | 2124 | """Execute a code object. |
|
2125 | 2125 | |
|
2126 | 2126 | When an exception occurs, self.showtraceback() is called to display a |
|
2127 | 2127 | traceback. |
|
2128 | 2128 | |
|
2129 | 2129 | Return value: a flag indicating whether the code to be run completed |
|
2130 | 2130 | successfully: |
|
2131 | 2131 | |
|
2132 | 2132 | - 0: successful execution. |
|
2133 | 2133 | - 1: an error occurred. |
|
2134 | 2134 | """ |
|
2135 | 2135 | |
|
2136 | 2136 | # Set our own excepthook in case the user code tries to call it |
|
2137 | 2137 | # directly, so that the IPython crash handler doesn't get triggered |
|
2138 | 2138 | old_excepthook,sys.excepthook = sys.excepthook, self.excepthook |
|
2139 | 2139 | |
|
2140 | 2140 | # we save the original sys.excepthook in the instance, in case config |
|
2141 | 2141 | # code (such as magics) needs access to it. |
|
2142 | 2142 | self.sys_excepthook = old_excepthook |
|
2143 | 2143 | outflag = 1 # happens in more places, so it's easier as default |
|
2144 | 2144 | try: |
|
2145 | 2145 | try: |
|
2146 | 2146 | self.hooks.pre_runcode_hook() |
|
2147 | 2147 | exec code_obj in self.user_global_ns, self.user_ns |
|
2148 | 2148 | finally: |
|
2149 | 2149 | # Reset our crash handler in place |
|
2150 | 2150 | sys.excepthook = old_excepthook |
|
2151 | 2151 | except SystemExit: |
|
2152 | 2152 | self.resetbuffer() |
|
2153 | 2153 | self.showtraceback() |
|
2154 | 2154 | warn("Type %exit or %quit to exit IPython " |
|
2155 | 2155 | "(%Exit or %Quit do so unconditionally).",level=1) |
|
2156 | 2156 | except self.custom_exceptions: |
|
2157 | 2157 | etype,value,tb = sys.exc_info() |
|
2158 | 2158 | self.CustomTB(etype,value,tb) |
|
2159 | 2159 | except: |
|
2160 | 2160 | self.showtraceback() |
|
2161 | 2161 | else: |
|
2162 | 2162 | outflag = 0 |
|
2163 | 2163 | if softspace(sys.stdout, 0): |
|
2164 | 2164 | |
|
2165 | 2165 | # Flush out code object which has been run (and source) |
|
2166 | 2166 | self.code_to_run = None |
|
2167 | 2167 | return outflag |
|
2168 | 2168 | |
|
2169 | 2169 | def push_line(self, line): |
|
2170 | 2170 | """Push a line to the interpreter. |
|
2171 | 2171 | |
|
2172 | 2172 | The line should not have a trailing newline; it may have |
|
2173 | 2173 | internal newlines. The line is appended to a buffer and the |
|
2174 | 2174 | interpreter's runsource() method is called with the |
|
2175 | 2175 | concatenated contents of the buffer as source. If this |
|
2176 | 2176 | indicates that the command was executed or invalid, the buffer |
|
2177 | 2177 | is reset; otherwise, the command is incomplete, and the buffer |
|
2178 | 2178 | is left as it was after the line was appended. The return |
|
2179 | 2179 | value is 1 if more input is required, 0 if the line was dealt |
|
2180 | 2180 | with in some way (this is the same as runsource()). |
|
2181 | 2181 | """ |
|
2182 | 2182 | |
|
2183 | 2183 | # autoindent management should be done here, and not in the |
|
2184 | 2184 | # interactive loop, since that one is only seen by keyboard input. We |
|
2185 | 2185 | # need this done correctly even for code run via runlines (which uses |
|
2186 | 2186 | # push). |
|
2187 | 2187 | |
|
2188 | 2188 | #print 'push line: <%s>' % line # dbg |
|
2189 | 2189 | for subline in line.splitlines(): |
|
2190 | 2190 | self._autoindent_update(subline) |
|
2191 | 2191 | self.buffer.append(line) |
|
2192 | 2192 | more = self.runsource('\n'.join(self.buffer), self.filename) |
|
2193 | 2193 | if not more: |
|
2194 | 2194 | self.resetbuffer() |
|
2195 | 2195 | return more |
|
2196 | 2196 | |
|
2197 | 2197 | def _autoindent_update(self,line): |
|
2198 | 2198 | """Keep track of the indent level.""" |
|
2199 | 2199 | |
|
2200 | 2200 | #debugx('line') |
|
2201 | 2201 | #debugx('self.indent_current_nsp') |
|
2202 | 2202 | if self.autoindent: |
|
2203 | 2203 | if line: |
|
2204 | 2204 | inisp = num_ini_spaces(line) |
|
2205 | 2205 | if inisp < self.indent_current_nsp: |
|
2206 | 2206 | self.indent_current_nsp = inisp |
|
2207 | 2207 | |
|
2208 | 2208 | if line[-1] == ':': |
|
2209 | 2209 | self.indent_current_nsp += 4 |
|
2210 | 2210 | elif dedent_re.match(line): |
|
2211 | 2211 | self.indent_current_nsp -= 4 |
|
2212 | 2212 | else: |
|
2213 | 2213 | self.indent_current_nsp = 0 |
|
2214 | 2214 | |
|
2215 | 2215 | def resetbuffer(self): |
|
2216 | 2216 | """Reset the input buffer.""" |
|
2217 | 2217 | self.buffer[:] = [] |
|
2218 | 2218 | |
|
2219 | 2219 | def raw_input(self,prompt='',continue_prompt=False): |
|
2220 | 2220 | """Write a prompt and read a line. |
|
2221 | 2221 | |
|
2222 | 2222 | The returned line does not include the trailing newline. |
|
2223 | 2223 | When the user enters the EOF key sequence, EOFError is raised. |
|
2224 | 2224 | |
|
2225 | 2225 | Optional inputs: |
|
2226 | 2226 | |
|
2227 | 2227 | - prompt(''): a string to be printed to prompt the user. |
|
2228 | 2228 | |
|
2229 | 2229 | - continue_prompt(False): whether this line is the first one or a |
|
2230 | 2230 | continuation in a sequence of inputs. |
|
2231 | 2231 | """ |
|
2232 | 2232 | # growl.notify("raw_input: ", "prompt = %r\ncontinue_prompt = %s" % (prompt, continue_prompt)) |
|
2233 | 2233 | |
|
2234 | 2234 | # Code run by the user may have modified the readline completer state. |
|
2235 | 2235 | # We must ensure that our completer is back in place. |
|
2236 | 2236 | |
|
2237 | 2237 | if self.has_readline: |
|
2238 | 2238 | self.set_completer() |
|
2239 | 2239 | |
|
2240 | 2240 | try: |
|
2241 | 2241 | line = raw_input_original(prompt).decode(self.stdin_encoding) |
|
2242 | 2242 | except ValueError: |
|
2243 | 2243 | warn("\n********\nYou or a %run:ed script called sys.stdin.close()" |
|
2244 | 2244 | " or sys.stdout.close()!\nExiting IPython!") |
|
2245 | 2245 | self.ask_exit() |
|
2246 | 2246 | return "" |
|
2247 | 2247 | |
|
2248 | 2248 | # Try to be reasonably smart about not re-indenting pasted input more |
|
2249 | 2249 | # than necessary. We do this by trimming out the auto-indent initial |
|
2250 | 2250 | # spaces, if the user's actual input started itself with whitespace. |
|
2251 | 2251 | #debugx('self.buffer[-1]') |
|
2252 | 2252 | |
|
2253 | 2253 | if self.autoindent: |
|
2254 | 2254 | if num_ini_spaces(line) > self.indent_current_nsp: |
|
2255 | 2255 | line = line[self.indent_current_nsp:] |
|
2256 | 2256 | self.indent_current_nsp = 0 |
|
2257 | 2257 | |
|
2258 | 2258 | # store the unfiltered input before the user has any chance to modify |
|
2259 | 2259 | # it. |
|
2260 | 2260 | if line.strip(): |
|
2261 | 2261 | if continue_prompt: |
|
2262 | 2262 | self.input_hist_raw[-1] += '%s\n' % line |
|
2263 | 2263 | if self.has_readline and self.readline_use: |
|
2264 | 2264 | try: |
|
2265 | 2265 | histlen = self.readline.get_current_history_length() |
|
2266 | 2266 | if histlen > 1: |
|
2267 | 2267 | newhist = self.input_hist_raw[-1].rstrip() |
|
2268 | 2268 | self.readline.remove_history_item(histlen-1) |
|
2269 | 2269 | self.readline.replace_history_item(histlen-2, |
|
2270 | 2270 | newhist.encode(self.stdin_encoding)) |
|
2271 | 2271 | except AttributeError: |
|
2272 | 2272 | pass # re{move,place}_history_item are new in 2.4. |
|
2273 | 2273 | else: |
|
2274 | 2274 | self.input_hist_raw.append('%s\n' % line) |
|
2275 | 2275 | # only entries starting at first column go to shadow history |
|
2276 | 2276 | if line.lstrip() == line: |
|
2277 | 2277 | self.shadowhist.add(line.strip()) |
|
2278 | 2278 | elif not continue_prompt: |
|
2279 | 2279 | self.input_hist_raw.append('\n') |
|
2280 | 2280 | try: |
|
2281 | 2281 | lineout = self.prefilter_manager.prefilter_lines(line,continue_prompt) |
|
2282 | 2282 | except: |
|
2283 | 2283 | # blanket except, in case a user-defined prefilter crashes, so it |
|
2284 | 2284 | # can't take all of ipython with it. |
|
2285 | 2285 | self.showtraceback() |
|
2286 | 2286 | return '' |
|
2287 | 2287 | else: |
|
2288 | 2288 | return lineout |
|
2289 | 2289 | |
|
2290 | 2290 | #------------------------------------------------------------------------- |
|
2291 | 2291 | # Working with components |
|
2292 | 2292 | #------------------------------------------------------------------------- |
|
2293 | 2293 | |
|
2294 | 2294 | def get_component(self, name=None, klass=None): |
|
2295 | 2295 | """Fetch a component by name and klass in my tree.""" |
|
2296 | 2296 | c = Component.get_instances(root=self, name=name, klass=klass) |
|
2297 | 2297 | if len(c) == 0: |
|
2298 | 2298 | return None |
|
2299 | 2299 | if len(c) == 1: |
|
2300 | 2300 | return c[0] |
|
2301 | 2301 | else: |
|
2302 | 2302 | return c |
|
2303 | 2303 | |
|
2304 | 2304 | #------------------------------------------------------------------------- |
|
2305 | 2305 | # IPython extensions |
|
2306 | 2306 | #------------------------------------------------------------------------- |
|
2307 | 2307 | |
|
2308 | 2308 | def load_extension(self, module_str): |
|
2309 | 2309 | """Load an IPython extension by its module name. |
|
2310 | 2310 | |
|
2311 | 2311 | An IPython extension is an importable Python module that has |
|
2312 | 2312 | a function with the signature:: |
|
2313 | 2313 | |
|
2314 | 2314 | def load_ipython_extension(ipython): |
|
2315 | 2315 | # Do things with ipython |
|
2316 | 2316 | |
|
2317 | 2317 | This function is called after your extension is imported and the |
|
2318 | 2318 | currently active :class:`InteractiveShell` instance is passed as |
|
2319 | 2319 | the only argument. You can do anything you want with IPython at |
|
2320 | 2320 | that point, including defining new magic and aliases, adding new |
|
2321 | 2321 | components, etc. |
|
2322 | 2322 | |
|
2323 | 2323 | The :func:`load_ipython_extension` will be called again is you |
|
2324 | 2324 | load or reload the extension again. It is up to the extension |
|
2325 | 2325 | author to add code to manage that. |
|
2326 | 2326 | |
|
2327 | 2327 | You can put your extension modules anywhere you want, as long as |
|
2328 | 2328 | they can be imported by Python's standard import mechanism. However, |
|
2329 | 2329 | to make it easy to write extensions, you can also put your extensions |
|
2330 | 2330 | in ``os.path.join(self.ipython_dir, 'extensions')``. This directory |
|
2331 | 2331 | is added to ``sys.path`` automatically. |
|
2332 | 2332 | """ |
|
2333 | 2333 | from IPython.utils.syspathcontext import prepended_to_syspath |
|
2334 | 2334 | |
|
2335 | 2335 | if module_str not in sys.modules: |
|
2336 | 2336 | with prepended_to_syspath(self.ipython_extension_dir): |
|
2337 | 2337 | __import__(module_str) |
|
2338 | 2338 | mod = sys.modules[module_str] |
|
2339 | 2339 | self._call_load_ipython_extension(mod) |
|
2340 | 2340 | |
|
2341 | 2341 | def unload_extension(self, module_str): |
|
2342 | 2342 | """Unload an IPython extension by its module name. |
|
2343 | 2343 | |
|
2344 | 2344 | This function looks up the extension's name in ``sys.modules`` and |
|
2345 | 2345 | simply calls ``mod.unload_ipython_extension(self)``. |
|
2346 | 2346 | """ |
|
2347 | 2347 | if module_str in sys.modules: |
|
2348 | 2348 | mod = sys.modules[module_str] |
|
2349 | 2349 | self._call_unload_ipython_extension(mod) |
|
2350 | 2350 | |
|
2351 | 2351 | def reload_extension(self, module_str): |
|
2352 | 2352 | """Reload an IPython extension by calling reload. |
|
2353 | 2353 | |
|
2354 | 2354 | If the module has not been loaded before, |
|
2355 | 2355 | :meth:`InteractiveShell.load_extension` is called. Otherwise |
|
2356 | 2356 | :func:`reload` is called and then the :func:`load_ipython_extension` |
|
2357 | 2357 | function of the module, if it exists is called. |
|
2358 | 2358 | """ |
|
2359 | 2359 | from IPython.utils.syspathcontext import prepended_to_syspath |
|
2360 | 2360 | |
|
2361 | 2361 | with prepended_to_syspath(self.ipython_extension_dir): |
|
2362 | 2362 | if module_str in sys.modules: |
|
2363 | 2363 | mod = sys.modules[module_str] |
|
2364 | 2364 | reload(mod) |
|
2365 | 2365 | self._call_load_ipython_extension(mod) |
|
2366 | 2366 | else: |
|
2367 | 2367 | self.load_extension(module_str) |
|
2368 | 2368 | |
|
2369 | 2369 | def _call_load_ipython_extension(self, mod): |
|
2370 | 2370 | if hasattr(mod, 'load_ipython_extension'): |
|
2371 | 2371 | mod.load_ipython_extension(self) |
|
2372 | 2372 | |
|
2373 | 2373 | def _call_unload_ipython_extension(self, mod): |
|
2374 | 2374 | if hasattr(mod, 'unload_ipython_extension'): |
|
2375 | 2375 | mod.unload_ipython_extension(self) |
|
2376 | 2376 | |
|
2377 | 2377 | #------------------------------------------------------------------------- |
|
2378 | 2378 | # Things related to the prefilter |
|
2379 | 2379 | #------------------------------------------------------------------------- |
|
2380 | 2380 | |
|
2381 | 2381 | def init_prefilter(self): |
|
2382 | 2382 | self.prefilter_manager = PrefilterManager(self, config=self.config) |
|
2383 | 2383 | |
|
2384 | 2384 | #------------------------------------------------------------------------- |
|
2385 | 2385 | # Utilities |
|
2386 | 2386 | #------------------------------------------------------------------------- |
|
2387 | 2387 | |
|
2388 | 2388 | def getoutput(self, cmd): |
|
2389 | 2389 | return getoutput(self.var_expand(cmd,depth=2), |
|
2390 | 2390 | header=self.system_header, |
|
2391 | 2391 | verbose=self.system_verbose) |
|
2392 | 2392 | |
|
2393 | 2393 | def getoutputerror(self, cmd): |
|
2394 | 2394 | return getoutputerror(self.var_expand(cmd,depth=2), |
|
2395 | 2395 | header=self.system_header, |
|
2396 | 2396 | verbose=self.system_verbose) |
|
2397 | 2397 | |
|
2398 | 2398 | def var_expand(self,cmd,depth=0): |
|
2399 | 2399 | """Expand python variables in a string. |
|
2400 | 2400 | |
|
2401 | 2401 | The depth argument indicates how many frames above the caller should |
|
2402 | 2402 | be walked to look for the local namespace where to expand variables. |
|
2403 | 2403 | |
|
2404 | 2404 | The global namespace for expansion is always the user's interactive |
|
2405 | 2405 | namespace. |
|
2406 | 2406 | """ |
|
2407 | 2407 | |
|
2408 | 2408 | return str(ItplNS(cmd, |
|
2409 | 2409 | self.user_ns, # globals |
|
2410 | 2410 | # Skip our own frame in searching for locals: |
|
2411 | 2411 | sys._getframe(depth+1).f_locals # locals |
|
2412 | 2412 | )) |
|
2413 | 2413 | |
|
2414 | 2414 | def mktempfile(self,data=None): |
|
2415 | 2415 | """Make a new tempfile and return its filename. |
|
2416 | 2416 | |
|
2417 | 2417 | This makes a call to tempfile.mktemp, but it registers the created |
|
2418 | 2418 | filename internally so ipython cleans it up at exit time. |
|
2419 | 2419 | |
|
2420 | 2420 | Optional inputs: |
|
2421 | 2421 | |
|
2422 | 2422 | - data(None): if data is given, it gets written out to the temp file |
|
2423 | 2423 | immediately, and the file is closed again.""" |
|
2424 | 2424 | |
|
2425 | 2425 | filename = tempfile.mktemp('.py','ipython_edit_') |
|
2426 | 2426 | self.tempfiles.append(filename) |
|
2427 | 2427 | |
|
2428 | 2428 | if data: |
|
2429 | 2429 | tmp_file = open(filename,'w') |
|
2430 | 2430 | tmp_file.write(data) |
|
2431 | 2431 | tmp_file.close() |
|
2432 | 2432 | return filename |
|
2433 | 2433 | |
|
2434 | 2434 | def write(self,data): |
|
2435 | 2435 | """Write a string to the default output""" |
|
2436 | 2436 | Term.cout.write(data) |
|
2437 | 2437 | |
|
2438 | 2438 | def write_err(self,data): |
|
2439 | 2439 | """Write a string to the default error output""" |
|
2440 | 2440 | Term.cerr.write(data) |
|
2441 | 2441 | |
|
2442 | 2442 | def ask_yes_no(self,prompt,default=True): |
|
2443 | 2443 | if self.quiet: |
|
2444 | 2444 | return True |
|
2445 | 2445 | return ask_yes_no(prompt,default) |
|
2446 | 2446 | |
|
2447 | 2447 | #------------------------------------------------------------------------- |
|
2448 | 2448 | # Things related to GUI support and pylab |
|
2449 | 2449 | #------------------------------------------------------------------------- |
|
2450 | 2450 | |
|
2451 | 2451 | def enable_pylab(self, gui=None): |
|
2452 | 2452 | """ |
|
2453 | 2453 | """ |
|
2454 | 2454 | gui = pylab_activate(self.user_ns, gui) |
|
2455 | 2455 | enable_gui(gui) |
|
2456 | 2456 | self.magic_run = self._pylab_magic_run |
|
2457 | 2457 | |
|
2458 | 2458 | |
|
2459 | 2459 | #------------------------------------------------------------------------- |
|
2460 | 2460 | # Things related to IPython exiting |
|
2461 | 2461 | #------------------------------------------------------------------------- |
|
2462 | 2462 | |
|
2463 | 2463 | def ask_exit(self): |
|
2464 |
""" |
|
|
2464 | """ Ask the shell to exit. Can be overiden and used as a callback. """ | |
|
2465 | 2465 | self.exit_now = True |
|
2466 | 2466 | |
|
2467 | 2467 | def exit(self): |
|
2468 | 2468 | """Handle interactive exit. |
|
2469 | 2469 | |
|
2470 | 2470 | This method calls the ask_exit callback.""" |
|
2471 | 2471 | if self.confirm_exit: |
|
2472 | 2472 | if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'): |
|
2473 | 2473 | self.ask_exit() |
|
2474 | 2474 | else: |
|
2475 | 2475 | self.ask_exit() |
|
2476 | 2476 | |
|
2477 | 2477 | def atexit_operations(self): |
|
2478 | 2478 | """This will be executed at the time of exit. |
|
2479 | 2479 | |
|
2480 | 2480 | Saving of persistent data should be performed here. |
|
2481 | 2481 | """ |
|
2482 | 2482 | self.savehist() |
|
2483 | 2483 | |
|
2484 | 2484 | # Cleanup all tempfiles left around |
|
2485 | 2485 | for tfile in self.tempfiles: |
|
2486 | 2486 | try: |
|
2487 | 2487 | os.unlink(tfile) |
|
2488 | 2488 | except OSError: |
|
2489 | 2489 | pass |
|
2490 | 2490 | |
|
2491 | 2491 | # Clear all user namespaces to release all references cleanly. |
|
2492 | 2492 | self.reset() |
|
2493 | 2493 | |
|
2494 | 2494 | # Run user hooks |
|
2495 | 2495 | self.hooks.shutdown_hook() |
|
2496 | 2496 | |
|
2497 | 2497 | def cleanup(self): |
|
2498 | 2498 | self.restore_sys_module_state() |
|
2499 | 2499 | |
|
2500 | 2500 |
@@ -1,3626 +1,3613 b'' | |||
|
1 | 1 | # -*- coding: utf-8 -*- |
|
2 | 2 | """Magic functions for InteractiveShell. |
|
3 | 3 | """ |
|
4 | 4 | |
|
5 | 5 | #***************************************************************************** |
|
6 | 6 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and |
|
7 | 7 | # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu> |
|
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 | # Modules and globals |
|
15 | 15 | |
|
16 | 16 | # Python standard modules |
|
17 | 17 | import __builtin__ |
|
18 | 18 | import bdb |
|
19 | 19 | import inspect |
|
20 | 20 | import os |
|
21 | 21 | import pdb |
|
22 | 22 | import pydoc |
|
23 | 23 | import sys |
|
24 | 24 | import shutil |
|
25 | 25 | import re |
|
26 | 26 | import tempfile |
|
27 | 27 | import time |
|
28 | 28 | import cPickle as pickle |
|
29 | 29 | import textwrap |
|
30 | 30 | from cStringIO import StringIO |
|
31 | 31 | from getopt import getopt,GetoptError |
|
32 | 32 | from pprint import pprint, pformat |
|
33 | 33 | |
|
34 | 34 | # cProfile was added in Python2.5 |
|
35 | 35 | try: |
|
36 | 36 | import cProfile as profile |
|
37 | 37 | import pstats |
|
38 | 38 | except ImportError: |
|
39 | 39 | # profile isn't bundled by default in Debian for license reasons |
|
40 | 40 | try: |
|
41 | 41 | import profile,pstats |
|
42 | 42 | except ImportError: |
|
43 | 43 | profile = pstats = None |
|
44 | 44 | |
|
45 | 45 | # Homebrewed |
|
46 | 46 | import IPython |
|
47 | 47 | import IPython.utils.generics |
|
48 | 48 | |
|
49 | 49 | from IPython.core import debugger, oinspect |
|
50 | 50 | from IPython.core.error import TryNext |
|
51 | 51 | from IPython.core.error import UsageError |
|
52 | 52 | from IPython.core.fakemodule import FakeModule |
|
53 | 53 | from IPython.core.macro import Macro |
|
54 | 54 | from IPython.core.page import page |
|
55 | 55 | from IPython.core.prefilter import ESC_MAGIC |
|
56 | 56 | from IPython.core.pylabtools import mpl_runner |
|
57 | 57 | from IPython.lib.inputhook import enable_gui |
|
58 | 58 | from IPython.external.Itpl import Itpl, itpl, printpl,itplns |
|
59 | 59 | from IPython.testing import decorators as testdec |
|
60 | 60 | from IPython.utils import platutils |
|
61 | 61 | from IPython.utils import wildcard |
|
62 | 62 | from IPython.utils.PyColorize import Parser |
|
63 | 63 | from IPython.utils.ipstruct import Struct |
|
64 | 64 | |
|
65 | 65 | # XXX - We need to switch to explicit imports here with genutils |
|
66 | 66 | from IPython.utils.genutils import * |
|
67 | 67 | |
|
68 | 68 | #*************************************************************************** |
|
69 | 69 | # Utility functions |
|
70 | 70 | def on_off(tag): |
|
71 | 71 | """Return an ON/OFF string for a 1/0 input. Simple utility function.""" |
|
72 | 72 | return ['OFF','ON'][tag] |
|
73 | 73 | |
|
74 | 74 | class Bunch: pass |
|
75 | 75 | |
|
76 | 76 | def compress_dhist(dh): |
|
77 | 77 | head, tail = dh[:-10], dh[-10:] |
|
78 | 78 | |
|
79 | 79 | newhead = [] |
|
80 | 80 | done = set() |
|
81 | 81 | for h in head: |
|
82 | 82 | if h in done: |
|
83 | 83 | continue |
|
84 | 84 | newhead.append(h) |
|
85 | 85 | done.add(h) |
|
86 | 86 | |
|
87 | 87 | return newhead + tail |
|
88 | 88 | |
|
89 | 89 | |
|
90 | 90 | #*************************************************************************** |
|
91 | 91 | # Main class implementing Magic functionality |
|
92 | 92 | |
|
93 | 93 | # XXX - for some odd reason, if Magic is made a new-style class, we get errors |
|
94 | 94 | # on construction of the main InteractiveShell object. Something odd is going |
|
95 | 95 | # on with super() calls, Component and the MRO... For now leave it as-is, but |
|
96 | 96 | # eventually this needs to be clarified. |
|
97 | 97 | |
|
98 | 98 | class Magic: |
|
99 | 99 | """Magic functions for InteractiveShell. |
|
100 | 100 | |
|
101 | 101 | Shell functions which can be reached as %function_name. All magic |
|
102 | 102 | functions should accept a string, which they can parse for their own |
|
103 | 103 | needs. This can make some functions easier to type, eg `%cd ../` |
|
104 | 104 | vs. `%cd("../")` |
|
105 | 105 | |
|
106 | 106 | ALL definitions MUST begin with the prefix magic_. The user won't need it |
|
107 | 107 | at the command line, but it is is needed in the definition. """ |
|
108 | 108 | |
|
109 | 109 | # class globals |
|
110 | 110 | auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.', |
|
111 | 111 | 'Automagic is ON, % prefix NOT needed for magic functions.'] |
|
112 | 112 | |
|
113 | 113 | #...................................................................... |
|
114 | 114 | # some utility functions |
|
115 | 115 | |
|
116 | 116 | def __init__(self,shell): |
|
117 | 117 | |
|
118 | 118 | self.options_table = {} |
|
119 | 119 | if profile is None: |
|
120 | 120 | self.magic_prun = self.profile_missing_notice |
|
121 | 121 | self.shell = shell |
|
122 | 122 | |
|
123 | 123 | # namespace for holding state we may need |
|
124 | 124 | self._magic_state = Bunch() |
|
125 | 125 | |
|
126 | 126 | def profile_missing_notice(self, *args, **kwargs): |
|
127 | 127 | error("""\ |
|
128 | 128 | The profile module could not be found. It has been removed from the standard |
|
129 | 129 | python packages because of its non-free license. To use profiling, install the |
|
130 | 130 | python-profiler package from non-free.""") |
|
131 | 131 | |
|
132 | 132 | def default_option(self,fn,optstr): |
|
133 | 133 | """Make an entry in the options_table for fn, with value optstr""" |
|
134 | 134 | |
|
135 | 135 | if fn not in self.lsmagic(): |
|
136 | 136 | error("%s is not a magic function" % fn) |
|
137 | 137 | self.options_table[fn] = optstr |
|
138 | 138 | |
|
139 | 139 | def lsmagic(self): |
|
140 | 140 | """Return a list of currently available magic functions. |
|
141 | 141 | |
|
142 | 142 | Gives a list of the bare names after mangling (['ls','cd', ...], not |
|
143 | 143 | ['magic_ls','magic_cd',...]""" |
|
144 | 144 | |
|
145 | 145 | # FIXME. This needs a cleanup, in the way the magics list is built. |
|
146 | 146 | |
|
147 | 147 | # magics in class definition |
|
148 | 148 | class_magic = lambda fn: fn.startswith('magic_') and \ |
|
149 | 149 | callable(Magic.__dict__[fn]) |
|
150 | 150 | # in instance namespace (run-time user additions) |
|
151 | 151 | inst_magic = lambda fn: fn.startswith('magic_') and \ |
|
152 | 152 | callable(self.__dict__[fn]) |
|
153 | 153 | # and bound magics by user (so they can access self): |
|
154 | 154 | inst_bound_magic = lambda fn: fn.startswith('magic_') and \ |
|
155 | 155 | callable(self.__class__.__dict__[fn]) |
|
156 | 156 | magics = filter(class_magic,Magic.__dict__.keys()) + \ |
|
157 | 157 | filter(inst_magic,self.__dict__.keys()) + \ |
|
158 | 158 | filter(inst_bound_magic,self.__class__.__dict__.keys()) |
|
159 | 159 | out = [] |
|
160 | 160 | for fn in set(magics): |
|
161 | 161 | out.append(fn.replace('magic_','',1)) |
|
162 | 162 | out.sort() |
|
163 | 163 | return out |
|
164 | 164 | |
|
165 | 165 | def extract_input_slices(self,slices,raw=False): |
|
166 | 166 | """Return as a string a set of input history slices. |
|
167 | 167 | |
|
168 | 168 | Inputs: |
|
169 | 169 | |
|
170 | 170 | - slices: the set of slices is given as a list of strings (like |
|
171 | 171 | ['1','4:8','9'], since this function is for use by magic functions |
|
172 | 172 | which get their arguments as strings. |
|
173 | 173 | |
|
174 | 174 | Optional inputs: |
|
175 | 175 | |
|
176 | 176 | - raw(False): by default, the processed input is used. If this is |
|
177 | 177 | true, the raw input history is used instead. |
|
178 | 178 | |
|
179 | 179 | Note that slices can be called with two notations: |
|
180 | 180 | |
|
181 | 181 | N:M -> standard python form, means including items N...(M-1). |
|
182 | 182 | |
|
183 | 183 | N-M -> include items N..M (closed endpoint).""" |
|
184 | 184 | |
|
185 | 185 | if raw: |
|
186 | 186 | hist = self.shell.input_hist_raw |
|
187 | 187 | else: |
|
188 | 188 | hist = self.shell.input_hist |
|
189 | 189 | |
|
190 | 190 | cmds = [] |
|
191 | 191 | for chunk in slices: |
|
192 | 192 | if ':' in chunk: |
|
193 | 193 | ini,fin = map(int,chunk.split(':')) |
|
194 | 194 | elif '-' in chunk: |
|
195 | 195 | ini,fin = map(int,chunk.split('-')) |
|
196 | 196 | fin += 1 |
|
197 | 197 | else: |
|
198 | 198 | ini = int(chunk) |
|
199 | 199 | fin = ini+1 |
|
200 | 200 | cmds.append(hist[ini:fin]) |
|
201 | 201 | return cmds |
|
202 | 202 | |
|
203 | 203 | def _ofind(self, oname, namespaces=None): |
|
204 | 204 | """Find an object in the available namespaces. |
|
205 | 205 | |
|
206 | 206 | self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic |
|
207 | 207 | |
|
208 | 208 | Has special code to detect magic functions. |
|
209 | 209 | """ |
|
210 | 210 | |
|
211 | 211 | oname = oname.strip() |
|
212 | 212 | |
|
213 | 213 | alias_ns = None |
|
214 | 214 | if namespaces is None: |
|
215 | 215 | # Namespaces to search in: |
|
216 | 216 | # Put them in a list. The order is important so that we |
|
217 | 217 | # find things in the same order that Python finds them. |
|
218 | 218 | namespaces = [ ('Interactive', self.shell.user_ns), |
|
219 | 219 | ('IPython internal', self.shell.internal_ns), |
|
220 | 220 | ('Python builtin', __builtin__.__dict__), |
|
221 | 221 | ('Alias', self.shell.alias_manager.alias_table), |
|
222 | 222 | ] |
|
223 | 223 | alias_ns = self.shell.alias_manager.alias_table |
|
224 | 224 | |
|
225 | 225 | # initialize results to 'null' |
|
226 | 226 | found = 0; obj = None; ospace = None; ds = None; |
|
227 | 227 | ismagic = 0; isalias = 0; parent = None |
|
228 | 228 | |
|
229 | 229 | # Look for the given name by splitting it in parts. If the head is |
|
230 | 230 | # found, then we look for all the remaining parts as members, and only |
|
231 | 231 | # declare success if we can find them all. |
|
232 | 232 | oname_parts = oname.split('.') |
|
233 | 233 | oname_head, oname_rest = oname_parts[0],oname_parts[1:] |
|
234 | 234 | for nsname,ns in namespaces: |
|
235 | 235 | try: |
|
236 | 236 | obj = ns[oname_head] |
|
237 | 237 | except KeyError: |
|
238 | 238 | continue |
|
239 | 239 | else: |
|
240 | 240 | #print 'oname_rest:', oname_rest # dbg |
|
241 | 241 | for part in oname_rest: |
|
242 | 242 | try: |
|
243 | 243 | parent = obj |
|
244 | 244 | obj = getattr(obj,part) |
|
245 | 245 | except: |
|
246 | 246 | # Blanket except b/c some badly implemented objects |
|
247 | 247 | # allow __getattr__ to raise exceptions other than |
|
248 | 248 | # AttributeError, which then crashes IPython. |
|
249 | 249 | break |
|
250 | 250 | else: |
|
251 | 251 | # If we finish the for loop (no break), we got all members |
|
252 | 252 | found = 1 |
|
253 | 253 | ospace = nsname |
|
254 | 254 | if ns == alias_ns: |
|
255 | 255 | isalias = 1 |
|
256 | 256 | break # namespace loop |
|
257 | 257 | |
|
258 | 258 | # Try to see if it's magic |
|
259 | 259 | if not found: |
|
260 | 260 | if oname.startswith(ESC_MAGIC): |
|
261 | 261 | oname = oname[1:] |
|
262 | 262 | obj = getattr(self,'magic_'+oname,None) |
|
263 | 263 | if obj is not None: |
|
264 | 264 | found = 1 |
|
265 | 265 | ospace = 'IPython internal' |
|
266 | 266 | ismagic = 1 |
|
267 | 267 | |
|
268 | 268 | # Last try: special-case some literals like '', [], {}, etc: |
|
269 | 269 | if not found and oname_head in ["''",'""','[]','{}','()']: |
|
270 | 270 | obj = eval(oname_head) |
|
271 | 271 | found = 1 |
|
272 | 272 | ospace = 'Interactive' |
|
273 | 273 | |
|
274 | 274 | return {'found':found, 'obj':obj, 'namespace':ospace, |
|
275 | 275 | 'ismagic':ismagic, 'isalias':isalias, 'parent':parent} |
|
276 | 276 | |
|
277 | 277 | def arg_err(self,func): |
|
278 | 278 | """Print docstring if incorrect arguments were passed""" |
|
279 | 279 | print 'Error in arguments:' |
|
280 | 280 | print OInspect.getdoc(func) |
|
281 | 281 | |
|
282 | 282 | def format_latex(self,strng): |
|
283 | 283 | """Format a string for latex inclusion.""" |
|
284 | 284 | |
|
285 | 285 | # Characters that need to be escaped for latex: |
|
286 | 286 | escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE) |
|
287 | 287 | # Magic command names as headers: |
|
288 | 288 | cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC, |
|
289 | 289 | re.MULTILINE) |
|
290 | 290 | # Magic commands |
|
291 | 291 | cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC, |
|
292 | 292 | re.MULTILINE) |
|
293 | 293 | # Paragraph continue |
|
294 | 294 | par_re = re.compile(r'\\$',re.MULTILINE) |
|
295 | 295 | |
|
296 | 296 | # The "\n" symbol |
|
297 | 297 | newline_re = re.compile(r'\\n') |
|
298 | 298 | |
|
299 | 299 | # Now build the string for output: |
|
300 | 300 | #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng) |
|
301 | 301 | strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:', |
|
302 | 302 | strng) |
|
303 | 303 | strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng) |
|
304 | 304 | strng = par_re.sub(r'\\\\',strng) |
|
305 | 305 | strng = escape_re.sub(r'\\\1',strng) |
|
306 | 306 | strng = newline_re.sub(r'\\textbackslash{}n',strng) |
|
307 | 307 | return strng |
|
308 | 308 | |
|
309 | 309 | def format_screen(self,strng): |
|
310 | 310 | """Format a string for screen printing. |
|
311 | 311 | |
|
312 | 312 | This removes some latex-type format codes.""" |
|
313 | 313 | # Paragraph continue |
|
314 | 314 | par_re = re.compile(r'\\$',re.MULTILINE) |
|
315 | 315 | strng = par_re.sub('',strng) |
|
316 | 316 | return strng |
|
317 | 317 | |
|
318 | 318 | def parse_options(self,arg_str,opt_str,*long_opts,**kw): |
|
319 | 319 | """Parse options passed to an argument string. |
|
320 | 320 | |
|
321 | 321 | The interface is similar to that of getopt(), but it returns back a |
|
322 | 322 | Struct with the options as keys and the stripped argument string still |
|
323 | 323 | as a string. |
|
324 | 324 | |
|
325 | 325 | arg_str is quoted as a true sys.argv vector by using shlex.split. |
|
326 | 326 | This allows us to easily expand variables, glob files, quote |
|
327 | 327 | arguments, etc. |
|
328 | 328 | |
|
329 | 329 | Options: |
|
330 | 330 | -mode: default 'string'. If given as 'list', the argument string is |
|
331 | 331 | returned as a list (split on whitespace) instead of a string. |
|
332 | 332 | |
|
333 | 333 | -list_all: put all option values in lists. Normally only options |
|
334 | 334 | appearing more than once are put in a list. |
|
335 | 335 | |
|
336 | 336 | -posix (True): whether to split the input line in POSIX mode or not, |
|
337 | 337 | as per the conventions outlined in the shlex module from the |
|
338 | 338 | standard library.""" |
|
339 | 339 | |
|
340 | 340 | # inject default options at the beginning of the input line |
|
341 | 341 | caller = sys._getframe(1).f_code.co_name.replace('magic_','') |
|
342 | 342 | arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str) |
|
343 | 343 | |
|
344 | 344 | mode = kw.get('mode','string') |
|
345 | 345 | if mode not in ['string','list']: |
|
346 | 346 | raise ValueError,'incorrect mode given: %s' % mode |
|
347 | 347 | # Get options |
|
348 | 348 | list_all = kw.get('list_all',0) |
|
349 | 349 | posix = kw.get('posix',True) |
|
350 | 350 | |
|
351 | 351 | # Check if we have more than one argument to warrant extra processing: |
|
352 | 352 | odict = {} # Dictionary with options |
|
353 | 353 | args = arg_str.split() |
|
354 | 354 | if len(args) >= 1: |
|
355 | 355 | # If the list of inputs only has 0 or 1 thing in it, there's no |
|
356 | 356 | # need to look for options |
|
357 | 357 | argv = arg_split(arg_str,posix) |
|
358 | 358 | # Do regular option processing |
|
359 | 359 | try: |
|
360 | 360 | opts,args = getopt(argv,opt_str,*long_opts) |
|
361 | 361 | except GetoptError,e: |
|
362 | 362 | raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str, |
|
363 | 363 | " ".join(long_opts))) |
|
364 | 364 | for o,a in opts: |
|
365 | 365 | if o.startswith('--'): |
|
366 | 366 | o = o[2:] |
|
367 | 367 | else: |
|
368 | 368 | o = o[1:] |
|
369 | 369 | try: |
|
370 | 370 | odict[o].append(a) |
|
371 | 371 | except AttributeError: |
|
372 | 372 | odict[o] = [odict[o],a] |
|
373 | 373 | except KeyError: |
|
374 | 374 | if list_all: |
|
375 | 375 | odict[o] = [a] |
|
376 | 376 | else: |
|
377 | 377 | odict[o] = a |
|
378 | 378 | |
|
379 | 379 | # Prepare opts,args for return |
|
380 | 380 | opts = Struct(odict) |
|
381 | 381 | if mode == 'string': |
|
382 | 382 | args = ' '.join(args) |
|
383 | 383 | |
|
384 | 384 | return opts,args |
|
385 | 385 | |
|
386 | 386 | #...................................................................... |
|
387 | 387 | # And now the actual magic functions |
|
388 | 388 | |
|
389 | 389 | # Functions for IPython shell work (vars,funcs, config, etc) |
|
390 | 390 | def magic_lsmagic(self, parameter_s = ''): |
|
391 | 391 | """List currently available magic functions.""" |
|
392 | 392 | mesc = ESC_MAGIC |
|
393 | 393 | print 'Available magic functions:\n'+mesc+\ |
|
394 | 394 | (' '+mesc).join(self.lsmagic()) |
|
395 | 395 | print '\n' + Magic.auto_status[self.shell.automagic] |
|
396 | 396 | return None |
|
397 | 397 | |
|
398 | 398 | def magic_magic(self, parameter_s = ''): |
|
399 | 399 | """Print information about the magic function system. |
|
400 | 400 | |
|
401 | 401 | Supported formats: -latex, -brief, -rest |
|
402 | 402 | """ |
|
403 | 403 | |
|
404 | 404 | mode = '' |
|
405 | 405 | try: |
|
406 | 406 | if parameter_s.split()[0] == '-latex': |
|
407 | 407 | mode = 'latex' |
|
408 | 408 | if parameter_s.split()[0] == '-brief': |
|
409 | 409 | mode = 'brief' |
|
410 | 410 | if parameter_s.split()[0] == '-rest': |
|
411 | 411 | mode = 'rest' |
|
412 | 412 | rest_docs = [] |
|
413 | 413 | except: |
|
414 | 414 | pass |
|
415 | 415 | |
|
416 | 416 | magic_docs = [] |
|
417 | 417 | for fname in self.lsmagic(): |
|
418 | 418 | mname = 'magic_' + fname |
|
419 | 419 | for space in (Magic,self,self.__class__): |
|
420 | 420 | try: |
|
421 | 421 | fn = space.__dict__[mname] |
|
422 | 422 | except KeyError: |
|
423 | 423 | pass |
|
424 | 424 | else: |
|
425 | 425 | break |
|
426 | 426 | if mode == 'brief': |
|
427 | 427 | # only first line |
|
428 | 428 | if fn.__doc__: |
|
429 | 429 | fndoc = fn.__doc__.split('\n',1)[0] |
|
430 | 430 | else: |
|
431 | 431 | fndoc = 'No documentation' |
|
432 | 432 | else: |
|
433 | 433 | if fn.__doc__: |
|
434 | 434 | fndoc = fn.__doc__.rstrip() |
|
435 | 435 | else: |
|
436 | 436 | fndoc = 'No documentation' |
|
437 | 437 | |
|
438 | 438 | |
|
439 | 439 | if mode == 'rest': |
|
440 | 440 | rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(ESC_MAGIC, |
|
441 | 441 | fname,fndoc)) |
|
442 | 442 | |
|
443 | 443 | else: |
|
444 | 444 | magic_docs.append('%s%s:\n\t%s\n' %(ESC_MAGIC, |
|
445 | 445 | fname,fndoc)) |
|
446 | 446 | |
|
447 | 447 | magic_docs = ''.join(magic_docs) |
|
448 | 448 | |
|
449 | 449 | if mode == 'rest': |
|
450 | 450 | return "".join(rest_docs) |
|
451 | 451 | |
|
452 | 452 | if mode == 'latex': |
|
453 | 453 | print self.format_latex(magic_docs) |
|
454 | 454 | return |
|
455 | 455 | else: |
|
456 | 456 | magic_docs = self.format_screen(magic_docs) |
|
457 | 457 | if mode == 'brief': |
|
458 | 458 | return magic_docs |
|
459 | 459 | |
|
460 | 460 | outmsg = """ |
|
461 | 461 | IPython's 'magic' functions |
|
462 | 462 | =========================== |
|
463 | 463 | |
|
464 | 464 | The magic function system provides a series of functions which allow you to |
|
465 | 465 | control the behavior of IPython itself, plus a lot of system-type |
|
466 | 466 | features. All these functions are prefixed with a % character, but parameters |
|
467 | 467 | are given without parentheses or quotes. |
|
468 | 468 | |
|
469 | 469 | NOTE: If you have 'automagic' enabled (via the command line option or with the |
|
470 | 470 | %automagic function), you don't need to type in the % explicitly. By default, |
|
471 | 471 | IPython ships with automagic on, so you should only rarely need the % escape. |
|
472 | 472 | |
|
473 | 473 | Example: typing '%cd mydir' (without the quotes) changes you working directory |
|
474 | 474 | to 'mydir', if it exists. |
|
475 | 475 | |
|
476 | 476 | You can define your own magic functions to extend the system. See the supplied |
|
477 | 477 | ipythonrc and example-magic.py files for details (in your ipython |
|
478 | 478 | configuration directory, typically $HOME/.ipython/). |
|
479 | 479 | |
|
480 | 480 | You can also define your own aliased names for magic functions. In your |
|
481 | 481 | ipythonrc file, placing a line like: |
|
482 | 482 | |
|
483 | 483 | execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile |
|
484 | 484 | |
|
485 | 485 | will define %pf as a new name for %profile. |
|
486 | 486 | |
|
487 | 487 | You can also call magics in code using the magic() function, which IPython |
|
488 | 488 | automatically adds to the builtin namespace. Type 'magic?' for details. |
|
489 | 489 | |
|
490 | 490 | For a list of the available magic functions, use %lsmagic. For a description |
|
491 | 491 | of any of them, type %magic_name?, e.g. '%cd?'. |
|
492 | 492 | |
|
493 | 493 | Currently the magic system has the following functions:\n""" |
|
494 | 494 | |
|
495 | 495 | mesc = ESC_MAGIC |
|
496 | 496 | outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):" |
|
497 | 497 | "\n\n%s%s\n\n%s" % (outmsg, |
|
498 | 498 | magic_docs,mesc,mesc, |
|
499 | 499 | (' '+mesc).join(self.lsmagic()), |
|
500 | 500 | Magic.auto_status[self.shell.automagic] ) ) |
|
501 | 501 | |
|
502 | 502 | page(outmsg,screen_lines=self.shell.usable_screen_length) |
|
503 | 503 | |
|
504 | 504 | |
|
505 | 505 | def magic_autoindent(self, parameter_s = ''): |
|
506 | 506 | """Toggle autoindent on/off (if available).""" |
|
507 | 507 | |
|
508 | 508 | self.shell.set_autoindent() |
|
509 | 509 | print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent] |
|
510 | 510 | |
|
511 | 511 | |
|
512 | 512 | def magic_automagic(self, parameter_s = ''): |
|
513 | 513 | """Make magic functions callable without having to type the initial %. |
|
514 | 514 | |
|
515 | 515 | Without argumentsl toggles on/off (when off, you must call it as |
|
516 | 516 | %automagic, of course). With arguments it sets the value, and you can |
|
517 | 517 | use any of (case insensitive): |
|
518 | 518 | |
|
519 | 519 | - on,1,True: to activate |
|
520 | 520 | |
|
521 | 521 | - off,0,False: to deactivate. |
|
522 | 522 | |
|
523 | 523 | Note that magic functions have lowest priority, so if there's a |
|
524 | 524 | variable whose name collides with that of a magic fn, automagic won't |
|
525 | 525 | work for that function (you get the variable instead). However, if you |
|
526 | 526 | delete the variable (del var), the previously shadowed magic function |
|
527 | 527 | becomes visible to automagic again.""" |
|
528 | 528 | |
|
529 | 529 | arg = parameter_s.lower() |
|
530 | 530 | if parameter_s in ('on','1','true'): |
|
531 | 531 | self.shell.automagic = True |
|
532 | 532 | elif parameter_s in ('off','0','false'): |
|
533 | 533 | self.shell.automagic = False |
|
534 | 534 | else: |
|
535 | 535 | self.shell.automagic = not self.shell.automagic |
|
536 | 536 | print '\n' + Magic.auto_status[self.shell.automagic] |
|
537 | 537 | |
|
538 | 538 | @testdec.skip_doctest |
|
539 | 539 | def magic_autocall(self, parameter_s = ''): |
|
540 | 540 | """Make functions callable without having to type parentheses. |
|
541 | 541 | |
|
542 | 542 | Usage: |
|
543 | 543 | |
|
544 | 544 | %autocall [mode] |
|
545 | 545 | |
|
546 | 546 | The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the |
|
547 | 547 | value is toggled on and off (remembering the previous state). |
|
548 | 548 | |
|
549 | 549 | In more detail, these values mean: |
|
550 | 550 | |
|
551 | 551 | 0 -> fully disabled |
|
552 | 552 | |
|
553 | 553 | 1 -> active, but do not apply if there are no arguments on the line. |
|
554 | 554 | |
|
555 | 555 | In this mode, you get: |
|
556 | 556 | |
|
557 | 557 | In [1]: callable |
|
558 | 558 | Out[1]: <built-in function callable> |
|
559 | 559 | |
|
560 | 560 | In [2]: callable 'hello' |
|
561 | 561 | ------> callable('hello') |
|
562 | 562 | Out[2]: False |
|
563 | 563 | |
|
564 | 564 | 2 -> Active always. Even if no arguments are present, the callable |
|
565 | 565 | object is called: |
|
566 | 566 | |
|
567 | 567 | In [2]: float |
|
568 | 568 | ------> float() |
|
569 | 569 | Out[2]: 0.0 |
|
570 | 570 | |
|
571 | 571 | Note that even with autocall off, you can still use '/' at the start of |
|
572 | 572 | a line to treat the first argument on the command line as a function |
|
573 | 573 | and add parentheses to it: |
|
574 | 574 | |
|
575 | 575 | In [8]: /str 43 |
|
576 | 576 | ------> str(43) |
|
577 | 577 | Out[8]: '43' |
|
578 | 578 | |
|
579 | 579 | # all-random (note for auto-testing) |
|
580 | 580 | """ |
|
581 | 581 | |
|
582 | 582 | if parameter_s: |
|
583 | 583 | arg = int(parameter_s) |
|
584 | 584 | else: |
|
585 | 585 | arg = 'toggle' |
|
586 | 586 | |
|
587 | 587 | if not arg in (0,1,2,'toggle'): |
|
588 | 588 | error('Valid modes: (0->Off, 1->Smart, 2->Full') |
|
589 | 589 | return |
|
590 | 590 | |
|
591 | 591 | if arg in (0,1,2): |
|
592 | 592 | self.shell.autocall = arg |
|
593 | 593 | else: # toggle |
|
594 | 594 | if self.shell.autocall: |
|
595 | 595 | self._magic_state.autocall_save = self.shell.autocall |
|
596 | 596 | self.shell.autocall = 0 |
|
597 | 597 | else: |
|
598 | 598 | try: |
|
599 | 599 | self.shell.autocall = self._magic_state.autocall_save |
|
600 | 600 | except AttributeError: |
|
601 | 601 | self.shell.autocall = self._magic_state.autocall_save = 1 |
|
602 | 602 | |
|
603 | 603 | print "Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall] |
|
604 | 604 | |
|
605 | 605 | def magic_system_verbose(self, parameter_s = ''): |
|
606 | 606 | """Set verbose printing of system calls. |
|
607 | 607 | |
|
608 | 608 | If called without an argument, act as a toggle""" |
|
609 | 609 | |
|
610 | 610 | if parameter_s: |
|
611 | 611 | val = bool(eval(parameter_s)) |
|
612 | 612 | else: |
|
613 | 613 | val = None |
|
614 | 614 | |
|
615 | 615 | if self.shell.system_verbose: |
|
616 | 616 | self.shell.system_verbose = False |
|
617 | 617 | else: |
|
618 | 618 | self.shell.system_verbose = True |
|
619 | 619 | print "System verbose printing is:",\ |
|
620 | 620 | ['OFF','ON'][self.shell.system_verbose] |
|
621 | 621 | |
|
622 | 622 | |
|
623 | 623 | def magic_page(self, parameter_s=''): |
|
624 | 624 | """Pretty print the object and display it through a pager. |
|
625 | 625 | |
|
626 | 626 | %page [options] OBJECT |
|
627 | 627 | |
|
628 | 628 | If no object is given, use _ (last output). |
|
629 | 629 | |
|
630 | 630 | Options: |
|
631 | 631 | |
|
632 | 632 | -r: page str(object), don't pretty-print it.""" |
|
633 | 633 | |
|
634 | 634 | # After a function contributed by Olivier Aubert, slightly modified. |
|
635 | 635 | |
|
636 | 636 | # Process options/args |
|
637 | 637 | opts,args = self.parse_options(parameter_s,'r') |
|
638 | 638 | raw = 'r' in opts |
|
639 | 639 | |
|
640 | 640 | oname = args and args or '_' |
|
641 | 641 | info = self._ofind(oname) |
|
642 | 642 | if info['found']: |
|
643 | 643 | txt = (raw and str or pformat)( info['obj'] ) |
|
644 | 644 | page(txt) |
|
645 | 645 | else: |
|
646 | 646 | print 'Object `%s` not found' % oname |
|
647 | 647 | |
|
648 | 648 | def magic_profile(self, parameter_s=''): |
|
649 | 649 | """Print your currently active IPyhton profile.""" |
|
650 | 650 | if self.shell.profile: |
|
651 | 651 | printpl('Current IPython profile: $self.shell.profile.') |
|
652 | 652 | else: |
|
653 | 653 | print 'No profile active.' |
|
654 | 654 | |
|
655 | 655 | def magic_pinfo(self, parameter_s='', namespaces=None): |
|
656 | 656 | """Provide detailed information about an object. |
|
657 | 657 | |
|
658 | 658 | '%pinfo object' is just a synonym for object? or ?object.""" |
|
659 | 659 | |
|
660 | 660 | #print 'pinfo par: <%s>' % parameter_s # dbg |
|
661 | 661 | |
|
662 | 662 | |
|
663 | 663 | # detail_level: 0 -> obj? , 1 -> obj?? |
|
664 | 664 | detail_level = 0 |
|
665 | 665 | # We need to detect if we got called as 'pinfo pinfo foo', which can |
|
666 | 666 | # happen if the user types 'pinfo foo?' at the cmd line. |
|
667 | 667 | pinfo,qmark1,oname,qmark2 = \ |
|
668 | 668 | re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups() |
|
669 | 669 | if pinfo or qmark1 or qmark2: |
|
670 | 670 | detail_level = 1 |
|
671 | 671 | if "*" in oname: |
|
672 | 672 | self.magic_psearch(oname) |
|
673 | 673 | else: |
|
674 | 674 | self._inspect('pinfo', oname, detail_level=detail_level, |
|
675 | 675 | namespaces=namespaces) |
|
676 | 676 | |
|
677 | 677 | def magic_pdef(self, parameter_s='', namespaces=None): |
|
678 | 678 | """Print the definition header for any callable object. |
|
679 | 679 | |
|
680 | 680 | If the object is a class, print the constructor information.""" |
|
681 | 681 | self._inspect('pdef',parameter_s, namespaces) |
|
682 | 682 | |
|
683 | 683 | def magic_pdoc(self, parameter_s='', namespaces=None): |
|
684 | 684 | """Print the docstring for an object. |
|
685 | 685 | |
|
686 | 686 | If the given object is a class, it will print both the class and the |
|
687 | 687 | constructor docstrings.""" |
|
688 | 688 | self._inspect('pdoc',parameter_s, namespaces) |
|
689 | 689 | |
|
690 | 690 | def magic_psource(self, parameter_s='', namespaces=None): |
|
691 | 691 | """Print (or run through pager) the source code for an object.""" |
|
692 | 692 | self._inspect('psource',parameter_s, namespaces) |
|
693 | 693 | |
|
694 | 694 | def magic_pfile(self, parameter_s=''): |
|
695 | 695 | """Print (or run through pager) the file where an object is defined. |
|
696 | 696 | |
|
697 | 697 | The file opens at the line where the object definition begins. IPython |
|
698 | 698 | will honor the environment variable PAGER if set, and otherwise will |
|
699 | 699 | do its best to print the file in a convenient form. |
|
700 | 700 | |
|
701 | 701 | If the given argument is not an object currently defined, IPython will |
|
702 | 702 | try to interpret it as a filename (automatically adding a .py extension |
|
703 | 703 | if needed). You can thus use %pfile as a syntax highlighting code |
|
704 | 704 | viewer.""" |
|
705 | 705 | |
|
706 | 706 | # first interpret argument as an object name |
|
707 | 707 | out = self._inspect('pfile',parameter_s) |
|
708 | 708 | # if not, try the input as a filename |
|
709 | 709 | if out == 'not found': |
|
710 | 710 | try: |
|
711 | 711 | filename = get_py_filename(parameter_s) |
|
712 | 712 | except IOError,msg: |
|
713 | 713 | print msg |
|
714 | 714 | return |
|
715 | 715 | page(self.shell.inspector.format(file(filename).read())) |
|
716 | 716 | |
|
717 | 717 | def _inspect(self,meth,oname,namespaces=None,**kw): |
|
718 | 718 | """Generic interface to the inspector system. |
|
719 | 719 | |
|
720 | 720 | This function is meant to be called by pdef, pdoc & friends.""" |
|
721 | 721 | |
|
722 | 722 | #oname = oname.strip() |
|
723 | 723 | #print '1- oname: <%r>' % oname # dbg |
|
724 | 724 | try: |
|
725 | 725 | oname = oname.strip().encode('ascii') |
|
726 | 726 | #print '2- oname: <%r>' % oname # dbg |
|
727 | 727 | except UnicodeEncodeError: |
|
728 | 728 | print 'Python identifiers can only contain ascii characters.' |
|
729 | 729 | return 'not found' |
|
730 | 730 | |
|
731 | 731 | info = Struct(self._ofind(oname, namespaces)) |
|
732 | 732 | |
|
733 | 733 | if info.found: |
|
734 | 734 | try: |
|
735 | 735 | IPython.utils.generics.inspect_object(info.obj) |
|
736 | 736 | return |
|
737 | 737 | except TryNext: |
|
738 | 738 | pass |
|
739 | 739 | # Get the docstring of the class property if it exists. |
|
740 | 740 | path = oname.split('.') |
|
741 | 741 | root = '.'.join(path[:-1]) |
|
742 | 742 | if info.parent is not None: |
|
743 | 743 | try: |
|
744 | 744 | target = getattr(info.parent, '__class__') |
|
745 | 745 | # The object belongs to a class instance. |
|
746 | 746 | try: |
|
747 | 747 | target = getattr(target, path[-1]) |
|
748 | 748 | # The class defines the object. |
|
749 | 749 | if isinstance(target, property): |
|
750 | 750 | oname = root + '.__class__.' + path[-1] |
|
751 | 751 | info = Struct(self._ofind(oname)) |
|
752 | 752 | except AttributeError: pass |
|
753 | 753 | except AttributeError: pass |
|
754 | 754 | |
|
755 | 755 | pmethod = getattr(self.shell.inspector,meth) |
|
756 | 756 | formatter = info.ismagic and self.format_screen or None |
|
757 | 757 | if meth == 'pdoc': |
|
758 | 758 | pmethod(info.obj,oname,formatter) |
|
759 | 759 | elif meth == 'pinfo': |
|
760 | 760 | pmethod(info.obj,oname,formatter,info,**kw) |
|
761 | 761 | else: |
|
762 | 762 | pmethod(info.obj,oname) |
|
763 | 763 | else: |
|
764 | 764 | print 'Object `%s` not found.' % oname |
|
765 | 765 | return 'not found' # so callers can take other action |
|
766 | 766 | |
|
767 | 767 | def magic_psearch(self, parameter_s=''): |
|
768 | 768 | """Search for object in namespaces by wildcard. |
|
769 | 769 | |
|
770 | 770 | %psearch [options] PATTERN [OBJECT TYPE] |
|
771 | 771 | |
|
772 | 772 | Note: ? can be used as a synonym for %psearch, at the beginning or at |
|
773 | 773 | the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the |
|
774 | 774 | rest of the command line must be unchanged (options come first), so |
|
775 | 775 | for example the following forms are equivalent |
|
776 | 776 | |
|
777 | 777 | %psearch -i a* function |
|
778 | 778 | -i a* function? |
|
779 | 779 | ?-i a* function |
|
780 | 780 | |
|
781 | 781 | Arguments: |
|
782 | 782 | |
|
783 | 783 | PATTERN |
|
784 | 784 | |
|
785 | 785 | where PATTERN is a string containing * as a wildcard similar to its |
|
786 | 786 | use in a shell. The pattern is matched in all namespaces on the |
|
787 | 787 | search path. By default objects starting with a single _ are not |
|
788 | 788 | matched, many IPython generated objects have a single |
|
789 | 789 | underscore. The default is case insensitive matching. Matching is |
|
790 | 790 | also done on the attributes of objects and not only on the objects |
|
791 | 791 | in a module. |
|
792 | 792 | |
|
793 | 793 | [OBJECT TYPE] |
|
794 | 794 | |
|
795 | 795 | Is the name of a python type from the types module. The name is |
|
796 | 796 | given in lowercase without the ending type, ex. StringType is |
|
797 | 797 | written string. By adding a type here only objects matching the |
|
798 | 798 | given type are matched. Using all here makes the pattern match all |
|
799 | 799 | types (this is the default). |
|
800 | 800 | |
|
801 | 801 | Options: |
|
802 | 802 | |
|
803 | 803 | -a: makes the pattern match even objects whose names start with a |
|
804 | 804 | single underscore. These names are normally ommitted from the |
|
805 | 805 | search. |
|
806 | 806 | |
|
807 | 807 | -i/-c: make the pattern case insensitive/sensitive. If neither of |
|
808 | 808 | these options is given, the default is read from your ipythonrc |
|
809 | 809 | file. The option name which sets this value is |
|
810 | 810 | 'wildcards_case_sensitive'. If this option is not specified in your |
|
811 | 811 | ipythonrc file, IPython's internal default is to do a case sensitive |
|
812 | 812 | search. |
|
813 | 813 | |
|
814 | 814 | -e/-s NAMESPACE: exclude/search a given namespace. The pattern you |
|
815 | 815 | specifiy can be searched in any of the following namespaces: |
|
816 | 816 | 'builtin', 'user', 'user_global','internal', 'alias', where |
|
817 | 817 | 'builtin' and 'user' are the search defaults. Note that you should |
|
818 | 818 | not use quotes when specifying namespaces. |
|
819 | 819 | |
|
820 | 820 | 'Builtin' contains the python module builtin, 'user' contains all |
|
821 | 821 | user data, 'alias' only contain the shell aliases and no python |
|
822 | 822 | objects, 'internal' contains objects used by IPython. The |
|
823 | 823 | 'user_global' namespace is only used by embedded IPython instances, |
|
824 | 824 | and it contains module-level globals. You can add namespaces to the |
|
825 | 825 | search with -s or exclude them with -e (these options can be given |
|
826 | 826 | more than once). |
|
827 | 827 | |
|
828 | 828 | Examples: |
|
829 | 829 | |
|
830 | 830 | %psearch a* -> objects beginning with an a |
|
831 | 831 | %psearch -e builtin a* -> objects NOT in the builtin space starting in a |
|
832 | 832 | %psearch a* function -> all functions beginning with an a |
|
833 | 833 | %psearch re.e* -> objects beginning with an e in module re |
|
834 | 834 | %psearch r*.e* -> objects that start with e in modules starting in r |
|
835 | 835 | %psearch r*.* string -> all strings in modules beginning with r |
|
836 | 836 | |
|
837 | 837 | Case sensitve search: |
|
838 | 838 | |
|
839 | 839 | %psearch -c a* list all object beginning with lower case a |
|
840 | 840 | |
|
841 | 841 | Show objects beginning with a single _: |
|
842 | 842 | |
|
843 | 843 | %psearch -a _* list objects beginning with a single underscore""" |
|
844 | 844 | try: |
|
845 | 845 | parameter_s = parameter_s.encode('ascii') |
|
846 | 846 | except UnicodeEncodeError: |
|
847 | 847 | print 'Python identifiers can only contain ascii characters.' |
|
848 | 848 | return |
|
849 | 849 | |
|
850 | 850 | # default namespaces to be searched |
|
851 | 851 | def_search = ['user','builtin'] |
|
852 | 852 | |
|
853 | 853 | # Process options/args |
|
854 | 854 | opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True) |
|
855 | 855 | opt = opts.get |
|
856 | 856 | shell = self.shell |
|
857 | 857 | psearch = shell.inspector.psearch |
|
858 | 858 | |
|
859 | 859 | # select case options |
|
860 | 860 | if opts.has_key('i'): |
|
861 | 861 | ignore_case = True |
|
862 | 862 | elif opts.has_key('c'): |
|
863 | 863 | ignore_case = False |
|
864 | 864 | else: |
|
865 | 865 | ignore_case = not shell.wildcards_case_sensitive |
|
866 | 866 | |
|
867 | 867 | # Build list of namespaces to search from user options |
|
868 | 868 | def_search.extend(opt('s',[])) |
|
869 | 869 | ns_exclude = ns_exclude=opt('e',[]) |
|
870 | 870 | ns_search = [nm for nm in def_search if nm not in ns_exclude] |
|
871 | 871 | |
|
872 | 872 | # Call the actual search |
|
873 | 873 | try: |
|
874 | 874 | psearch(args,shell.ns_table,ns_search, |
|
875 | 875 | show_all=opt('a'),ignore_case=ignore_case) |
|
876 | 876 | except: |
|
877 | 877 | shell.showtraceback() |
|
878 | 878 | |
|
879 | 879 | def magic_who_ls(self, parameter_s=''): |
|
880 | 880 | """Return a sorted list of all interactive variables. |
|
881 | 881 | |
|
882 | 882 | If arguments are given, only variables of types matching these |
|
883 | 883 | arguments are returned.""" |
|
884 | 884 | |
|
885 | 885 | user_ns = self.shell.user_ns |
|
886 | 886 | internal_ns = self.shell.internal_ns |
|
887 | 887 | user_config_ns = self.shell.user_config_ns |
|
888 | 888 | out = [] |
|
889 | 889 | typelist = parameter_s.split() |
|
890 | 890 | |
|
891 | 891 | for i in user_ns: |
|
892 | 892 | if not (i.startswith('_') or i.startswith('_i')) \ |
|
893 | 893 | and not (i in internal_ns or i in user_config_ns): |
|
894 | 894 | if typelist: |
|
895 | 895 | if type(user_ns[i]).__name__ in typelist: |
|
896 | 896 | out.append(i) |
|
897 | 897 | else: |
|
898 | 898 | out.append(i) |
|
899 | 899 | out.sort() |
|
900 | 900 | return out |
|
901 | 901 | |
|
902 | 902 | def magic_who(self, parameter_s=''): |
|
903 | 903 | """Print all interactive variables, with some minimal formatting. |
|
904 | 904 | |
|
905 | 905 | If any arguments are given, only variables whose type matches one of |
|
906 | 906 | these are printed. For example: |
|
907 | 907 | |
|
908 | 908 | %who function str |
|
909 | 909 | |
|
910 | 910 | will only list functions and strings, excluding all other types of |
|
911 | 911 | variables. To find the proper type names, simply use type(var) at a |
|
912 | 912 | command line to see how python prints type names. For example: |
|
913 | 913 | |
|
914 | 914 | In [1]: type('hello')\\ |
|
915 | 915 | Out[1]: <type 'str'> |
|
916 | 916 | |
|
917 | 917 | indicates that the type name for strings is 'str'. |
|
918 | 918 | |
|
919 | 919 | %who always excludes executed names loaded through your configuration |
|
920 | 920 | file and things which are internal to IPython. |
|
921 | 921 | |
|
922 | 922 | This is deliberate, as typically you may load many modules and the |
|
923 | 923 | purpose of %who is to show you only what you've manually defined.""" |
|
924 | 924 | |
|
925 | 925 | varlist = self.magic_who_ls(parameter_s) |
|
926 | 926 | if not varlist: |
|
927 | 927 | if parameter_s: |
|
928 | 928 | print 'No variables match your requested type.' |
|
929 | 929 | else: |
|
930 | 930 | print 'Interactive namespace is empty.' |
|
931 | 931 | return |
|
932 | 932 | |
|
933 | 933 | # if we have variables, move on... |
|
934 | 934 | count = 0 |
|
935 | 935 | for i in varlist: |
|
936 | 936 | print i+'\t', |
|
937 | 937 | count += 1 |
|
938 | 938 | if count > 8: |
|
939 | 939 | count = 0 |
|
940 | 940 | |
|
941 | 941 | |
|
942 | 942 | |
|
943 | 943 | def magic_whos(self, parameter_s=''): |
|
944 | 944 | """Like %who, but gives some extra information about each variable. |
|
945 | 945 | |
|
946 | 946 | The same type filtering of %who can be applied here. |
|
947 | 947 | |
|
948 | 948 | For all variables, the type is printed. Additionally it prints: |
|
949 | 949 | |
|
950 | 950 | - For {},[],(): their length. |
|
951 | 951 | |
|
952 | 952 | - For numpy and Numeric arrays, a summary with shape, number of |
|
953 | 953 | elements, typecode and size in memory. |
|
954 | 954 | |
|
955 | 955 | - Everything else: a string representation, snipping their middle if |
|
956 | 956 | too long.""" |
|
957 | 957 | |
|
958 | 958 | varnames = self.magic_who_ls(parameter_s) |
|
959 | 959 | if not varnames: |
|
960 | 960 | if parameter_s: |
|
961 | 961 | print 'No variables match your requested type.' |
|
962 | 962 | else: |
|
963 | 963 | print 'Interactive namespace is empty.' |
|
964 | 964 | return |
|
965 | 965 | |
|
966 | 966 | # if we have variables, move on... |
|
967 | 967 | |
|
968 | 968 | # for these types, show len() instead of data: |
|
969 | 969 | seq_types = [types.DictType,types.ListType,types.TupleType] |
|
970 | 970 | |
|
971 | 971 | # for numpy/Numeric arrays, display summary info |
|
972 | 972 | try: |
|
973 | 973 | import numpy |
|
974 | 974 | except ImportError: |
|
975 | 975 | ndarray_type = None |
|
976 | 976 | else: |
|
977 | 977 | ndarray_type = numpy.ndarray.__name__ |
|
978 | 978 | try: |
|
979 | 979 | import Numeric |
|
980 | 980 | except ImportError: |
|
981 | 981 | array_type = None |
|
982 | 982 | else: |
|
983 | 983 | array_type = Numeric.ArrayType.__name__ |
|
984 | 984 | |
|
985 | 985 | # Find all variable names and types so we can figure out column sizes |
|
986 | 986 | def get_vars(i): |
|
987 | 987 | return self.shell.user_ns[i] |
|
988 | 988 | |
|
989 | 989 | # some types are well known and can be shorter |
|
990 | 990 | abbrevs = {'IPython.core.macro.Macro' : 'Macro'} |
|
991 | 991 | def type_name(v): |
|
992 | 992 | tn = type(v).__name__ |
|
993 | 993 | return abbrevs.get(tn,tn) |
|
994 | 994 | |
|
995 | 995 | varlist = map(get_vars,varnames) |
|
996 | 996 | |
|
997 | 997 | typelist = [] |
|
998 | 998 | for vv in varlist: |
|
999 | 999 | tt = type_name(vv) |
|
1000 | 1000 | |
|
1001 | 1001 | if tt=='instance': |
|
1002 | 1002 | typelist.append( abbrevs.get(str(vv.__class__), |
|
1003 | 1003 | str(vv.__class__))) |
|
1004 | 1004 | else: |
|
1005 | 1005 | typelist.append(tt) |
|
1006 | 1006 | |
|
1007 | 1007 | # column labels and # of spaces as separator |
|
1008 | 1008 | varlabel = 'Variable' |
|
1009 | 1009 | typelabel = 'Type' |
|
1010 | 1010 | datalabel = 'Data/Info' |
|
1011 | 1011 | colsep = 3 |
|
1012 | 1012 | # variable format strings |
|
1013 | 1013 | vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)" |
|
1014 | 1014 | vfmt_short = '$vstr[:25]<...>$vstr[-25:]' |
|
1015 | 1015 | aformat = "%s: %s elems, type `%s`, %s bytes" |
|
1016 | 1016 | # find the size of the columns to format the output nicely |
|
1017 | 1017 | varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep |
|
1018 | 1018 | typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep |
|
1019 | 1019 | # table header |
|
1020 | 1020 | print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \ |
|
1021 | 1021 | ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1) |
|
1022 | 1022 | # and the table itself |
|
1023 | 1023 | kb = 1024 |
|
1024 | 1024 | Mb = 1048576 # kb**2 |
|
1025 | 1025 | for vname,var,vtype in zip(varnames,varlist,typelist): |
|
1026 | 1026 | print itpl(vformat), |
|
1027 | 1027 | if vtype in seq_types: |
|
1028 | 1028 | print len(var) |
|
1029 | 1029 | elif vtype in [array_type,ndarray_type]: |
|
1030 | 1030 | vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1] |
|
1031 | 1031 | if vtype==ndarray_type: |
|
1032 | 1032 | # numpy |
|
1033 | 1033 | vsize = var.size |
|
1034 | 1034 | vbytes = vsize*var.itemsize |
|
1035 | 1035 | vdtype = var.dtype |
|
1036 | 1036 | else: |
|
1037 | 1037 | # Numeric |
|
1038 | 1038 | vsize = Numeric.size(var) |
|
1039 | 1039 | vbytes = vsize*var.itemsize() |
|
1040 | 1040 | vdtype = var.typecode() |
|
1041 | 1041 | |
|
1042 | 1042 | if vbytes < 100000: |
|
1043 | 1043 | print aformat % (vshape,vsize,vdtype,vbytes) |
|
1044 | 1044 | else: |
|
1045 | 1045 | print aformat % (vshape,vsize,vdtype,vbytes), |
|
1046 | 1046 | if vbytes < Mb: |
|
1047 | 1047 | print '(%s kb)' % (vbytes/kb,) |
|
1048 | 1048 | else: |
|
1049 | 1049 | print '(%s Mb)' % (vbytes/Mb,) |
|
1050 | 1050 | else: |
|
1051 | 1051 | try: |
|
1052 | 1052 | vstr = str(var) |
|
1053 | 1053 | except UnicodeEncodeError: |
|
1054 | 1054 | vstr = unicode(var).encode(sys.getdefaultencoding(), |
|
1055 | 1055 | 'backslashreplace') |
|
1056 | 1056 | vstr = vstr.replace('\n','\\n') |
|
1057 | 1057 | if len(vstr) < 50: |
|
1058 | 1058 | print vstr |
|
1059 | 1059 | else: |
|
1060 | 1060 | printpl(vfmt_short) |
|
1061 | 1061 | |
|
1062 | 1062 | def magic_reset(self, parameter_s=''): |
|
1063 | 1063 | """Resets the namespace by removing all names defined by the user. |
|
1064 | 1064 | |
|
1065 | 1065 | Input/Output history are left around in case you need them. |
|
1066 | 1066 | |
|
1067 | 1067 | Parameters |
|
1068 | 1068 | ---------- |
|
1069 | 1069 | -y : force reset without asking for confirmation. |
|
1070 | 1070 | |
|
1071 | 1071 | Examples |
|
1072 | 1072 | -------- |
|
1073 | 1073 | In [6]: a = 1 |
|
1074 | 1074 | |
|
1075 | 1075 | In [7]: a |
|
1076 | 1076 | Out[7]: 1 |
|
1077 | 1077 | |
|
1078 | 1078 | In [8]: 'a' in _ip.user_ns |
|
1079 | 1079 | Out[8]: True |
|
1080 | 1080 | |
|
1081 | 1081 | In [9]: %reset -f |
|
1082 | 1082 | |
|
1083 | 1083 | In [10]: 'a' in _ip.user_ns |
|
1084 | 1084 | Out[10]: False |
|
1085 | 1085 | """ |
|
1086 | 1086 | |
|
1087 | 1087 | if parameter_s == '-f': |
|
1088 | 1088 | ans = True |
|
1089 | 1089 | else: |
|
1090 | 1090 | ans = self.shell.ask_yes_no( |
|
1091 | 1091 | "Once deleted, variables cannot be recovered. Proceed (y/[n])? ") |
|
1092 | 1092 | if not ans: |
|
1093 | 1093 | print 'Nothing done.' |
|
1094 | 1094 | return |
|
1095 | 1095 | user_ns = self.shell.user_ns |
|
1096 | 1096 | for i in self.magic_who_ls(): |
|
1097 | 1097 | del(user_ns[i]) |
|
1098 | 1098 | |
|
1099 | 1099 | # Also flush the private list of module references kept for script |
|
1100 | 1100 | # execution protection |
|
1101 | 1101 | self.shell.clear_main_mod_cache() |
|
1102 | 1102 | |
|
1103 | 1103 | def magic_logstart(self,parameter_s=''): |
|
1104 | 1104 | """Start logging anywhere in a session. |
|
1105 | 1105 | |
|
1106 | 1106 | %logstart [-o|-r|-t] [log_name [log_mode]] |
|
1107 | 1107 | |
|
1108 | 1108 | If no name is given, it defaults to a file named 'ipython_log.py' in your |
|
1109 | 1109 | current directory, in 'rotate' mode (see below). |
|
1110 | 1110 | |
|
1111 | 1111 | '%logstart name' saves to file 'name' in 'backup' mode. It saves your |
|
1112 | 1112 | history up to that point and then continues logging. |
|
1113 | 1113 | |
|
1114 | 1114 | %logstart takes a second optional parameter: logging mode. This can be one |
|
1115 | 1115 | of (note that the modes are given unquoted):\\ |
|
1116 | 1116 | append: well, that says it.\\ |
|
1117 | 1117 | backup: rename (if exists) to name~ and start name.\\ |
|
1118 | 1118 | global: single logfile in your home dir, appended to.\\ |
|
1119 | 1119 | over : overwrite existing log.\\ |
|
1120 | 1120 | rotate: create rotating logs name.1~, name.2~, etc. |
|
1121 | 1121 | |
|
1122 | 1122 | Options: |
|
1123 | 1123 | |
|
1124 | 1124 | -o: log also IPython's output. In this mode, all commands which |
|
1125 | 1125 | generate an Out[NN] prompt are recorded to the logfile, right after |
|
1126 | 1126 | their corresponding input line. The output lines are always |
|
1127 | 1127 | prepended with a '#[Out]# ' marker, so that the log remains valid |
|
1128 | 1128 | Python code. |
|
1129 | 1129 | |
|
1130 | 1130 | Since this marker is always the same, filtering only the output from |
|
1131 | 1131 | a log is very easy, using for example a simple awk call: |
|
1132 | 1132 | |
|
1133 | 1133 | awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py |
|
1134 | 1134 | |
|
1135 | 1135 | -r: log 'raw' input. Normally, IPython's logs contain the processed |
|
1136 | 1136 | input, so that user lines are logged in their final form, converted |
|
1137 | 1137 | into valid Python. For example, %Exit is logged as |
|
1138 | 1138 | '_ip.magic("Exit"). If the -r flag is given, all input is logged |
|
1139 | 1139 | exactly as typed, with no transformations applied. |
|
1140 | 1140 | |
|
1141 | 1141 | -t: put timestamps before each input line logged (these are put in |
|
1142 | 1142 | comments).""" |
|
1143 | 1143 | |
|
1144 | 1144 | opts,par = self.parse_options(parameter_s,'ort') |
|
1145 | 1145 | log_output = 'o' in opts |
|
1146 | 1146 | log_raw_input = 'r' in opts |
|
1147 | 1147 | timestamp = 't' in opts |
|
1148 | 1148 | |
|
1149 | 1149 | logger = self.shell.logger |
|
1150 | 1150 | |
|
1151 | 1151 | # if no args are given, the defaults set in the logger constructor by |
|
1152 | 1152 | # ipytohn remain valid |
|
1153 | 1153 | if par: |
|
1154 | 1154 | try: |
|
1155 | 1155 | logfname,logmode = par.split() |
|
1156 | 1156 | except: |
|
1157 | 1157 | logfname = par |
|
1158 | 1158 | logmode = 'backup' |
|
1159 | 1159 | else: |
|
1160 | 1160 | logfname = logger.logfname |
|
1161 | 1161 | logmode = logger.logmode |
|
1162 | 1162 | # put logfname into rc struct as if it had been called on the command |
|
1163 | 1163 | # line, so it ends up saved in the log header Save it in case we need |
|
1164 | 1164 | # to restore it... |
|
1165 | 1165 | old_logfile = self.shell.logfile |
|
1166 | 1166 | if logfname: |
|
1167 | 1167 | logfname = os.path.expanduser(logfname) |
|
1168 | 1168 | self.shell.logfile = logfname |
|
1169 | 1169 | |
|
1170 | 1170 | loghead = '# IPython log file\n\n' |
|
1171 | 1171 | try: |
|
1172 | 1172 | started = logger.logstart(logfname,loghead,logmode, |
|
1173 | 1173 | log_output,timestamp,log_raw_input) |
|
1174 | 1174 | except: |
|
1175 | 1175 | rc.opts.logfile = old_logfile |
|
1176 | 1176 | warn("Couldn't start log: %s" % sys.exc_info()[1]) |
|
1177 | 1177 | else: |
|
1178 | 1178 | # log input history up to this point, optionally interleaving |
|
1179 | 1179 | # output if requested |
|
1180 | 1180 | |
|
1181 | 1181 | if timestamp: |
|
1182 | 1182 | # disable timestamping for the previous history, since we've |
|
1183 | 1183 | # lost those already (no time machine here). |
|
1184 | 1184 | logger.timestamp = False |
|
1185 | 1185 | |
|
1186 | 1186 | if log_raw_input: |
|
1187 | 1187 | input_hist = self.shell.input_hist_raw |
|
1188 | 1188 | else: |
|
1189 | 1189 | input_hist = self.shell.input_hist |
|
1190 | 1190 | |
|
1191 | 1191 | if log_output: |
|
1192 | 1192 | log_write = logger.log_write |
|
1193 | 1193 | output_hist = self.shell.output_hist |
|
1194 | 1194 | for n in range(1,len(input_hist)-1): |
|
1195 | 1195 | log_write(input_hist[n].rstrip()) |
|
1196 | 1196 | if n in output_hist: |
|
1197 | 1197 | log_write(repr(output_hist[n]),'output') |
|
1198 | 1198 | else: |
|
1199 | 1199 | logger.log_write(input_hist[1:]) |
|
1200 | 1200 | if timestamp: |
|
1201 | 1201 | # re-enable timestamping |
|
1202 | 1202 | logger.timestamp = True |
|
1203 | 1203 | |
|
1204 | 1204 | print ('Activating auto-logging. ' |
|
1205 | 1205 | 'Current session state plus future input saved.') |
|
1206 | 1206 | logger.logstate() |
|
1207 | 1207 | |
|
1208 | 1208 | def magic_logstop(self,parameter_s=''): |
|
1209 | 1209 | """Fully stop logging and close log file. |
|
1210 | 1210 | |
|
1211 | 1211 | In order to start logging again, a new %logstart call needs to be made, |
|
1212 | 1212 | possibly (though not necessarily) with a new filename, mode and other |
|
1213 | 1213 | options.""" |
|
1214 | 1214 | self.logger.logstop() |
|
1215 | 1215 | |
|
1216 | 1216 | def magic_logoff(self,parameter_s=''): |
|
1217 | 1217 | """Temporarily stop logging. |
|
1218 | 1218 | |
|
1219 | 1219 | You must have previously started logging.""" |
|
1220 | 1220 | self.shell.logger.switch_log(0) |
|
1221 | 1221 | |
|
1222 | 1222 | def magic_logon(self,parameter_s=''): |
|
1223 | 1223 | """Restart logging. |
|
1224 | 1224 | |
|
1225 | 1225 | This function is for restarting logging which you've temporarily |
|
1226 | 1226 | stopped with %logoff. For starting logging for the first time, you |
|
1227 | 1227 | must use the %logstart function, which allows you to specify an |
|
1228 | 1228 | optional log filename.""" |
|
1229 | 1229 | |
|
1230 | 1230 | self.shell.logger.switch_log(1) |
|
1231 | 1231 | |
|
1232 | 1232 | def magic_logstate(self,parameter_s=''): |
|
1233 | 1233 | """Print the status of the logging system.""" |
|
1234 | 1234 | |
|
1235 | 1235 | self.shell.logger.logstate() |
|
1236 | 1236 | |
|
1237 | 1237 | def magic_pdb(self, parameter_s=''): |
|
1238 | 1238 | """Control the automatic calling of the pdb interactive debugger. |
|
1239 | 1239 | |
|
1240 | 1240 | Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without |
|
1241 | 1241 | argument it works as a toggle. |
|
1242 | 1242 | |
|
1243 | 1243 | When an exception is triggered, IPython can optionally call the |
|
1244 | 1244 | interactive pdb debugger after the traceback printout. %pdb toggles |
|
1245 | 1245 | this feature on and off. |
|
1246 | 1246 | |
|
1247 | 1247 | The initial state of this feature is set in your ipythonrc |
|
1248 | 1248 | configuration file (the variable is called 'pdb'). |
|
1249 | 1249 | |
|
1250 | 1250 | If you want to just activate the debugger AFTER an exception has fired, |
|
1251 | 1251 | without having to type '%pdb on' and rerunning your code, you can use |
|
1252 | 1252 | the %debug magic.""" |
|
1253 | 1253 | |
|
1254 | 1254 | par = parameter_s.strip().lower() |
|
1255 | 1255 | |
|
1256 | 1256 | if par: |
|
1257 | 1257 | try: |
|
1258 | 1258 | new_pdb = {'off':0,'0':0,'on':1,'1':1}[par] |
|
1259 | 1259 | except KeyError: |
|
1260 | 1260 | print ('Incorrect argument. Use on/1, off/0, ' |
|
1261 | 1261 | 'or nothing for a toggle.') |
|
1262 | 1262 | return |
|
1263 | 1263 | else: |
|
1264 | 1264 | # toggle |
|
1265 | 1265 | new_pdb = not self.shell.call_pdb |
|
1266 | 1266 | |
|
1267 | 1267 | # set on the shell |
|
1268 | 1268 | self.shell.call_pdb = new_pdb |
|
1269 | 1269 | print 'Automatic pdb calling has been turned',on_off(new_pdb) |
|
1270 | 1270 | |
|
1271 | 1271 | def magic_debug(self, parameter_s=''): |
|
1272 | 1272 | """Activate the interactive debugger in post-mortem mode. |
|
1273 | 1273 | |
|
1274 | 1274 | If an exception has just occurred, this lets you inspect its stack |
|
1275 | 1275 | frames interactively. Note that this will always work only on the last |
|
1276 | 1276 | traceback that occurred, so you must call this quickly after an |
|
1277 | 1277 | exception that you wish to inspect has fired, because if another one |
|
1278 | 1278 | occurs, it clobbers the previous one. |
|
1279 | 1279 | |
|
1280 | 1280 | If you want IPython to automatically do this on every exception, see |
|
1281 | 1281 | the %pdb magic for more details. |
|
1282 | 1282 | """ |
|
1283 | 1283 | self.shell.debugger(force=True) |
|
1284 | 1284 | |
|
1285 | 1285 | @testdec.skip_doctest |
|
1286 | 1286 | def magic_prun(self, parameter_s ='',user_mode=1, |
|
1287 | 1287 | opts=None,arg_lst=None,prog_ns=None): |
|
1288 | 1288 | |
|
1289 | 1289 | """Run a statement through the python code profiler. |
|
1290 | 1290 | |
|
1291 | 1291 | Usage: |
|
1292 | 1292 | %prun [options] statement |
|
1293 | 1293 | |
|
1294 | 1294 | The given statement (which doesn't require quote marks) is run via the |
|
1295 | 1295 | python profiler in a manner similar to the profile.run() function. |
|
1296 | 1296 | Namespaces are internally managed to work correctly; profile.run |
|
1297 | 1297 | cannot be used in IPython because it makes certain assumptions about |
|
1298 | 1298 | namespaces which do not hold under IPython. |
|
1299 | 1299 | |
|
1300 | 1300 | Options: |
|
1301 | 1301 | |
|
1302 | 1302 | -l <limit>: you can place restrictions on what or how much of the |
|
1303 | 1303 | profile gets printed. The limit value can be: |
|
1304 | 1304 | |
|
1305 | 1305 | * A string: only information for function names containing this string |
|
1306 | 1306 | is printed. |
|
1307 | 1307 | |
|
1308 | 1308 | * An integer: only these many lines are printed. |
|
1309 | 1309 | |
|
1310 | 1310 | * A float (between 0 and 1): this fraction of the report is printed |
|
1311 | 1311 | (for example, use a limit of 0.4 to see the topmost 40% only). |
|
1312 | 1312 | |
|
1313 | 1313 | You can combine several limits with repeated use of the option. For |
|
1314 | 1314 | example, '-l __init__ -l 5' will print only the topmost 5 lines of |
|
1315 | 1315 | information about class constructors. |
|
1316 | 1316 | |
|
1317 | 1317 | -r: return the pstats.Stats object generated by the profiling. This |
|
1318 | 1318 | object has all the information about the profile in it, and you can |
|
1319 | 1319 | later use it for further analysis or in other functions. |
|
1320 | 1320 | |
|
1321 | 1321 | -s <key>: sort profile by given key. You can provide more than one key |
|
1322 | 1322 | by using the option several times: '-s key1 -s key2 -s key3...'. The |
|
1323 | 1323 | default sorting key is 'time'. |
|
1324 | 1324 | |
|
1325 | 1325 | The following is copied verbatim from the profile documentation |
|
1326 | 1326 | referenced below: |
|
1327 | 1327 | |
|
1328 | 1328 | When more than one key is provided, additional keys are used as |
|
1329 | 1329 | secondary criteria when the there is equality in all keys selected |
|
1330 | 1330 | before them. |
|
1331 | 1331 | |
|
1332 | 1332 | Abbreviations can be used for any key names, as long as the |
|
1333 | 1333 | abbreviation is unambiguous. The following are the keys currently |
|
1334 | 1334 | defined: |
|
1335 | 1335 | |
|
1336 | 1336 | Valid Arg Meaning |
|
1337 | 1337 | "calls" call count |
|
1338 | 1338 | "cumulative" cumulative time |
|
1339 | 1339 | "file" file name |
|
1340 | 1340 | "module" file name |
|
1341 | 1341 | "pcalls" primitive call count |
|
1342 | 1342 | "line" line number |
|
1343 | 1343 | "name" function name |
|
1344 | 1344 | "nfl" name/file/line |
|
1345 | 1345 | "stdname" standard name |
|
1346 | 1346 | "time" internal time |
|
1347 | 1347 | |
|
1348 | 1348 | Note that all sorts on statistics are in descending order (placing |
|
1349 | 1349 | most time consuming items first), where as name, file, and line number |
|
1350 | 1350 | searches are in ascending order (i.e., alphabetical). The subtle |
|
1351 | 1351 | distinction between "nfl" and "stdname" is that the standard name is a |
|
1352 | 1352 | sort of the name as printed, which means that the embedded line |
|
1353 | 1353 | numbers get compared in an odd way. For example, lines 3, 20, and 40 |
|
1354 | 1354 | would (if the file names were the same) appear in the string order |
|
1355 | 1355 | "20" "3" and "40". In contrast, "nfl" does a numeric compare of the |
|
1356 | 1356 | line numbers. In fact, sort_stats("nfl") is the same as |
|
1357 | 1357 | sort_stats("name", "file", "line"). |
|
1358 | 1358 | |
|
1359 | 1359 | -T <filename>: save profile results as shown on screen to a text |
|
1360 | 1360 | file. The profile is still shown on screen. |
|
1361 | 1361 | |
|
1362 | 1362 | -D <filename>: save (via dump_stats) profile statistics to given |
|
1363 | 1363 | filename. This data is in a format understod by the pstats module, and |
|
1364 | 1364 | is generated by a call to the dump_stats() method of profile |
|
1365 | 1365 | objects. The profile is still shown on screen. |
|
1366 | 1366 | |
|
1367 | 1367 | If you want to run complete programs under the profiler's control, use |
|
1368 | 1368 | '%run -p [prof_opts] filename.py [args to program]' where prof_opts |
|
1369 | 1369 | contains profiler specific options as described here. |
|
1370 | 1370 | |
|
1371 | 1371 | You can read the complete documentation for the profile module with:: |
|
1372 | 1372 | |
|
1373 | 1373 | In [1]: import profile; profile.help() |
|
1374 | 1374 | """ |
|
1375 | 1375 | |
|
1376 | 1376 | opts_def = Struct(D=[''],l=[],s=['time'],T=['']) |
|
1377 | 1377 | # protect user quote marks |
|
1378 | 1378 | parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'") |
|
1379 | 1379 | |
|
1380 | 1380 | if user_mode: # regular user call |
|
1381 | 1381 | opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:', |
|
1382 | 1382 | list_all=1) |
|
1383 | 1383 | namespace = self.shell.user_ns |
|
1384 | 1384 | else: # called to run a program by %run -p |
|
1385 | 1385 | try: |
|
1386 | 1386 | filename = get_py_filename(arg_lst[0]) |
|
1387 | 1387 | except IOError,msg: |
|
1388 | 1388 | error(msg) |
|
1389 | 1389 | return |
|
1390 | 1390 | |
|
1391 | 1391 | arg_str = 'execfile(filename,prog_ns)' |
|
1392 | 1392 | namespace = locals() |
|
1393 | 1393 | |
|
1394 | 1394 | opts.merge(opts_def) |
|
1395 | 1395 | |
|
1396 | 1396 | prof = profile.Profile() |
|
1397 | 1397 | try: |
|
1398 | 1398 | prof = prof.runctx(arg_str,namespace,namespace) |
|
1399 | 1399 | sys_exit = '' |
|
1400 | 1400 | except SystemExit: |
|
1401 | 1401 | sys_exit = """*** SystemExit exception caught in code being profiled.""" |
|
1402 | 1402 | |
|
1403 | 1403 | stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s) |
|
1404 | 1404 | |
|
1405 | 1405 | lims = opts.l |
|
1406 | 1406 | if lims: |
|
1407 | 1407 | lims = [] # rebuild lims with ints/floats/strings |
|
1408 | 1408 | for lim in opts.l: |
|
1409 | 1409 | try: |
|
1410 | 1410 | lims.append(int(lim)) |
|
1411 | 1411 | except ValueError: |
|
1412 | 1412 | try: |
|
1413 | 1413 | lims.append(float(lim)) |
|
1414 | 1414 | except ValueError: |
|
1415 | 1415 | lims.append(lim) |
|
1416 | 1416 | |
|
1417 | 1417 | # Trap output. |
|
1418 | 1418 | stdout_trap = StringIO() |
|
1419 | 1419 | |
|
1420 | 1420 | if hasattr(stats,'stream'): |
|
1421 | 1421 | # In newer versions of python, the stats object has a 'stream' |
|
1422 | 1422 | # attribute to write into. |
|
1423 | 1423 | stats.stream = stdout_trap |
|
1424 | 1424 | stats.print_stats(*lims) |
|
1425 | 1425 | else: |
|
1426 | 1426 | # For older versions, we manually redirect stdout during printing |
|
1427 | 1427 | sys_stdout = sys.stdout |
|
1428 | 1428 | try: |
|
1429 | 1429 | sys.stdout = stdout_trap |
|
1430 | 1430 | stats.print_stats(*lims) |
|
1431 | 1431 | finally: |
|
1432 | 1432 | sys.stdout = sys_stdout |
|
1433 | 1433 | |
|
1434 | 1434 | output = stdout_trap.getvalue() |
|
1435 | 1435 | output = output.rstrip() |
|
1436 | 1436 | |
|
1437 | 1437 | page(output,screen_lines=self.shell.usable_screen_length) |
|
1438 | 1438 | print sys_exit, |
|
1439 | 1439 | |
|
1440 | 1440 | dump_file = opts.D[0] |
|
1441 | 1441 | text_file = opts.T[0] |
|
1442 | 1442 | if dump_file: |
|
1443 | 1443 | prof.dump_stats(dump_file) |
|
1444 | 1444 | print '\n*** Profile stats marshalled to file',\ |
|
1445 | 1445 | `dump_file`+'.',sys_exit |
|
1446 | 1446 | if text_file: |
|
1447 | 1447 | pfile = file(text_file,'w') |
|
1448 | 1448 | pfile.write(output) |
|
1449 | 1449 | pfile.close() |
|
1450 | 1450 | print '\n*** Profile printout saved to text file',\ |
|
1451 | 1451 | `text_file`+'.',sys_exit |
|
1452 | 1452 | |
|
1453 | 1453 | if opts.has_key('r'): |
|
1454 | 1454 | return stats |
|
1455 | 1455 | else: |
|
1456 | 1456 | return None |
|
1457 | 1457 | |
|
1458 | 1458 | @testdec.skip_doctest |
|
1459 | 1459 | def magic_run(self, parameter_s ='',runner=None, |
|
1460 | 1460 | file_finder=get_py_filename): |
|
1461 | 1461 | """Run the named file inside IPython as a program. |
|
1462 | 1462 | |
|
1463 | 1463 | Usage:\\ |
|
1464 | 1464 | %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args] |
|
1465 | 1465 | |
|
1466 | 1466 | Parameters after the filename are passed as command-line arguments to |
|
1467 | 1467 | the program (put in sys.argv). Then, control returns to IPython's |
|
1468 | 1468 | prompt. |
|
1469 | 1469 | |
|
1470 | 1470 | This is similar to running at a system prompt:\\ |
|
1471 | 1471 | $ python file args\\ |
|
1472 | 1472 | but with the advantage of giving you IPython's tracebacks, and of |
|
1473 | 1473 | loading all variables into your interactive namespace for further use |
|
1474 | 1474 | (unless -p is used, see below). |
|
1475 | 1475 | |
|
1476 | 1476 | The file is executed in a namespace initially consisting only of |
|
1477 | 1477 | __name__=='__main__' and sys.argv constructed as indicated. It thus |
|
1478 | 1478 | sees its environment as if it were being run as a stand-alone program |
|
1479 | 1479 | (except for sharing global objects such as previously imported |
|
1480 | 1480 | modules). But after execution, the IPython interactive namespace gets |
|
1481 | 1481 | updated with all variables defined in the program (except for __name__ |
|
1482 | 1482 | and sys.argv). This allows for very convenient loading of code for |
|
1483 | 1483 | interactive work, while giving each program a 'clean sheet' to run in. |
|
1484 | 1484 | |
|
1485 | 1485 | Options: |
|
1486 | 1486 | |
|
1487 | 1487 | -n: __name__ is NOT set to '__main__', but to the running file's name |
|
1488 | 1488 | without extension (as python does under import). This allows running |
|
1489 | 1489 | scripts and reloading the definitions in them without calling code |
|
1490 | 1490 | protected by an ' if __name__ == "__main__" ' clause. |
|
1491 | 1491 | |
|
1492 | 1492 | -i: run the file in IPython's namespace instead of an empty one. This |
|
1493 | 1493 | is useful if you are experimenting with code written in a text editor |
|
1494 | 1494 | which depends on variables defined interactively. |
|
1495 | 1495 | |
|
1496 | 1496 | -e: ignore sys.exit() calls or SystemExit exceptions in the script |
|
1497 | 1497 | being run. This is particularly useful if IPython is being used to |
|
1498 | 1498 | run unittests, which always exit with a sys.exit() call. In such |
|
1499 | 1499 | cases you are interested in the output of the test results, not in |
|
1500 | 1500 | seeing a traceback of the unittest module. |
|
1501 | 1501 | |
|
1502 | 1502 | -t: print timing information at the end of the run. IPython will give |
|
1503 | 1503 | you an estimated CPU time consumption for your script, which under |
|
1504 | 1504 | Unix uses the resource module to avoid the wraparound problems of |
|
1505 | 1505 | time.clock(). Under Unix, an estimate of time spent on system tasks |
|
1506 | 1506 | is also given (for Windows platforms this is reported as 0.0). |
|
1507 | 1507 | |
|
1508 | 1508 | If -t is given, an additional -N<N> option can be given, where <N> |
|
1509 | 1509 | must be an integer indicating how many times you want the script to |
|
1510 | 1510 | run. The final timing report will include total and per run results. |
|
1511 | 1511 | |
|
1512 | 1512 | For example (testing the script uniq_stable.py): |
|
1513 | 1513 | |
|
1514 | 1514 | In [1]: run -t uniq_stable |
|
1515 | 1515 | |
|
1516 | 1516 | IPython CPU timings (estimated):\\ |
|
1517 | 1517 | User : 0.19597 s.\\ |
|
1518 | 1518 | System: 0.0 s.\\ |
|
1519 | 1519 | |
|
1520 | 1520 | In [2]: run -t -N5 uniq_stable |
|
1521 | 1521 | |
|
1522 | 1522 | IPython CPU timings (estimated):\\ |
|
1523 | 1523 | Total runs performed: 5\\ |
|
1524 | 1524 | Times : Total Per run\\ |
|
1525 | 1525 | User : 0.910862 s, 0.1821724 s.\\ |
|
1526 | 1526 | System: 0.0 s, 0.0 s. |
|
1527 | 1527 | |
|
1528 | 1528 | -d: run your program under the control of pdb, the Python debugger. |
|
1529 | 1529 | This allows you to execute your program step by step, watch variables, |
|
1530 | 1530 | etc. Internally, what IPython does is similar to calling: |
|
1531 | 1531 | |
|
1532 | 1532 | pdb.run('execfile("YOURFILENAME")') |
|
1533 | 1533 | |
|
1534 | 1534 | with a breakpoint set on line 1 of your file. You can change the line |
|
1535 | 1535 | number for this automatic breakpoint to be <N> by using the -bN option |
|
1536 | 1536 | (where N must be an integer). For example: |
|
1537 | 1537 | |
|
1538 | 1538 | %run -d -b40 myscript |
|
1539 | 1539 | |
|
1540 | 1540 | will set the first breakpoint at line 40 in myscript.py. Note that |
|
1541 | 1541 | the first breakpoint must be set on a line which actually does |
|
1542 | 1542 | something (not a comment or docstring) for it to stop execution. |
|
1543 | 1543 | |
|
1544 | 1544 | When the pdb debugger starts, you will see a (Pdb) prompt. You must |
|
1545 | 1545 | first enter 'c' (without qoutes) to start execution up to the first |
|
1546 | 1546 | breakpoint. |
|
1547 | 1547 | |
|
1548 | 1548 | Entering 'help' gives information about the use of the debugger. You |
|
1549 | 1549 | can easily see pdb's full documentation with "import pdb;pdb.help()" |
|
1550 | 1550 | at a prompt. |
|
1551 | 1551 | |
|
1552 | 1552 | -p: run program under the control of the Python profiler module (which |
|
1553 | 1553 | prints a detailed report of execution times, function calls, etc). |
|
1554 | 1554 | |
|
1555 | 1555 | You can pass other options after -p which affect the behavior of the |
|
1556 | 1556 | profiler itself. See the docs for %prun for details. |
|
1557 | 1557 | |
|
1558 | 1558 | In this mode, the program's variables do NOT propagate back to the |
|
1559 | 1559 | IPython interactive namespace (because they remain in the namespace |
|
1560 | 1560 | where the profiler executes them). |
|
1561 | 1561 | |
|
1562 | 1562 | Internally this triggers a call to %prun, see its documentation for |
|
1563 | 1563 | details on the options available specifically for profiling. |
|
1564 | 1564 | |
|
1565 | 1565 | There is one special usage for which the text above doesn't apply: |
|
1566 | 1566 | if the filename ends with .ipy, the file is run as ipython script, |
|
1567 | 1567 | just as if the commands were written on IPython prompt. |
|
1568 | 1568 | """ |
|
1569 | 1569 | |
|
1570 | 1570 | # get arguments and set sys.argv for program to be run. |
|
1571 | 1571 | opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e', |
|
1572 | 1572 | mode='list',list_all=1) |
|
1573 | 1573 | |
|
1574 | 1574 | try: |
|
1575 | 1575 | filename = file_finder(arg_lst[0]) |
|
1576 | 1576 | except IndexError: |
|
1577 | 1577 | warn('you must provide at least a filename.') |
|
1578 | 1578 | print '\n%run:\n',oinspect.getdoc(self.magic_run) |
|
1579 | 1579 | return |
|
1580 | 1580 | except IOError,msg: |
|
1581 | 1581 | error(msg) |
|
1582 | 1582 | return |
|
1583 | 1583 | |
|
1584 | 1584 | if filename.lower().endswith('.ipy'): |
|
1585 | 1585 | self.shell.safe_execfile_ipy(filename) |
|
1586 | 1586 | return |
|
1587 | 1587 | |
|
1588 | 1588 | # Control the response to exit() calls made by the script being run |
|
1589 | 1589 | exit_ignore = opts.has_key('e') |
|
1590 | 1590 | |
|
1591 | 1591 | # Make sure that the running script gets a proper sys.argv as if it |
|
1592 | 1592 | # were run from a system shell. |
|
1593 | 1593 | save_argv = sys.argv # save it for later restoring |
|
1594 | 1594 | sys.argv = [filename]+ arg_lst[1:] # put in the proper filename |
|
1595 | 1595 | |
|
1596 | 1596 | if opts.has_key('i'): |
|
1597 | 1597 | # Run in user's interactive namespace |
|
1598 | 1598 | prog_ns = self.shell.user_ns |
|
1599 | 1599 | __name__save = self.shell.user_ns['__name__'] |
|
1600 | 1600 | prog_ns['__name__'] = '__main__' |
|
1601 | 1601 | main_mod = self.shell.new_main_mod(prog_ns) |
|
1602 | 1602 | else: |
|
1603 | 1603 | # Run in a fresh, empty namespace |
|
1604 | 1604 | if opts.has_key('n'): |
|
1605 | 1605 | name = os.path.splitext(os.path.basename(filename))[0] |
|
1606 | 1606 | else: |
|
1607 | 1607 | name = '__main__' |
|
1608 | 1608 | |
|
1609 | 1609 | main_mod = self.shell.new_main_mod() |
|
1610 | 1610 | prog_ns = main_mod.__dict__ |
|
1611 | 1611 | prog_ns['__name__'] = name |
|
1612 | 1612 | |
|
1613 | 1613 | # Since '%run foo' emulates 'python foo.py' at the cmd line, we must |
|
1614 | 1614 | # set the __file__ global in the script's namespace |
|
1615 | 1615 | prog_ns['__file__'] = filename |
|
1616 | 1616 | |
|
1617 | 1617 | # pickle fix. See iplib for an explanation. But we need to make sure |
|
1618 | 1618 | # that, if we overwrite __main__, we replace it at the end |
|
1619 | 1619 | main_mod_name = prog_ns['__name__'] |
|
1620 | 1620 | |
|
1621 | 1621 | if main_mod_name == '__main__': |
|
1622 | 1622 | restore_main = sys.modules['__main__'] |
|
1623 | 1623 | else: |
|
1624 | 1624 | restore_main = False |
|
1625 | 1625 | |
|
1626 | 1626 | # This needs to be undone at the end to prevent holding references to |
|
1627 | 1627 | # every single object ever created. |
|
1628 | 1628 | sys.modules[main_mod_name] = main_mod |
|
1629 | 1629 | |
|
1630 | 1630 | stats = None |
|
1631 | 1631 | try: |
|
1632 | 1632 | self.shell.savehist() |
|
1633 | 1633 | |
|
1634 | 1634 | if opts.has_key('p'): |
|
1635 | 1635 | stats = self.magic_prun('',0,opts,arg_lst,prog_ns) |
|
1636 | 1636 | else: |
|
1637 | 1637 | if opts.has_key('d'): |
|
1638 | 1638 | deb = debugger.Pdb(self.shell.colors) |
|
1639 | 1639 | # reset Breakpoint state, which is moronically kept |
|
1640 | 1640 | # in a class |
|
1641 | 1641 | bdb.Breakpoint.next = 1 |
|
1642 | 1642 | bdb.Breakpoint.bplist = {} |
|
1643 | 1643 | bdb.Breakpoint.bpbynumber = [None] |
|
1644 | 1644 | # Set an initial breakpoint to stop execution |
|
1645 | 1645 | maxtries = 10 |
|
1646 | 1646 | bp = int(opts.get('b',[1])[0]) |
|
1647 | 1647 | checkline = deb.checkline(filename,bp) |
|
1648 | 1648 | if not checkline: |
|
1649 | 1649 | for bp in range(bp+1,bp+maxtries+1): |
|
1650 | 1650 | if deb.checkline(filename,bp): |
|
1651 | 1651 | break |
|
1652 | 1652 | else: |
|
1653 | 1653 | msg = ("\nI failed to find a valid line to set " |
|
1654 | 1654 | "a breakpoint\n" |
|
1655 | 1655 | "after trying up to line: %s.\n" |
|
1656 | 1656 | "Please set a valid breakpoint manually " |
|
1657 | 1657 | "with the -b option." % bp) |
|
1658 | 1658 | error(msg) |
|
1659 | 1659 | return |
|
1660 | 1660 | # if we find a good linenumber, set the breakpoint |
|
1661 | 1661 | deb.do_break('%s:%s' % (filename,bp)) |
|
1662 | 1662 | # Start file run |
|
1663 | 1663 | print "NOTE: Enter 'c' at the", |
|
1664 | 1664 | print "%s prompt to start your script." % deb.prompt |
|
1665 | 1665 | try: |
|
1666 | 1666 | deb.run('execfile("%s")' % filename,prog_ns) |
|
1667 | 1667 | |
|
1668 | 1668 | except: |
|
1669 | 1669 | etype, value, tb = sys.exc_info() |
|
1670 | 1670 | # Skip three frames in the traceback: the %run one, |
|
1671 | 1671 | # one inside bdb.py, and the command-line typed by the |
|
1672 | 1672 | # user (run by exec in pdb itself). |
|
1673 | 1673 | self.shell.InteractiveTB(etype,value,tb,tb_offset=3) |
|
1674 | 1674 | else: |
|
1675 | 1675 | if runner is None: |
|
1676 | 1676 | runner = self.shell.safe_execfile |
|
1677 | 1677 | if opts.has_key('t'): |
|
1678 | 1678 | # timed execution |
|
1679 | 1679 | try: |
|
1680 | 1680 | nruns = int(opts['N'][0]) |
|
1681 | 1681 | if nruns < 1: |
|
1682 | 1682 | error('Number of runs must be >=1') |
|
1683 | 1683 | return |
|
1684 | 1684 | except (KeyError): |
|
1685 | 1685 | nruns = 1 |
|
1686 | 1686 | if nruns == 1: |
|
1687 | 1687 | t0 = clock2() |
|
1688 | 1688 | runner(filename,prog_ns,prog_ns, |
|
1689 | 1689 | exit_ignore=exit_ignore) |
|
1690 | 1690 | t1 = clock2() |
|
1691 | 1691 | t_usr = t1[0]-t0[0] |
|
1692 | 1692 | t_sys = t1[1]-t0[1] |
|
1693 | 1693 | print "\nIPython CPU timings (estimated):" |
|
1694 | 1694 | print " User : %10s s." % t_usr |
|
1695 | 1695 | print " System: %10s s." % t_sys |
|
1696 | 1696 | else: |
|
1697 | 1697 | runs = range(nruns) |
|
1698 | 1698 | t0 = clock2() |
|
1699 | 1699 | for nr in runs: |
|
1700 | 1700 | runner(filename,prog_ns,prog_ns, |
|
1701 | 1701 | exit_ignore=exit_ignore) |
|
1702 | 1702 | t1 = clock2() |
|
1703 | 1703 | t_usr = t1[0]-t0[0] |
|
1704 | 1704 | t_sys = t1[1]-t0[1] |
|
1705 | 1705 | print "\nIPython CPU timings (estimated):" |
|
1706 | 1706 | print "Total runs performed:",nruns |
|
1707 | 1707 | print " Times : %10s %10s" % ('Total','Per run') |
|
1708 | 1708 | print " User : %10s s, %10s s." % (t_usr,t_usr/nruns) |
|
1709 | 1709 | print " System: %10s s, %10s s." % (t_sys,t_sys/nruns) |
|
1710 | 1710 | |
|
1711 | 1711 | else: |
|
1712 | 1712 | # regular execution |
|
1713 | 1713 | runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore) |
|
1714 | 1714 | |
|
1715 | 1715 | if opts.has_key('i'): |
|
1716 | 1716 | self.shell.user_ns['__name__'] = __name__save |
|
1717 | 1717 | else: |
|
1718 | 1718 | # The shell MUST hold a reference to prog_ns so after %run |
|
1719 | 1719 | # exits, the python deletion mechanism doesn't zero it out |
|
1720 | 1720 | # (leaving dangling references). |
|
1721 | 1721 | self.shell.cache_main_mod(prog_ns,filename) |
|
1722 | 1722 | # update IPython interactive namespace |
|
1723 | 1723 | |
|
1724 | 1724 | # Some forms of read errors on the file may mean the |
|
1725 | 1725 | # __name__ key was never set; using pop we don't have to |
|
1726 | 1726 | # worry about a possible KeyError. |
|
1727 | 1727 | prog_ns.pop('__name__', None) |
|
1728 | 1728 | |
|
1729 | 1729 | self.shell.user_ns.update(prog_ns) |
|
1730 | 1730 | finally: |
|
1731 | 1731 | # It's a bit of a mystery why, but __builtins__ can change from |
|
1732 | 1732 | # being a module to becoming a dict missing some key data after |
|
1733 | 1733 | # %run. As best I can see, this is NOT something IPython is doing |
|
1734 | 1734 | # at all, and similar problems have been reported before: |
|
1735 | 1735 | # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html |
|
1736 | 1736 | # Since this seems to be done by the interpreter itself, the best |
|
1737 | 1737 | # we can do is to at least restore __builtins__ for the user on |
|
1738 | 1738 | # exit. |
|
1739 | 1739 | self.shell.user_ns['__builtins__'] = __builtin__ |
|
1740 | 1740 | |
|
1741 | 1741 | # Ensure key global structures are restored |
|
1742 | 1742 | sys.argv = save_argv |
|
1743 | 1743 | if restore_main: |
|
1744 | 1744 | sys.modules['__main__'] = restore_main |
|
1745 | 1745 | else: |
|
1746 | 1746 | # Remove from sys.modules the reference to main_mod we'd |
|
1747 | 1747 | # added. Otherwise it will trap references to objects |
|
1748 | 1748 | # contained therein. |
|
1749 | 1749 | del sys.modules[main_mod_name] |
|
1750 | 1750 | |
|
1751 | 1751 | self.shell.reloadhist() |
|
1752 | 1752 | |
|
1753 | 1753 | return stats |
|
1754 | 1754 | |
|
1755 | 1755 | @testdec.skip_doctest |
|
1756 | 1756 | def magic_timeit(self, parameter_s =''): |
|
1757 | 1757 | """Time execution of a Python statement or expression |
|
1758 | 1758 | |
|
1759 | 1759 | Usage:\\ |
|
1760 | 1760 | %timeit [-n<N> -r<R> [-t|-c]] statement |
|
1761 | 1761 | |
|
1762 | 1762 | Time execution of a Python statement or expression using the timeit |
|
1763 | 1763 | module. |
|
1764 | 1764 | |
|
1765 | 1765 | Options: |
|
1766 | 1766 | -n<N>: execute the given statement <N> times in a loop. If this value |
|
1767 | 1767 | is not given, a fitting value is chosen. |
|
1768 | 1768 | |
|
1769 | 1769 | -r<R>: repeat the loop iteration <R> times and take the best result. |
|
1770 | 1770 | Default: 3 |
|
1771 | 1771 | |
|
1772 | 1772 | -t: use time.time to measure the time, which is the default on Unix. |
|
1773 | 1773 | This function measures wall time. |
|
1774 | 1774 | |
|
1775 | 1775 | -c: use time.clock to measure the time, which is the default on |
|
1776 | 1776 | Windows and measures wall time. On Unix, resource.getrusage is used |
|
1777 | 1777 | instead and returns the CPU user time. |
|
1778 | 1778 | |
|
1779 | 1779 | -p<P>: use a precision of <P> digits to display the timing result. |
|
1780 | 1780 | Default: 3 |
|
1781 | 1781 | |
|
1782 | 1782 | |
|
1783 | 1783 | Examples: |
|
1784 | 1784 | |
|
1785 | 1785 | In [1]: %timeit pass |
|
1786 | 1786 | 10000000 loops, best of 3: 53.3 ns per loop |
|
1787 | 1787 | |
|
1788 | 1788 | In [2]: u = None |
|
1789 | 1789 | |
|
1790 | 1790 | In [3]: %timeit u is None |
|
1791 | 1791 | 10000000 loops, best of 3: 184 ns per loop |
|
1792 | 1792 | |
|
1793 | 1793 | In [4]: %timeit -r 4 u == None |
|
1794 | 1794 | 1000000 loops, best of 4: 242 ns per loop |
|
1795 | 1795 | |
|
1796 | 1796 | In [5]: import time |
|
1797 | 1797 | |
|
1798 | 1798 | In [6]: %timeit -n1 time.sleep(2) |
|
1799 | 1799 | 1 loops, best of 3: 2 s per loop |
|
1800 | 1800 | |
|
1801 | 1801 | |
|
1802 | 1802 | The times reported by %timeit will be slightly higher than those |
|
1803 | 1803 | reported by the timeit.py script when variables are accessed. This is |
|
1804 | 1804 | due to the fact that %timeit executes the statement in the namespace |
|
1805 | 1805 | of the shell, compared with timeit.py, which uses a single setup |
|
1806 | 1806 | statement to import function or create variables. Generally, the bias |
|
1807 | 1807 | does not matter as long as results from timeit.py are not mixed with |
|
1808 | 1808 | those from %timeit.""" |
|
1809 | 1809 | |
|
1810 | 1810 | import timeit |
|
1811 | 1811 | import math |
|
1812 | 1812 | |
|
1813 | 1813 | # XXX: Unfortunately the unicode 'micro' symbol can cause problems in |
|
1814 | 1814 | # certain terminals. Until we figure out a robust way of |
|
1815 | 1815 | # auto-detecting if the terminal can deal with it, use plain 'us' for |
|
1816 | 1816 | # microseconds. I am really NOT happy about disabling the proper |
|
1817 | 1817 | # 'micro' prefix, but crashing is worse... If anyone knows what the |
|
1818 | 1818 | # right solution for this is, I'm all ears... |
|
1819 | 1819 | # |
|
1820 | 1820 | # Note: using |
|
1821 | 1821 | # |
|
1822 | 1822 | # s = u'\xb5' |
|
1823 | 1823 | # s.encode(sys.getdefaultencoding()) |
|
1824 | 1824 | # |
|
1825 | 1825 | # is not sufficient, as I've seen terminals where that fails but |
|
1826 | 1826 | # print s |
|
1827 | 1827 | # |
|
1828 | 1828 | # succeeds |
|
1829 | 1829 | # |
|
1830 | 1830 | # See bug: https://bugs.launchpad.net/ipython/+bug/348466 |
|
1831 | 1831 | |
|
1832 | 1832 | #units = [u"s", u"ms",u'\xb5',"ns"] |
|
1833 | 1833 | units = [u"s", u"ms",u'us',"ns"] |
|
1834 | 1834 | |
|
1835 | 1835 | scaling = [1, 1e3, 1e6, 1e9] |
|
1836 | 1836 | |
|
1837 | 1837 | opts, stmt = self.parse_options(parameter_s,'n:r:tcp:', |
|
1838 | 1838 | posix=False) |
|
1839 | 1839 | if stmt == "": |
|
1840 | 1840 | return |
|
1841 | 1841 | timefunc = timeit.default_timer |
|
1842 | 1842 | number = int(getattr(opts, "n", 0)) |
|
1843 | 1843 | repeat = int(getattr(opts, "r", timeit.default_repeat)) |
|
1844 | 1844 | precision = int(getattr(opts, "p", 3)) |
|
1845 | 1845 | if hasattr(opts, "t"): |
|
1846 | 1846 | timefunc = time.time |
|
1847 | 1847 | if hasattr(opts, "c"): |
|
1848 | 1848 | timefunc = clock |
|
1849 | 1849 | |
|
1850 | 1850 | timer = timeit.Timer(timer=timefunc) |
|
1851 | 1851 | # this code has tight coupling to the inner workings of timeit.Timer, |
|
1852 | 1852 | # but is there a better way to achieve that the code stmt has access |
|
1853 | 1853 | # to the shell namespace? |
|
1854 | 1854 | |
|
1855 | 1855 | src = timeit.template % {'stmt': timeit.reindent(stmt, 8), |
|
1856 | 1856 | 'setup': "pass"} |
|
1857 | 1857 | # Track compilation time so it can be reported if too long |
|
1858 | 1858 | # Minimum time above which compilation time will be reported |
|
1859 | 1859 | tc_min = 0.1 |
|
1860 | 1860 | |
|
1861 | 1861 | t0 = clock() |
|
1862 | 1862 | code = compile(src, "<magic-timeit>", "exec") |
|
1863 | 1863 | tc = clock()-t0 |
|
1864 | 1864 | |
|
1865 | 1865 | ns = {} |
|
1866 | 1866 | exec code in self.shell.user_ns, ns |
|
1867 | 1867 | timer.inner = ns["inner"] |
|
1868 | 1868 | |
|
1869 | 1869 | if number == 0: |
|
1870 | 1870 | # determine number so that 0.2 <= total time < 2.0 |
|
1871 | 1871 | number = 1 |
|
1872 | 1872 | for i in range(1, 10): |
|
1873 | 1873 | if timer.timeit(number) >= 0.2: |
|
1874 | 1874 | break |
|
1875 | 1875 | number *= 10 |
|
1876 | 1876 | |
|
1877 | 1877 | best = min(timer.repeat(repeat, number)) / number |
|
1878 | 1878 | |
|
1879 | 1879 | if best > 0.0: |
|
1880 | 1880 | order = min(-int(math.floor(math.log10(best)) // 3), 3) |
|
1881 | 1881 | else: |
|
1882 | 1882 | order = 3 |
|
1883 | 1883 | print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat, |
|
1884 | 1884 | precision, |
|
1885 | 1885 | best * scaling[order], |
|
1886 | 1886 | units[order]) |
|
1887 | 1887 | if tc > tc_min: |
|
1888 | 1888 | print "Compiler time: %.2f s" % tc |
|
1889 | 1889 | |
|
1890 | 1890 | @testdec.skip_doctest |
|
1891 | 1891 | def magic_time(self,parameter_s = ''): |
|
1892 | 1892 | """Time execution of a Python statement or expression. |
|
1893 | 1893 | |
|
1894 | 1894 | The CPU and wall clock times are printed, and the value of the |
|
1895 | 1895 | expression (if any) is returned. Note that under Win32, system time |
|
1896 | 1896 | is always reported as 0, since it can not be measured. |
|
1897 | 1897 | |
|
1898 | 1898 | This function provides very basic timing functionality. In Python |
|
1899 | 1899 | 2.3, the timeit module offers more control and sophistication, so this |
|
1900 | 1900 | could be rewritten to use it (patches welcome). |
|
1901 | 1901 | |
|
1902 | 1902 | Some examples: |
|
1903 | 1903 | |
|
1904 | 1904 | In [1]: time 2**128 |
|
1905 | 1905 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1906 | 1906 | Wall time: 0.00 |
|
1907 | 1907 | Out[1]: 340282366920938463463374607431768211456L |
|
1908 | 1908 | |
|
1909 | 1909 | In [2]: n = 1000000 |
|
1910 | 1910 | |
|
1911 | 1911 | In [3]: time sum(range(n)) |
|
1912 | 1912 | CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s |
|
1913 | 1913 | Wall time: 1.37 |
|
1914 | 1914 | Out[3]: 499999500000L |
|
1915 | 1915 | |
|
1916 | 1916 | In [4]: time print 'hello world' |
|
1917 | 1917 | hello world |
|
1918 | 1918 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1919 | 1919 | Wall time: 0.00 |
|
1920 | 1920 | |
|
1921 | 1921 | Note that the time needed by Python to compile the given expression |
|
1922 | 1922 | will be reported if it is more than 0.1s. In this example, the |
|
1923 | 1923 | actual exponentiation is done by Python at compilation time, so while |
|
1924 | 1924 | the expression can take a noticeable amount of time to compute, that |
|
1925 | 1925 | time is purely due to the compilation: |
|
1926 | 1926 | |
|
1927 | 1927 | In [5]: time 3**9999; |
|
1928 | 1928 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1929 | 1929 | Wall time: 0.00 s |
|
1930 | 1930 | |
|
1931 | 1931 | In [6]: time 3**999999; |
|
1932 | 1932 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1933 | 1933 | Wall time: 0.00 s |
|
1934 | 1934 | Compiler : 0.78 s |
|
1935 | 1935 | """ |
|
1936 | 1936 | |
|
1937 | 1937 | # fail immediately if the given expression can't be compiled |
|
1938 | 1938 | |
|
1939 | 1939 | expr = self.shell.prefilter(parameter_s,False) |
|
1940 | 1940 | |
|
1941 | 1941 | # Minimum time above which compilation time will be reported |
|
1942 | 1942 | tc_min = 0.1 |
|
1943 | 1943 | |
|
1944 | 1944 | try: |
|
1945 | 1945 | mode = 'eval' |
|
1946 | 1946 | t0 = clock() |
|
1947 | 1947 | code = compile(expr,'<timed eval>',mode) |
|
1948 | 1948 | tc = clock()-t0 |
|
1949 | 1949 | except SyntaxError: |
|
1950 | 1950 | mode = 'exec' |
|
1951 | 1951 | t0 = clock() |
|
1952 | 1952 | code = compile(expr,'<timed exec>',mode) |
|
1953 | 1953 | tc = clock()-t0 |
|
1954 | 1954 | # skew measurement as little as possible |
|
1955 | 1955 | glob = self.shell.user_ns |
|
1956 | 1956 | clk = clock2 |
|
1957 | 1957 | wtime = time.time |
|
1958 | 1958 | # time execution |
|
1959 | 1959 | wall_st = wtime() |
|
1960 | 1960 | if mode=='eval': |
|
1961 | 1961 | st = clk() |
|
1962 | 1962 | out = eval(code,glob) |
|
1963 | 1963 | end = clk() |
|
1964 | 1964 | else: |
|
1965 | 1965 | st = clk() |
|
1966 | 1966 | exec code in glob |
|
1967 | 1967 | end = clk() |
|
1968 | 1968 | out = None |
|
1969 | 1969 | wall_end = wtime() |
|
1970 | 1970 | # Compute actual times and report |
|
1971 | 1971 | wall_time = wall_end-wall_st |
|
1972 | 1972 | cpu_user = end[0]-st[0] |
|
1973 | 1973 | cpu_sys = end[1]-st[1] |
|
1974 | 1974 | cpu_tot = cpu_user+cpu_sys |
|
1975 | 1975 | print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \ |
|
1976 | 1976 | (cpu_user,cpu_sys,cpu_tot) |
|
1977 | 1977 | print "Wall time: %.2f s" % wall_time |
|
1978 | 1978 | if tc > tc_min: |
|
1979 | 1979 | print "Compiler : %.2f s" % tc |
|
1980 | 1980 | return out |
|
1981 | 1981 | |
|
1982 | 1982 | @testdec.skip_doctest |
|
1983 | 1983 | def magic_macro(self,parameter_s = ''): |
|
1984 | 1984 | """Define a set of input lines as a macro for future re-execution. |
|
1985 | 1985 | |
|
1986 | 1986 | Usage:\\ |
|
1987 | 1987 | %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ... |
|
1988 | 1988 | |
|
1989 | 1989 | Options: |
|
1990 | 1990 | |
|
1991 | 1991 | -r: use 'raw' input. By default, the 'processed' history is used, |
|
1992 | 1992 | so that magics are loaded in their transformed version to valid |
|
1993 | 1993 | Python. If this option is given, the raw input as typed as the |
|
1994 | 1994 | command line is used instead. |
|
1995 | 1995 | |
|
1996 | 1996 | This will define a global variable called `name` which is a string |
|
1997 | 1997 | made of joining the slices and lines you specify (n1,n2,... numbers |
|
1998 | 1998 | above) from your input history into a single string. This variable |
|
1999 | 1999 | acts like an automatic function which re-executes those lines as if |
|
2000 | 2000 | you had typed them. You just type 'name' at the prompt and the code |
|
2001 | 2001 | executes. |
|
2002 | 2002 | |
|
2003 | 2003 | The notation for indicating number ranges is: n1-n2 means 'use line |
|
2004 | 2004 | numbers n1,...n2' (the endpoint is included). That is, '5-7' means |
|
2005 | 2005 | using the lines numbered 5,6 and 7. |
|
2006 | 2006 | |
|
2007 | 2007 | Note: as a 'hidden' feature, you can also use traditional python slice |
|
2008 | 2008 | notation, where N:M means numbers N through M-1. |
|
2009 | 2009 | |
|
2010 | 2010 | For example, if your history contains (%hist prints it): |
|
2011 | 2011 | |
|
2012 | 2012 | 44: x=1 |
|
2013 | 2013 | 45: y=3 |
|
2014 | 2014 | 46: z=x+y |
|
2015 | 2015 | 47: print x |
|
2016 | 2016 | 48: a=5 |
|
2017 | 2017 | 49: print 'x',x,'y',y |
|
2018 | 2018 | |
|
2019 | 2019 | you can create a macro with lines 44 through 47 (included) and line 49 |
|
2020 | 2020 | called my_macro with: |
|
2021 | 2021 | |
|
2022 | 2022 | In [55]: %macro my_macro 44-47 49 |
|
2023 | 2023 | |
|
2024 | 2024 | Now, typing `my_macro` (without quotes) will re-execute all this code |
|
2025 | 2025 | in one pass. |
|
2026 | 2026 | |
|
2027 | 2027 | You don't need to give the line-numbers in order, and any given line |
|
2028 | 2028 | number can appear multiple times. You can assemble macros with any |
|
2029 | 2029 | lines from your input history in any order. |
|
2030 | 2030 | |
|
2031 | 2031 | The macro is a simple object which holds its value in an attribute, |
|
2032 | 2032 | but IPython's display system checks for macros and executes them as |
|
2033 | 2033 | code instead of printing them when you type their name. |
|
2034 | 2034 | |
|
2035 | 2035 | You can view a macro's contents by explicitly printing it with: |
|
2036 | 2036 | |
|
2037 | 2037 | 'print macro_name'. |
|
2038 | 2038 | |
|
2039 | 2039 | For one-off cases which DON'T contain magic function calls in them you |
|
2040 | 2040 | can obtain similar results by explicitly executing slices from your |
|
2041 | 2041 | input history with: |
|
2042 | 2042 | |
|
2043 | 2043 | In [60]: exec In[44:48]+In[49]""" |
|
2044 | 2044 | |
|
2045 | 2045 | opts,args = self.parse_options(parameter_s,'r',mode='list') |
|
2046 | 2046 | if not args: |
|
2047 | 2047 | macs = [k for k,v in self.shell.user_ns.items() if isinstance(v, Macro)] |
|
2048 | 2048 | macs.sort() |
|
2049 | 2049 | return macs |
|
2050 | 2050 | if len(args) == 1: |
|
2051 | 2051 | raise UsageError( |
|
2052 | 2052 | "%macro insufficient args; usage '%macro name n1-n2 n3-4...") |
|
2053 | 2053 | name,ranges = args[0], args[1:] |
|
2054 | 2054 | |
|
2055 | 2055 | #print 'rng',ranges # dbg |
|
2056 | 2056 | lines = self.extract_input_slices(ranges,opts.has_key('r')) |
|
2057 | 2057 | macro = Macro(lines) |
|
2058 | 2058 | self.shell.define_macro(name, macro) |
|
2059 | 2059 | print 'Macro `%s` created. To execute, type its name (without quotes).' % name |
|
2060 | 2060 | print 'Macro contents:' |
|
2061 | 2061 | print macro, |
|
2062 | 2062 | |
|
2063 | 2063 | def magic_save(self,parameter_s = ''): |
|
2064 | 2064 | """Save a set of lines to a given filename. |
|
2065 | 2065 | |
|
2066 | 2066 | Usage:\\ |
|
2067 | 2067 | %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ... |
|
2068 | 2068 | |
|
2069 | 2069 | Options: |
|
2070 | 2070 | |
|
2071 | 2071 | -r: use 'raw' input. By default, the 'processed' history is used, |
|
2072 | 2072 | so that magics are loaded in their transformed version to valid |
|
2073 | 2073 | Python. If this option is given, the raw input as typed as the |
|
2074 | 2074 | command line is used instead. |
|
2075 | 2075 | |
|
2076 | 2076 | This function uses the same syntax as %macro for line extraction, but |
|
2077 | 2077 | instead of creating a macro it saves the resulting string to the |
|
2078 | 2078 | filename you specify. |
|
2079 | 2079 | |
|
2080 | 2080 | It adds a '.py' extension to the file if you don't do so yourself, and |
|
2081 | 2081 | it asks for confirmation before overwriting existing files.""" |
|
2082 | 2082 | |
|
2083 | 2083 | opts,args = self.parse_options(parameter_s,'r',mode='list') |
|
2084 | 2084 | fname,ranges = args[0], args[1:] |
|
2085 | 2085 | if not fname.endswith('.py'): |
|
2086 | 2086 | fname += '.py' |
|
2087 | 2087 | if os.path.isfile(fname): |
|
2088 | 2088 | ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname) |
|
2089 | 2089 | if ans.lower() not in ['y','yes']: |
|
2090 | 2090 | print 'Operation cancelled.' |
|
2091 | 2091 | return |
|
2092 | 2092 | cmds = ''.join(self.extract_input_slices(ranges,opts.has_key('r'))) |
|
2093 | 2093 | f = file(fname,'w') |
|
2094 | 2094 | f.write(cmds) |
|
2095 | 2095 | f.close() |
|
2096 | 2096 | print 'The following commands were written to file `%s`:' % fname |
|
2097 | 2097 | print cmds |
|
2098 | 2098 | |
|
2099 | 2099 | def _edit_macro(self,mname,macro): |
|
2100 | 2100 | """open an editor with the macro data in a file""" |
|
2101 | 2101 | filename = self.shell.mktempfile(macro.value) |
|
2102 | 2102 | self.shell.hooks.editor(filename) |
|
2103 | 2103 | |
|
2104 | 2104 | # and make a new macro object, to replace the old one |
|
2105 | 2105 | mfile = open(filename) |
|
2106 | 2106 | mvalue = mfile.read() |
|
2107 | 2107 | mfile.close() |
|
2108 | 2108 | self.shell.user_ns[mname] = Macro(mvalue) |
|
2109 | 2109 | |
|
2110 | 2110 | def magic_ed(self,parameter_s=''): |
|
2111 | 2111 | """Alias to %edit.""" |
|
2112 | 2112 | return self.magic_edit(parameter_s) |
|
2113 | 2113 | |
|
2114 | 2114 | @testdec.skip_doctest |
|
2115 | 2115 | def magic_edit(self,parameter_s='',last_call=['','']): |
|
2116 | 2116 | """Bring up an editor and execute the resulting code. |
|
2117 | 2117 | |
|
2118 | 2118 | Usage: |
|
2119 | 2119 | %edit [options] [args] |
|
2120 | 2120 | |
|
2121 | 2121 | %edit runs IPython's editor hook. The default version of this hook is |
|
2122 | 2122 | set to call the __IPYTHON__.rc.editor command. This is read from your |
|
2123 | 2123 | environment variable $EDITOR. If this isn't found, it will default to |
|
2124 | 2124 | vi under Linux/Unix and to notepad under Windows. See the end of this |
|
2125 | 2125 | docstring for how to change the editor hook. |
|
2126 | 2126 | |
|
2127 | 2127 | You can also set the value of this editor via the command line option |
|
2128 | 2128 | '-editor' or in your ipythonrc file. This is useful if you wish to use |
|
2129 | 2129 | specifically for IPython an editor different from your typical default |
|
2130 | 2130 | (and for Windows users who typically don't set environment variables). |
|
2131 | 2131 | |
|
2132 | 2132 | This command allows you to conveniently edit multi-line code right in |
|
2133 | 2133 | your IPython session. |
|
2134 | 2134 | |
|
2135 | 2135 | If called without arguments, %edit opens up an empty editor with a |
|
2136 | 2136 | temporary file and will execute the contents of this file when you |
|
2137 | 2137 | close it (don't forget to save it!). |
|
2138 | 2138 | |
|
2139 | 2139 | |
|
2140 | 2140 | Options: |
|
2141 | 2141 | |
|
2142 | 2142 | -n <number>: open the editor at a specified line number. By default, |
|
2143 | 2143 | the IPython editor hook uses the unix syntax 'editor +N filename', but |
|
2144 | 2144 | you can configure this by providing your own modified hook if your |
|
2145 | 2145 | favorite editor supports line-number specifications with a different |
|
2146 | 2146 | syntax. |
|
2147 | 2147 | |
|
2148 | 2148 | -p: this will call the editor with the same data as the previous time |
|
2149 | 2149 | it was used, regardless of how long ago (in your current session) it |
|
2150 | 2150 | was. |
|
2151 | 2151 | |
|
2152 | 2152 | -r: use 'raw' input. This option only applies to input taken from the |
|
2153 | 2153 | user's history. By default, the 'processed' history is used, so that |
|
2154 | 2154 | magics are loaded in their transformed version to valid Python. If |
|
2155 | 2155 | this option is given, the raw input as typed as the command line is |
|
2156 | 2156 | used instead. When you exit the editor, it will be executed by |
|
2157 | 2157 | IPython's own processor. |
|
2158 | 2158 | |
|
2159 | 2159 | -x: do not execute the edited code immediately upon exit. This is |
|
2160 | 2160 | mainly useful if you are editing programs which need to be called with |
|
2161 | 2161 | command line arguments, which you can then do using %run. |
|
2162 | 2162 | |
|
2163 | 2163 | |
|
2164 | 2164 | Arguments: |
|
2165 | 2165 | |
|
2166 | 2166 | If arguments are given, the following possibilites exist: |
|
2167 | 2167 | |
|
2168 | 2168 | - The arguments are numbers or pairs of colon-separated numbers (like |
|
2169 | 2169 | 1 4:8 9). These are interpreted as lines of previous input to be |
|
2170 | 2170 | loaded into the editor. The syntax is the same of the %macro command. |
|
2171 | 2171 | |
|
2172 | 2172 | - If the argument doesn't start with a number, it is evaluated as a |
|
2173 | 2173 | variable and its contents loaded into the editor. You can thus edit |
|
2174 | 2174 | any string which contains python code (including the result of |
|
2175 | 2175 | previous edits). |
|
2176 | 2176 | |
|
2177 | 2177 | - If the argument is the name of an object (other than a string), |
|
2178 | 2178 | IPython will try to locate the file where it was defined and open the |
|
2179 | 2179 | editor at the point where it is defined. You can use `%edit function` |
|
2180 | 2180 | to load an editor exactly at the point where 'function' is defined, |
|
2181 | 2181 | edit it and have the file be executed automatically. |
|
2182 | 2182 | |
|
2183 | 2183 | If the object is a macro (see %macro for details), this opens up your |
|
2184 | 2184 | specified editor with a temporary file containing the macro's data. |
|
2185 | 2185 | Upon exit, the macro is reloaded with the contents of the file. |
|
2186 | 2186 | |
|
2187 | 2187 | Note: opening at an exact line is only supported under Unix, and some |
|
2188 | 2188 | editors (like kedit and gedit up to Gnome 2.8) do not understand the |
|
2189 | 2189 | '+NUMBER' parameter necessary for this feature. Good editors like |
|
2190 | 2190 | (X)Emacs, vi, jed, pico and joe all do. |
|
2191 | 2191 | |
|
2192 | 2192 | - If the argument is not found as a variable, IPython will look for a |
|
2193 | 2193 | file with that name (adding .py if necessary) and load it into the |
|
2194 | 2194 | editor. It will execute its contents with execfile() when you exit, |
|
2195 | 2195 | loading any code in the file into your interactive namespace. |
|
2196 | 2196 | |
|
2197 | 2197 | After executing your code, %edit will return as output the code you |
|
2198 | 2198 | typed in the editor (except when it was an existing file). This way |
|
2199 | 2199 | you can reload the code in further invocations of %edit as a variable, |
|
2200 | 2200 | via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of |
|
2201 | 2201 | the output. |
|
2202 | 2202 | |
|
2203 | 2203 | Note that %edit is also available through the alias %ed. |
|
2204 | 2204 | |
|
2205 | 2205 | This is an example of creating a simple function inside the editor and |
|
2206 | 2206 | then modifying it. First, start up the editor: |
|
2207 | 2207 | |
|
2208 | 2208 | In [1]: ed |
|
2209 | 2209 | Editing... done. Executing edited code... |
|
2210 | 2210 | Out[1]: 'def foo():n print "foo() was defined in an editing session"n' |
|
2211 | 2211 | |
|
2212 | 2212 | We can then call the function foo(): |
|
2213 | 2213 | |
|
2214 | 2214 | In [2]: foo() |
|
2215 | 2215 | foo() was defined in an editing session |
|
2216 | 2216 | |
|
2217 | 2217 | Now we edit foo. IPython automatically loads the editor with the |
|
2218 | 2218 | (temporary) file where foo() was previously defined: |
|
2219 | 2219 | |
|
2220 | 2220 | In [3]: ed foo |
|
2221 | 2221 | Editing... done. Executing edited code... |
|
2222 | 2222 | |
|
2223 | 2223 | And if we call foo() again we get the modified version: |
|
2224 | 2224 | |
|
2225 | 2225 | In [4]: foo() |
|
2226 | 2226 | foo() has now been changed! |
|
2227 | 2227 | |
|
2228 | 2228 | Here is an example of how to edit a code snippet successive |
|
2229 | 2229 | times. First we call the editor: |
|
2230 | 2230 | |
|
2231 | 2231 | In [5]: ed |
|
2232 | 2232 | Editing... done. Executing edited code... |
|
2233 | 2233 | hello |
|
2234 | 2234 | Out[5]: "print 'hello'n" |
|
2235 | 2235 | |
|
2236 | 2236 | Now we call it again with the previous output (stored in _): |
|
2237 | 2237 | |
|
2238 | 2238 | In [6]: ed _ |
|
2239 | 2239 | Editing... done. Executing edited code... |
|
2240 | 2240 | hello world |
|
2241 | 2241 | Out[6]: "print 'hello world'n" |
|
2242 | 2242 | |
|
2243 | 2243 | Now we call it with the output #8 (stored in _8, also as Out[8]): |
|
2244 | 2244 | |
|
2245 | 2245 | In [7]: ed _8 |
|
2246 | 2246 | Editing... done. Executing edited code... |
|
2247 | 2247 | hello again |
|
2248 | 2248 | Out[7]: "print 'hello again'n" |
|
2249 | 2249 | |
|
2250 | 2250 | |
|
2251 | 2251 | Changing the default editor hook: |
|
2252 | 2252 | |
|
2253 | 2253 | If you wish to write your own editor hook, you can put it in a |
|
2254 | 2254 | configuration file which you load at startup time. The default hook |
|
2255 | 2255 | is defined in the IPython.core.hooks module, and you can use that as a |
|
2256 | 2256 | starting example for further modifications. That file also has |
|
2257 | 2257 | general instructions on how to set a new hook for use once you've |
|
2258 | 2258 | defined it.""" |
|
2259 | 2259 | |
|
2260 | 2260 | # FIXME: This function has become a convoluted mess. It needs a |
|
2261 | 2261 | # ground-up rewrite with clean, simple logic. |
|
2262 | 2262 | |
|
2263 | 2263 | def make_filename(arg): |
|
2264 | 2264 | "Make a filename from the given args" |
|
2265 | 2265 | try: |
|
2266 | 2266 | filename = get_py_filename(arg) |
|
2267 | 2267 | except IOError: |
|
2268 | 2268 | if args.endswith('.py'): |
|
2269 | 2269 | filename = arg |
|
2270 | 2270 | else: |
|
2271 | 2271 | filename = None |
|
2272 | 2272 | return filename |
|
2273 | 2273 | |
|
2274 | 2274 | # custom exceptions |
|
2275 | 2275 | class DataIsObject(Exception): pass |
|
2276 | 2276 | |
|
2277 | 2277 | opts,args = self.parse_options(parameter_s,'prxn:') |
|
2278 | 2278 | # Set a few locals from the options for convenience: |
|
2279 | 2279 | opts_p = opts.has_key('p') |
|
2280 | 2280 | opts_r = opts.has_key('r') |
|
2281 | 2281 | |
|
2282 | 2282 | # Default line number value |
|
2283 | 2283 | lineno = opts.get('n',None) |
|
2284 | 2284 | |
|
2285 | 2285 | if opts_p: |
|
2286 | 2286 | args = '_%s' % last_call[0] |
|
2287 | 2287 | if not self.shell.user_ns.has_key(args): |
|
2288 | 2288 | args = last_call[1] |
|
2289 | 2289 | |
|
2290 | 2290 | # use last_call to remember the state of the previous call, but don't |
|
2291 | 2291 | # let it be clobbered by successive '-p' calls. |
|
2292 | 2292 | try: |
|
2293 | 2293 | last_call[0] = self.shell.outputcache.prompt_count |
|
2294 | 2294 | if not opts_p: |
|
2295 | 2295 | last_call[1] = parameter_s |
|
2296 | 2296 | except: |
|
2297 | 2297 | pass |
|
2298 | 2298 | |
|
2299 | 2299 | # by default this is done with temp files, except when the given |
|
2300 | 2300 | # arg is a filename |
|
2301 | 2301 | use_temp = 1 |
|
2302 | 2302 | |
|
2303 | 2303 | if re.match(r'\d',args): |
|
2304 | 2304 | # Mode where user specifies ranges of lines, like in %macro. |
|
2305 | 2305 | # This means that you can't edit files whose names begin with |
|
2306 | 2306 | # numbers this way. Tough. |
|
2307 | 2307 | ranges = args.split() |
|
2308 | 2308 | data = ''.join(self.extract_input_slices(ranges,opts_r)) |
|
2309 | 2309 | elif args.endswith('.py'): |
|
2310 | 2310 | filename = make_filename(args) |
|
2311 | 2311 | data = '' |
|
2312 | 2312 | use_temp = 0 |
|
2313 | 2313 | elif args: |
|
2314 | 2314 | try: |
|
2315 | 2315 | # Load the parameter given as a variable. If not a string, |
|
2316 | 2316 | # process it as an object instead (below) |
|
2317 | 2317 | |
|
2318 | 2318 | #print '*** args',args,'type',type(args) # dbg |
|
2319 | 2319 | data = eval(args,self.shell.user_ns) |
|
2320 | 2320 | if not type(data) in StringTypes: |
|
2321 | 2321 | raise DataIsObject |
|
2322 | 2322 | |
|
2323 | 2323 | except (NameError,SyntaxError): |
|
2324 | 2324 | # given argument is not a variable, try as a filename |
|
2325 | 2325 | filename = make_filename(args) |
|
2326 | 2326 | if filename is None: |
|
2327 | 2327 | warn("Argument given (%s) can't be found as a variable " |
|
2328 | 2328 | "or as a filename." % args) |
|
2329 | 2329 | return |
|
2330 | 2330 | |
|
2331 | 2331 | data = '' |
|
2332 | 2332 | use_temp = 0 |
|
2333 | 2333 | except DataIsObject: |
|
2334 | 2334 | |
|
2335 | 2335 | # macros have a special edit function |
|
2336 | 2336 | if isinstance(data,Macro): |
|
2337 | 2337 | self._edit_macro(args,data) |
|
2338 | 2338 | return |
|
2339 | 2339 | |
|
2340 | 2340 | # For objects, try to edit the file where they are defined |
|
2341 | 2341 | try: |
|
2342 | 2342 | filename = inspect.getabsfile(data) |
|
2343 | 2343 | if 'fakemodule' in filename.lower() and inspect.isclass(data): |
|
2344 | 2344 | # class created by %edit? Try to find source |
|
2345 | 2345 | # by looking for method definitions instead, the |
|
2346 | 2346 | # __module__ in those classes is FakeModule. |
|
2347 | 2347 | attrs = [getattr(data, aname) for aname in dir(data)] |
|
2348 | 2348 | for attr in attrs: |
|
2349 | 2349 | if not inspect.ismethod(attr): |
|
2350 | 2350 | continue |
|
2351 | 2351 | filename = inspect.getabsfile(attr) |
|
2352 | 2352 | if filename and 'fakemodule' not in filename.lower(): |
|
2353 | 2353 | # change the attribute to be the edit target instead |
|
2354 | 2354 | data = attr |
|
2355 | 2355 | break |
|
2356 | 2356 | |
|
2357 | 2357 | datafile = 1 |
|
2358 | 2358 | except TypeError: |
|
2359 | 2359 | filename = make_filename(args) |
|
2360 | 2360 | datafile = 1 |
|
2361 | 2361 | warn('Could not find file where `%s` is defined.\n' |
|
2362 | 2362 | 'Opening a file named `%s`' % (args,filename)) |
|
2363 | 2363 | # Now, make sure we can actually read the source (if it was in |
|
2364 | 2364 | # a temp file it's gone by now). |
|
2365 | 2365 | if datafile: |
|
2366 | 2366 | try: |
|
2367 | 2367 | if lineno is None: |
|
2368 | 2368 | lineno = inspect.getsourcelines(data)[1] |
|
2369 | 2369 | except IOError: |
|
2370 | 2370 | filename = make_filename(args) |
|
2371 | 2371 | if filename is None: |
|
2372 | 2372 | warn('The file `%s` where `%s` was defined cannot ' |
|
2373 | 2373 | 'be read.' % (filename,data)) |
|
2374 | 2374 | return |
|
2375 | 2375 | use_temp = 0 |
|
2376 | 2376 | else: |
|
2377 | 2377 | data = '' |
|
2378 | 2378 | |
|
2379 | 2379 | if use_temp: |
|
2380 | 2380 | filename = self.shell.mktempfile(data) |
|
2381 | 2381 | print 'IPython will make a temporary file named:',filename |
|
2382 | 2382 | |
|
2383 | 2383 | # do actual editing here |
|
2384 | 2384 | print 'Editing...', |
|
2385 | 2385 | sys.stdout.flush() |
|
2386 | 2386 | try: |
|
2387 | 2387 | self.shell.hooks.editor(filename,lineno) |
|
2388 | 2388 | except TryNext: |
|
2389 | 2389 | warn('Could not open editor') |
|
2390 | 2390 | return |
|
2391 | 2391 | |
|
2392 | 2392 | # XXX TODO: should this be generalized for all string vars? |
|
2393 | 2393 | # For now, this is special-cased to blocks created by cpaste |
|
2394 | 2394 | if args.strip() == 'pasted_block': |
|
2395 | 2395 | self.shell.user_ns['pasted_block'] = file_read(filename) |
|
2396 | 2396 | |
|
2397 | 2397 | if opts.has_key('x'): # -x prevents actual execution |
|
2398 | 2398 | |
|
2399 | 2399 | else: |
|
2400 | 2400 | print 'done. Executing edited code...' |
|
2401 | 2401 | if opts_r: |
|
2402 | 2402 | self.shell.runlines(file_read(filename)) |
|
2403 | 2403 | else: |
|
2404 | 2404 | self.shell.safe_execfile(filename,self.shell.user_ns, |
|
2405 | 2405 | self.shell.user_ns) |
|
2406 | 2406 | |
|
2407 | 2407 | |
|
2408 | 2408 | if use_temp: |
|
2409 | 2409 | try: |
|
2410 | 2410 | return open(filename).read() |
|
2411 | 2411 | except IOError,msg: |
|
2412 | 2412 | if msg.filename == filename: |
|
2413 | 2413 | warn('File not found. Did you forget to save?') |
|
2414 | 2414 | return |
|
2415 | 2415 | else: |
|
2416 | 2416 | self.shell.showtraceback() |
|
2417 | 2417 | |
|
2418 | 2418 | def magic_xmode(self,parameter_s = ''): |
|
2419 | 2419 | """Switch modes for the exception handlers. |
|
2420 | 2420 | |
|
2421 | 2421 | Valid modes: Plain, Context and Verbose. |
|
2422 | 2422 | |
|
2423 | 2423 | If called without arguments, acts as a toggle.""" |
|
2424 | 2424 | |
|
2425 | 2425 | def xmode_switch_err(name): |
|
2426 | 2426 | warn('Error changing %s exception modes.\n%s' % |
|
2427 | 2427 | (name,sys.exc_info()[1])) |
|
2428 | 2428 | |
|
2429 | 2429 | shell = self.shell |
|
2430 | 2430 | new_mode = parameter_s.strip().capitalize() |
|
2431 | 2431 | try: |
|
2432 | 2432 | shell.InteractiveTB.set_mode(mode=new_mode) |
|
2433 | 2433 | print 'Exception reporting mode:',shell.InteractiveTB.mode |
|
2434 | 2434 | except: |
|
2435 | 2435 | xmode_switch_err('user') |
|
2436 | 2436 | |
|
2437 | 2437 | # threaded shells use a special handler in sys.excepthook |
|
2438 | 2438 | if shell.isthreaded: |
|
2439 | 2439 | try: |
|
2440 | 2440 | shell.sys_excepthook.set_mode(mode=new_mode) |
|
2441 | 2441 | except: |
|
2442 | 2442 | xmode_switch_err('threaded') |
|
2443 | 2443 | |
|
2444 | 2444 | def magic_colors(self,parameter_s = ''): |
|
2445 | 2445 | """Switch color scheme for prompts, info system and exception handlers. |
|
2446 | 2446 | |
|
2447 | 2447 | Currently implemented schemes: NoColor, Linux, LightBG. |
|
2448 | 2448 | |
|
2449 | 2449 | Color scheme names are not case-sensitive.""" |
|
2450 | 2450 | |
|
2451 | 2451 | def color_switch_err(name): |
|
2452 | 2452 | warn('Error changing %s color schemes.\n%s' % |
|
2453 | 2453 | (name,sys.exc_info()[1])) |
|
2454 | 2454 | |
|
2455 | 2455 | |
|
2456 | 2456 | new_scheme = parameter_s.strip() |
|
2457 | 2457 | if not new_scheme: |
|
2458 | 2458 | raise UsageError( |
|
2459 | 2459 | "%colors: you must specify a color scheme. See '%colors?'") |
|
2460 | 2460 | return |
|
2461 | 2461 | # local shortcut |
|
2462 | 2462 | shell = self.shell |
|
2463 | 2463 | |
|
2464 | 2464 | import IPython.utils.rlineimpl as readline |
|
2465 | 2465 | |
|
2466 | 2466 | if not readline.have_readline and sys.platform == "win32": |
|
2467 | 2467 | msg = """\ |
|
2468 | 2468 | Proper color support under MS Windows requires the pyreadline library. |
|
2469 | 2469 | You can find it at: |
|
2470 | 2470 | http://ipython.scipy.org/moin/PyReadline/Intro |
|
2471 | 2471 | Gary's readline needs the ctypes module, from: |
|
2472 | 2472 | http://starship.python.net/crew/theller/ctypes |
|
2473 | 2473 | (Note that ctypes is already part of Python versions 2.5 and newer). |
|
2474 | 2474 | |
|
2475 | 2475 | Defaulting color scheme to 'NoColor'""" |
|
2476 | 2476 | new_scheme = 'NoColor' |
|
2477 | 2477 | warn(msg) |
|
2478 | 2478 | |
|
2479 | 2479 | # readline option is 0 |
|
2480 | 2480 | if not shell.has_readline: |
|
2481 | 2481 | new_scheme = 'NoColor' |
|
2482 | 2482 | |
|
2483 | 2483 | # Set prompt colors |
|
2484 | 2484 | try: |
|
2485 | 2485 | shell.outputcache.set_colors(new_scheme) |
|
2486 | 2486 | except: |
|
2487 | 2487 | color_switch_err('prompt') |
|
2488 | 2488 | else: |
|
2489 | 2489 | shell.colors = \ |
|
2490 | 2490 | shell.outputcache.color_table.active_scheme_name |
|
2491 | 2491 | # Set exception colors |
|
2492 | 2492 | try: |
|
2493 | 2493 | shell.InteractiveTB.set_colors(scheme = new_scheme) |
|
2494 | 2494 | shell.SyntaxTB.set_colors(scheme = new_scheme) |
|
2495 | 2495 | except: |
|
2496 | 2496 | color_switch_err('exception') |
|
2497 | 2497 | |
|
2498 | 2498 | # threaded shells use a verbose traceback in sys.excepthook |
|
2499 | 2499 | if shell.isthreaded: |
|
2500 | 2500 | try: |
|
2501 | 2501 | shell.sys_excepthook.set_colors(scheme=new_scheme) |
|
2502 | 2502 | except: |
|
2503 | 2503 | color_switch_err('system exception handler') |
|
2504 | 2504 | |
|
2505 | 2505 | # Set info (for 'object?') colors |
|
2506 | 2506 | if shell.color_info: |
|
2507 | 2507 | try: |
|
2508 | 2508 | shell.inspector.set_active_scheme(new_scheme) |
|
2509 | 2509 | except: |
|
2510 | 2510 | color_switch_err('object inspector') |
|
2511 | 2511 | else: |
|
2512 | 2512 | shell.inspector.set_active_scheme('NoColor') |
|
2513 | 2513 | |
|
2514 | 2514 | def magic_color_info(self,parameter_s = ''): |
|
2515 | 2515 | """Toggle color_info. |
|
2516 | 2516 | |
|
2517 | 2517 | The color_info configuration parameter controls whether colors are |
|
2518 | 2518 | used for displaying object details (by things like %psource, %pfile or |
|
2519 | 2519 | the '?' system). This function toggles this value with each call. |
|
2520 | 2520 | |
|
2521 | 2521 | Note that unless you have a fairly recent pager (less works better |
|
2522 | 2522 | than more) in your system, using colored object information displays |
|
2523 | 2523 | will not work properly. Test it and see.""" |
|
2524 | 2524 | |
|
2525 | 2525 | self.shell.color_info = not self.shell.color_info |
|
2526 | 2526 | self.magic_colors(self.shell.colors) |
|
2527 | 2527 | print 'Object introspection functions have now coloring:', |
|
2528 | 2528 | print ['OFF','ON'][int(self.shell.color_info)] |
|
2529 | 2529 | |
|
2530 | 2530 | def magic_Pprint(self, parameter_s=''): |
|
2531 | 2531 | """Toggle pretty printing on/off.""" |
|
2532 | 2532 | |
|
2533 | 2533 | self.shell.pprint = 1 - self.shell.pprint |
|
2534 | 2534 | print 'Pretty printing has been turned', \ |
|
2535 | 2535 | ['OFF','ON'][self.shell.pprint] |
|
2536 | 2536 | |
|
2537 | def magic_exit(self, parameter_s=''): | |
|
2538 | """Exit IPython, confirming if configured to do so. | |
|
2539 | ||
|
2540 | You can configure whether IPython asks for confirmation upon exit by | |
|
2541 | setting the confirm_exit flag in the ipythonrc file.""" | |
|
2542 | ||
|
2543 | self.shell.exit() | |
|
2544 | ||
|
2545 | def magic_quit(self, parameter_s=''): | |
|
2546 | """Exit IPython, confirming if configured to do so (like %exit)""" | |
|
2547 | ||
|
2548 | self.shell.exit() | |
|
2549 | ||
|
2550 | 2537 | def magic_Exit(self, parameter_s=''): |
|
2551 | 2538 | """Exit IPython without confirmation.""" |
|
2552 | 2539 | |
|
2553 | 2540 | self.shell.ask_exit() |
|
2554 | 2541 | |
|
2555 | 2542 | #...................................................................... |
|
2556 | 2543 | # Functions to implement unix shell-type things |
|
2557 | 2544 | |
|
2558 | 2545 | @testdec.skip_doctest |
|
2559 | 2546 | def magic_alias(self, parameter_s = ''): |
|
2560 | 2547 | """Define an alias for a system command. |
|
2561 | 2548 | |
|
2562 | 2549 | '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd' |
|
2563 | 2550 | |
|
2564 | 2551 | Then, typing 'alias_name params' will execute the system command 'cmd |
|
2565 | 2552 | params' (from your underlying operating system). |
|
2566 | 2553 | |
|
2567 | 2554 | Aliases have lower precedence than magic functions and Python normal |
|
2568 | 2555 | variables, so if 'foo' is both a Python variable and an alias, the |
|
2569 | 2556 | alias can not be executed until 'del foo' removes the Python variable. |
|
2570 | 2557 | |
|
2571 | 2558 | You can use the %l specifier in an alias definition to represent the |
|
2572 | 2559 | whole line when the alias is called. For example: |
|
2573 | 2560 | |
|
2574 | 2561 | In [2]: alias all echo "Input in brackets: <%l>" |
|
2575 | 2562 | In [3]: all hello world |
|
2576 | 2563 | Input in brackets: <hello world> |
|
2577 | 2564 | |
|
2578 | 2565 | You can also define aliases with parameters using %s specifiers (one |
|
2579 | 2566 | per parameter): |
|
2580 | 2567 | |
|
2581 | 2568 | In [1]: alias parts echo first %s second %s |
|
2582 | 2569 | In [2]: %parts A B |
|
2583 | 2570 | first A second B |
|
2584 | 2571 | In [3]: %parts A |
|
2585 | 2572 | Incorrect number of arguments: 2 expected. |
|
2586 | 2573 | parts is an alias to: 'echo first %s second %s' |
|
2587 | 2574 | |
|
2588 | 2575 | Note that %l and %s are mutually exclusive. You can only use one or |
|
2589 | 2576 | the other in your aliases. |
|
2590 | 2577 | |
|
2591 | 2578 | Aliases expand Python variables just like system calls using ! or !! |
|
2592 | 2579 | do: all expressions prefixed with '$' get expanded. For details of |
|
2593 | 2580 | the semantic rules, see PEP-215: |
|
2594 | 2581 | http://www.python.org/peps/pep-0215.html. This is the library used by |
|
2595 | 2582 | IPython for variable expansion. If you want to access a true shell |
|
2596 | 2583 | variable, an extra $ is necessary to prevent its expansion by IPython: |
|
2597 | 2584 | |
|
2598 | 2585 | In [6]: alias show echo |
|
2599 | 2586 | In [7]: PATH='A Python string' |
|
2600 | 2587 | In [8]: show $PATH |
|
2601 | 2588 | A Python string |
|
2602 | 2589 | In [9]: show $$PATH |
|
2603 | 2590 | /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:... |
|
2604 | 2591 | |
|
2605 | 2592 | You can use the alias facility to acess all of $PATH. See the %rehash |
|
2606 | 2593 | and %rehashx functions, which automatically create aliases for the |
|
2607 | 2594 | contents of your $PATH. |
|
2608 | 2595 | |
|
2609 | 2596 | If called with no parameters, %alias prints the current alias table.""" |
|
2610 | 2597 | |
|
2611 | 2598 | par = parameter_s.strip() |
|
2612 | 2599 | if not par: |
|
2613 | 2600 | stored = self.db.get('stored_aliases', {} ) |
|
2614 | 2601 | aliases = sorted(self.shell.alias_manager.aliases) |
|
2615 | 2602 | # for k, v in stored: |
|
2616 | 2603 | # atab.append(k, v[0]) |
|
2617 | 2604 | |
|
2618 | 2605 | print "Total number of aliases:", len(aliases) |
|
2619 | 2606 | return aliases |
|
2620 | 2607 | |
|
2621 | 2608 | # Now try to define a new one |
|
2622 | 2609 | try: |
|
2623 | 2610 | alias,cmd = par.split(None, 1) |
|
2624 | 2611 | except: |
|
2625 | 2612 | print oinspect.getdoc(self.magic_alias) |
|
2626 | 2613 | else: |
|
2627 | 2614 | self.shell.alias_manager.soft_define_alias(alias, cmd) |
|
2628 | 2615 | # end magic_alias |
|
2629 | 2616 | |
|
2630 | 2617 | def magic_unalias(self, parameter_s = ''): |
|
2631 | 2618 | """Remove an alias""" |
|
2632 | 2619 | |
|
2633 | 2620 | aname = parameter_s.strip() |
|
2634 | 2621 | self.shell.alias_manager.undefine_alias(aname) |
|
2635 | 2622 | stored = self.db.get('stored_aliases', {} ) |
|
2636 | 2623 | if aname in stored: |
|
2637 | 2624 | print "Removing %stored alias",aname |
|
2638 | 2625 | del stored[aname] |
|
2639 | 2626 | self.db['stored_aliases'] = stored |
|
2640 | 2627 | |
|
2641 | 2628 | |
|
2642 | 2629 | def magic_rehashx(self, parameter_s = ''): |
|
2643 | 2630 | """Update the alias table with all executable files in $PATH. |
|
2644 | 2631 | |
|
2645 | 2632 | This version explicitly checks that every entry in $PATH is a file |
|
2646 | 2633 | with execute access (os.X_OK), so it is much slower than %rehash. |
|
2647 | 2634 | |
|
2648 | 2635 | Under Windows, it checks executability as a match agains a |
|
2649 | 2636 | '|'-separated string of extensions, stored in the IPython config |
|
2650 | 2637 | variable win_exec_ext. This defaults to 'exe|com|bat'. |
|
2651 | 2638 | |
|
2652 | 2639 | This function also resets the root module cache of module completer, |
|
2653 | 2640 | used on slow filesystems. |
|
2654 | 2641 | """ |
|
2655 | 2642 | from IPython.core.alias import InvalidAliasError |
|
2656 | 2643 | |
|
2657 | 2644 | # for the benefit of module completer in ipy_completers.py |
|
2658 | 2645 | del self.db['rootmodules'] |
|
2659 | 2646 | |
|
2660 | 2647 | path = [os.path.abspath(os.path.expanduser(p)) for p in |
|
2661 | 2648 | os.environ.get('PATH','').split(os.pathsep)] |
|
2662 | 2649 | path = filter(os.path.isdir,path) |
|
2663 | 2650 | |
|
2664 | 2651 | syscmdlist = [] |
|
2665 | 2652 | # Now define isexec in a cross platform manner. |
|
2666 | 2653 | if os.name == 'posix': |
|
2667 | 2654 | isexec = lambda fname:os.path.isfile(fname) and \ |
|
2668 | 2655 | os.access(fname,os.X_OK) |
|
2669 | 2656 | else: |
|
2670 | 2657 | try: |
|
2671 | 2658 | winext = os.environ['pathext'].replace(';','|').replace('.','') |
|
2672 | 2659 | except KeyError: |
|
2673 | 2660 | winext = 'exe|com|bat|py' |
|
2674 | 2661 | if 'py' not in winext: |
|
2675 | 2662 | winext += '|py' |
|
2676 | 2663 | execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE) |
|
2677 | 2664 | isexec = lambda fname:os.path.isfile(fname) and execre.match(fname) |
|
2678 | 2665 | savedir = os.getcwd() |
|
2679 | 2666 | |
|
2680 | 2667 | # Now walk the paths looking for executables to alias. |
|
2681 | 2668 | try: |
|
2682 | 2669 | # write the whole loop for posix/Windows so we don't have an if in |
|
2683 | 2670 | # the innermost part |
|
2684 | 2671 | if os.name == 'posix': |
|
2685 | 2672 | for pdir in path: |
|
2686 | 2673 | os.chdir(pdir) |
|
2687 | 2674 | for ff in os.listdir(pdir): |
|
2688 | 2675 | if isexec(ff): |
|
2689 | 2676 | try: |
|
2690 | 2677 | # Removes dots from the name since ipython |
|
2691 | 2678 | # will assume names with dots to be python. |
|
2692 | 2679 | self.shell.alias_manager.define_alias( |
|
2693 | 2680 | ff.replace('.',''), ff) |
|
2694 | 2681 | except InvalidAliasError: |
|
2695 | 2682 | pass |
|
2696 | 2683 | else: |
|
2697 | 2684 | syscmdlist.append(ff) |
|
2698 | 2685 | else: |
|
2699 | 2686 | for pdir in path: |
|
2700 | 2687 | os.chdir(pdir) |
|
2701 | 2688 | for ff in os.listdir(pdir): |
|
2702 | 2689 | base, ext = os.path.splitext(ff) |
|
2703 | 2690 | if isexec(ff) and base.lower() not in self.shell.no_alias: |
|
2704 | 2691 | if ext.lower() == '.exe': |
|
2705 | 2692 | ff = base |
|
2706 | 2693 | try: |
|
2707 | 2694 | # Removes dots from the name since ipython |
|
2708 | 2695 | # will assume names with dots to be python. |
|
2709 | 2696 | self.shell.alias_manager.define_alias( |
|
2710 | 2697 | base.lower().replace('.',''), ff) |
|
2711 | 2698 | except InvalidAliasError: |
|
2712 | 2699 | pass |
|
2713 | 2700 | syscmdlist.append(ff) |
|
2714 | 2701 | db = self.db |
|
2715 | 2702 | db['syscmdlist'] = syscmdlist |
|
2716 | 2703 | finally: |
|
2717 | 2704 | os.chdir(savedir) |
|
2718 | 2705 | |
|
2719 | 2706 | def magic_pwd(self, parameter_s = ''): |
|
2720 | 2707 | """Return the current working directory path.""" |
|
2721 | 2708 | return os.getcwd() |
|
2722 | 2709 | |
|
2723 | 2710 | def magic_cd(self, parameter_s=''): |
|
2724 | 2711 | """Change the current working directory. |
|
2725 | 2712 | |
|
2726 | 2713 | This command automatically maintains an internal list of directories |
|
2727 | 2714 | you visit during your IPython session, in the variable _dh. The |
|
2728 | 2715 | command %dhist shows this history nicely formatted. You can also |
|
2729 | 2716 | do 'cd -<tab>' to see directory history conveniently. |
|
2730 | 2717 | |
|
2731 | 2718 | Usage: |
|
2732 | 2719 | |
|
2733 | 2720 | cd 'dir': changes to directory 'dir'. |
|
2734 | 2721 | |
|
2735 | 2722 | cd -: changes to the last visited directory. |
|
2736 | 2723 | |
|
2737 | 2724 | cd -<n>: changes to the n-th directory in the directory history. |
|
2738 | 2725 | |
|
2739 | 2726 | cd --foo: change to directory that matches 'foo' in history |
|
2740 | 2727 | |
|
2741 | 2728 | cd -b <bookmark_name>: jump to a bookmark set by %bookmark |
|
2742 | 2729 | (note: cd <bookmark_name> is enough if there is no |
|
2743 | 2730 | directory <bookmark_name>, but a bookmark with the name exists.) |
|
2744 | 2731 | 'cd -b <tab>' allows you to tab-complete bookmark names. |
|
2745 | 2732 | |
|
2746 | 2733 | Options: |
|
2747 | 2734 | |
|
2748 | 2735 | -q: quiet. Do not print the working directory after the cd command is |
|
2749 | 2736 | executed. By default IPython's cd command does print this directory, |
|
2750 | 2737 | since the default prompts do not display path information. |
|
2751 | 2738 | |
|
2752 | 2739 | Note that !cd doesn't work for this purpose because the shell where |
|
2753 | 2740 | !command runs is immediately discarded after executing 'command'.""" |
|
2754 | 2741 | |
|
2755 | 2742 | parameter_s = parameter_s.strip() |
|
2756 | 2743 | #bkms = self.shell.persist.get("bookmarks",{}) |
|
2757 | 2744 | |
|
2758 | 2745 | oldcwd = os.getcwd() |
|
2759 | 2746 | numcd = re.match(r'(-)(\d+)$',parameter_s) |
|
2760 | 2747 | # jump in directory history by number |
|
2761 | 2748 | if numcd: |
|
2762 | 2749 | nn = int(numcd.group(2)) |
|
2763 | 2750 | try: |
|
2764 | 2751 | ps = self.shell.user_ns['_dh'][nn] |
|
2765 | 2752 | except IndexError: |
|
2766 | 2753 | print 'The requested directory does not exist in history.' |
|
2767 | 2754 | return |
|
2768 | 2755 | else: |
|
2769 | 2756 | opts = {} |
|
2770 | 2757 | elif parameter_s.startswith('--'): |
|
2771 | 2758 | ps = None |
|
2772 | 2759 | fallback = None |
|
2773 | 2760 | pat = parameter_s[2:] |
|
2774 | 2761 | dh = self.shell.user_ns['_dh'] |
|
2775 | 2762 | # first search only by basename (last component) |
|
2776 | 2763 | for ent in reversed(dh): |
|
2777 | 2764 | if pat in os.path.basename(ent) and os.path.isdir(ent): |
|
2778 | 2765 | ps = ent |
|
2779 | 2766 | break |
|
2780 | 2767 | |
|
2781 | 2768 | if fallback is None and pat in ent and os.path.isdir(ent): |
|
2782 | 2769 | fallback = ent |
|
2783 | 2770 | |
|
2784 | 2771 | # if we have no last part match, pick the first full path match |
|
2785 | 2772 | if ps is None: |
|
2786 | 2773 | ps = fallback |
|
2787 | 2774 | |
|
2788 | 2775 | if ps is None: |
|
2789 | 2776 | print "No matching entry in directory history" |
|
2790 | 2777 | return |
|
2791 | 2778 | else: |
|
2792 | 2779 | opts = {} |
|
2793 | 2780 | |
|
2794 | 2781 | |
|
2795 | 2782 | else: |
|
2796 | 2783 | #turn all non-space-escaping backslashes to slashes, |
|
2797 | 2784 | # for c:\windows\directory\names\ |
|
2798 | 2785 | parameter_s = re.sub(r'\\(?! )','/', parameter_s) |
|
2799 | 2786 | opts,ps = self.parse_options(parameter_s,'qb',mode='string') |
|
2800 | 2787 | # jump to previous |
|
2801 | 2788 | if ps == '-': |
|
2802 | 2789 | try: |
|
2803 | 2790 | ps = self.shell.user_ns['_dh'][-2] |
|
2804 | 2791 | except IndexError: |
|
2805 | 2792 | raise UsageError('%cd -: No previous directory to change to.') |
|
2806 | 2793 | # jump to bookmark if needed |
|
2807 | 2794 | else: |
|
2808 | 2795 | if not os.path.isdir(ps) or opts.has_key('b'): |
|
2809 | 2796 | bkms = self.db.get('bookmarks', {}) |
|
2810 | 2797 | |
|
2811 | 2798 | if bkms.has_key(ps): |
|
2812 | 2799 | target = bkms[ps] |
|
2813 | 2800 | print '(bookmark:%s) -> %s' % (ps,target) |
|
2814 | 2801 | ps = target |
|
2815 | 2802 | else: |
|
2816 | 2803 | if opts.has_key('b'): |
|
2817 | 2804 | raise UsageError("Bookmark '%s' not found. " |
|
2818 | 2805 | "Use '%%bookmark -l' to see your bookmarks." % ps) |
|
2819 | 2806 | |
|
2820 | 2807 | # at this point ps should point to the target dir |
|
2821 | 2808 | if ps: |
|
2822 | 2809 | try: |
|
2823 | 2810 | os.chdir(os.path.expanduser(ps)) |
|
2824 | 2811 | if self.shell.term_title: |
|
2825 | 2812 | platutils.set_term_title('IPython: ' + abbrev_cwd()) |
|
2826 | 2813 | except OSError: |
|
2827 | 2814 | print sys.exc_info()[1] |
|
2828 | 2815 | else: |
|
2829 | 2816 | cwd = os.getcwd() |
|
2830 | 2817 | dhist = self.shell.user_ns['_dh'] |
|
2831 | 2818 | if oldcwd != cwd: |
|
2832 | 2819 | dhist.append(cwd) |
|
2833 | 2820 | self.db['dhist'] = compress_dhist(dhist)[-100:] |
|
2834 | 2821 | |
|
2835 | 2822 | else: |
|
2836 | 2823 | os.chdir(self.shell.home_dir) |
|
2837 | 2824 | if self.shell.term_title: |
|
2838 | 2825 | platutils.set_term_title('IPython: ' + '~') |
|
2839 | 2826 | cwd = os.getcwd() |
|
2840 | 2827 | dhist = self.shell.user_ns['_dh'] |
|
2841 | 2828 | |
|
2842 | 2829 | if oldcwd != cwd: |
|
2843 | 2830 | dhist.append(cwd) |
|
2844 | 2831 | self.db['dhist'] = compress_dhist(dhist)[-100:] |
|
2845 | 2832 | if not 'q' in opts and self.shell.user_ns['_dh']: |
|
2846 | 2833 | print self.shell.user_ns['_dh'][-1] |
|
2847 | 2834 | |
|
2848 | 2835 | |
|
2849 | 2836 | def magic_env(self, parameter_s=''): |
|
2850 | 2837 | """List environment variables.""" |
|
2851 | 2838 | |
|
2852 | 2839 | return os.environ.data |
|
2853 | 2840 | |
|
2854 | 2841 | def magic_pushd(self, parameter_s=''): |
|
2855 | 2842 | """Place the current dir on stack and change directory. |
|
2856 | 2843 | |
|
2857 | 2844 | Usage:\\ |
|
2858 | 2845 | %pushd ['dirname'] |
|
2859 | 2846 | """ |
|
2860 | 2847 | |
|
2861 | 2848 | dir_s = self.shell.dir_stack |
|
2862 | 2849 | tgt = os.path.expanduser(parameter_s) |
|
2863 | 2850 | cwd = os.getcwd().replace(self.home_dir,'~') |
|
2864 | 2851 | if tgt: |
|
2865 | 2852 | self.magic_cd(parameter_s) |
|
2866 | 2853 | dir_s.insert(0,cwd) |
|
2867 | 2854 | return self.magic_dirs() |
|
2868 | 2855 | |
|
2869 | 2856 | def magic_popd(self, parameter_s=''): |
|
2870 | 2857 | """Change to directory popped off the top of the stack. |
|
2871 | 2858 | """ |
|
2872 | 2859 | if not self.shell.dir_stack: |
|
2873 | 2860 | raise UsageError("%popd on empty stack") |
|
2874 | 2861 | top = self.shell.dir_stack.pop(0) |
|
2875 | 2862 | self.magic_cd(top) |
|
2876 | 2863 | print "popd ->",top |
|
2877 | 2864 | |
|
2878 | 2865 | def magic_dirs(self, parameter_s=''): |
|
2879 | 2866 | """Return the current directory stack.""" |
|
2880 | 2867 | |
|
2881 | 2868 | return self.shell.dir_stack |
|
2882 | 2869 | |
|
2883 | 2870 | def magic_dhist(self, parameter_s=''): |
|
2884 | 2871 | """Print your history of visited directories. |
|
2885 | 2872 | |
|
2886 | 2873 | %dhist -> print full history\\ |
|
2887 | 2874 | %dhist n -> print last n entries only\\ |
|
2888 | 2875 | %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\ |
|
2889 | 2876 | |
|
2890 | 2877 | This history is automatically maintained by the %cd command, and |
|
2891 | 2878 | always available as the global list variable _dh. You can use %cd -<n> |
|
2892 | 2879 | to go to directory number <n>. |
|
2893 | 2880 | |
|
2894 | 2881 | Note that most of time, you should view directory history by entering |
|
2895 | 2882 | cd -<TAB>. |
|
2896 | 2883 | |
|
2897 | 2884 | """ |
|
2898 | 2885 | |
|
2899 | 2886 | dh = self.shell.user_ns['_dh'] |
|
2900 | 2887 | if parameter_s: |
|
2901 | 2888 | try: |
|
2902 | 2889 | args = map(int,parameter_s.split()) |
|
2903 | 2890 | except: |
|
2904 | 2891 | self.arg_err(Magic.magic_dhist) |
|
2905 | 2892 | return |
|
2906 | 2893 | if len(args) == 1: |
|
2907 | 2894 | ini,fin = max(len(dh)-(args[0]),0),len(dh) |
|
2908 | 2895 | elif len(args) == 2: |
|
2909 | 2896 | ini,fin = args |
|
2910 | 2897 | else: |
|
2911 | 2898 | self.arg_err(Magic.magic_dhist) |
|
2912 | 2899 | return |
|
2913 | 2900 | else: |
|
2914 | 2901 | ini,fin = 0,len(dh) |
|
2915 | 2902 | nlprint(dh, |
|
2916 | 2903 | header = 'Directory history (kept in _dh)', |
|
2917 | 2904 | start=ini,stop=fin) |
|
2918 | 2905 | |
|
2919 | 2906 | @testdec.skip_doctest |
|
2920 | 2907 | def magic_sc(self, parameter_s=''): |
|
2921 | 2908 | """Shell capture - execute a shell command and capture its output. |
|
2922 | 2909 | |
|
2923 | 2910 | DEPRECATED. Suboptimal, retained for backwards compatibility. |
|
2924 | 2911 | |
|
2925 | 2912 | You should use the form 'var = !command' instead. Example: |
|
2926 | 2913 | |
|
2927 | 2914 | "%sc -l myfiles = ls ~" should now be written as |
|
2928 | 2915 | |
|
2929 | 2916 | "myfiles = !ls ~" |
|
2930 | 2917 | |
|
2931 | 2918 | myfiles.s, myfiles.l and myfiles.n still apply as documented |
|
2932 | 2919 | below. |
|
2933 | 2920 | |
|
2934 | 2921 | -- |
|
2935 | 2922 | %sc [options] varname=command |
|
2936 | 2923 | |
|
2937 | 2924 | IPython will run the given command using commands.getoutput(), and |
|
2938 | 2925 | will then update the user's interactive namespace with a variable |
|
2939 | 2926 | called varname, containing the value of the call. Your command can |
|
2940 | 2927 | contain shell wildcards, pipes, etc. |
|
2941 | 2928 | |
|
2942 | 2929 | The '=' sign in the syntax is mandatory, and the variable name you |
|
2943 | 2930 | supply must follow Python's standard conventions for valid names. |
|
2944 | 2931 | |
|
2945 | 2932 | (A special format without variable name exists for internal use) |
|
2946 | 2933 | |
|
2947 | 2934 | Options: |
|
2948 | 2935 | |
|
2949 | 2936 | -l: list output. Split the output on newlines into a list before |
|
2950 | 2937 | assigning it to the given variable. By default the output is stored |
|
2951 | 2938 | as a single string. |
|
2952 | 2939 | |
|
2953 | 2940 | -v: verbose. Print the contents of the variable. |
|
2954 | 2941 | |
|
2955 | 2942 | In most cases you should not need to split as a list, because the |
|
2956 | 2943 | returned value is a special type of string which can automatically |
|
2957 | 2944 | provide its contents either as a list (split on newlines) or as a |
|
2958 | 2945 | space-separated string. These are convenient, respectively, either |
|
2959 | 2946 | for sequential processing or to be passed to a shell command. |
|
2960 | 2947 | |
|
2961 | 2948 | For example: |
|
2962 | 2949 | |
|
2963 | 2950 | # all-random |
|
2964 | 2951 | |
|
2965 | 2952 | # Capture into variable a |
|
2966 | 2953 | In [1]: sc a=ls *py |
|
2967 | 2954 | |
|
2968 | 2955 | # a is a string with embedded newlines |
|
2969 | 2956 | In [2]: a |
|
2970 | 2957 | Out[2]: 'setup.py\\nwin32_manual_post_install.py' |
|
2971 | 2958 | |
|
2972 | 2959 | # which can be seen as a list: |
|
2973 | 2960 | In [3]: a.l |
|
2974 | 2961 | Out[3]: ['setup.py', 'win32_manual_post_install.py'] |
|
2975 | 2962 | |
|
2976 | 2963 | # or as a whitespace-separated string: |
|
2977 | 2964 | In [4]: a.s |
|
2978 | 2965 | Out[4]: 'setup.py win32_manual_post_install.py' |
|
2979 | 2966 | |
|
2980 | 2967 | # a.s is useful to pass as a single command line: |
|
2981 | 2968 | In [5]: !wc -l $a.s |
|
2982 | 2969 | 146 setup.py |
|
2983 | 2970 | 130 win32_manual_post_install.py |
|
2984 | 2971 | 276 total |
|
2985 | 2972 | |
|
2986 | 2973 | # while the list form is useful to loop over: |
|
2987 | 2974 | In [6]: for f in a.l: |
|
2988 | 2975 | ...: !wc -l $f |
|
2989 | 2976 | ...: |
|
2990 | 2977 | 146 setup.py |
|
2991 | 2978 | 130 win32_manual_post_install.py |
|
2992 | 2979 | |
|
2993 | 2980 | Similiarly, the lists returned by the -l option are also special, in |
|
2994 | 2981 | the sense that you can equally invoke the .s attribute on them to |
|
2995 | 2982 | automatically get a whitespace-separated string from their contents: |
|
2996 | 2983 | |
|
2997 | 2984 | In [7]: sc -l b=ls *py |
|
2998 | 2985 | |
|
2999 | 2986 | In [8]: b |
|
3000 | 2987 | Out[8]: ['setup.py', 'win32_manual_post_install.py'] |
|
3001 | 2988 | |
|
3002 | 2989 | In [9]: b.s |
|
3003 | 2990 | Out[9]: 'setup.py win32_manual_post_install.py' |
|
3004 | 2991 | |
|
3005 | 2992 | In summary, both the lists and strings used for ouptut capture have |
|
3006 | 2993 | the following special attributes: |
|
3007 | 2994 | |
|
3008 | 2995 | .l (or .list) : value as list. |
|
3009 | 2996 | .n (or .nlstr): value as newline-separated string. |
|
3010 | 2997 | .s (or .spstr): value as space-separated string. |
|
3011 | 2998 | """ |
|
3012 | 2999 | |
|
3013 | 3000 | opts,args = self.parse_options(parameter_s,'lv') |
|
3014 | 3001 | # Try to get a variable name and command to run |
|
3015 | 3002 | try: |
|
3016 | 3003 | # the variable name must be obtained from the parse_options |
|
3017 | 3004 | # output, which uses shlex.split to strip options out. |
|
3018 | 3005 | var,_ = args.split('=',1) |
|
3019 | 3006 | var = var.strip() |
|
3020 | 3007 | # But the the command has to be extracted from the original input |
|
3021 | 3008 | # parameter_s, not on what parse_options returns, to avoid the |
|
3022 | 3009 | # quote stripping which shlex.split performs on it. |
|
3023 | 3010 | _,cmd = parameter_s.split('=',1) |
|
3024 | 3011 | except ValueError: |
|
3025 | 3012 | var,cmd = '','' |
|
3026 | 3013 | # If all looks ok, proceed |
|
3027 | 3014 | out,err = self.shell.getoutputerror(cmd) |
|
3028 | 3015 | if err: |
|
3029 | 3016 | print >> Term.cerr,err |
|
3030 | 3017 | if opts.has_key('l'): |
|
3031 | 3018 | out = SList(out.split('\n')) |
|
3032 | 3019 | else: |
|
3033 | 3020 | out = LSString(out) |
|
3034 | 3021 | if opts.has_key('v'): |
|
3035 | 3022 | print '%s ==\n%s' % (var,pformat(out)) |
|
3036 | 3023 | if var: |
|
3037 | 3024 | self.shell.user_ns.update({var:out}) |
|
3038 | 3025 | else: |
|
3039 | 3026 | return out |
|
3040 | 3027 | |
|
3041 | 3028 | def magic_sx(self, parameter_s=''): |
|
3042 | 3029 | """Shell execute - run a shell command and capture its output. |
|
3043 | 3030 | |
|
3044 | 3031 | %sx command |
|
3045 | 3032 | |
|
3046 | 3033 | IPython will run the given command using commands.getoutput(), and |
|
3047 | 3034 | return the result formatted as a list (split on '\\n'). Since the |
|
3048 | 3035 | output is _returned_, it will be stored in ipython's regular output |
|
3049 | 3036 | cache Out[N] and in the '_N' automatic variables. |
|
3050 | 3037 | |
|
3051 | 3038 | Notes: |
|
3052 | 3039 | |
|
3053 | 3040 | 1) If an input line begins with '!!', then %sx is automatically |
|
3054 | 3041 | invoked. That is, while: |
|
3055 | 3042 | !ls |
|
3056 | 3043 | causes ipython to simply issue system('ls'), typing |
|
3057 | 3044 | !!ls |
|
3058 | 3045 | is a shorthand equivalent to: |
|
3059 | 3046 | %sx ls |
|
3060 | 3047 | |
|
3061 | 3048 | 2) %sx differs from %sc in that %sx automatically splits into a list, |
|
3062 | 3049 | like '%sc -l'. The reason for this is to make it as easy as possible |
|
3063 | 3050 | to process line-oriented shell output via further python commands. |
|
3064 | 3051 | %sc is meant to provide much finer control, but requires more |
|
3065 | 3052 | typing. |
|
3066 | 3053 | |
|
3067 | 3054 | 3) Just like %sc -l, this is a list with special attributes: |
|
3068 | 3055 | |
|
3069 | 3056 | .l (or .list) : value as list. |
|
3070 | 3057 | .n (or .nlstr): value as newline-separated string. |
|
3071 | 3058 | .s (or .spstr): value as whitespace-separated string. |
|
3072 | 3059 | |
|
3073 | 3060 | This is very useful when trying to use such lists as arguments to |
|
3074 | 3061 | system commands.""" |
|
3075 | 3062 | |
|
3076 | 3063 | if parameter_s: |
|
3077 | 3064 | out,err = self.shell.getoutputerror(parameter_s) |
|
3078 | 3065 | if err: |
|
3079 | 3066 | print >> Term.cerr,err |
|
3080 | 3067 | return SList(out.split('\n')) |
|
3081 | 3068 | |
|
3082 | 3069 | def magic_bg(self, parameter_s=''): |
|
3083 | 3070 | """Run a job in the background, in a separate thread. |
|
3084 | 3071 | |
|
3085 | 3072 | For example, |
|
3086 | 3073 | |
|
3087 | 3074 | %bg myfunc(x,y,z=1) |
|
3088 | 3075 | |
|
3089 | 3076 | will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the |
|
3090 | 3077 | execution starts, a message will be printed indicating the job |
|
3091 | 3078 | number. If your job number is 5, you can use |
|
3092 | 3079 | |
|
3093 | 3080 | myvar = jobs.result(5) or myvar = jobs[5].result |
|
3094 | 3081 | |
|
3095 | 3082 | to assign this result to variable 'myvar'. |
|
3096 | 3083 | |
|
3097 | 3084 | IPython has a job manager, accessible via the 'jobs' object. You can |
|
3098 | 3085 | type jobs? to get more information about it, and use jobs.<TAB> to see |
|
3099 | 3086 | its attributes. All attributes not starting with an underscore are |
|
3100 | 3087 | meant for public use. |
|
3101 | 3088 | |
|
3102 | 3089 | In particular, look at the jobs.new() method, which is used to create |
|
3103 | 3090 | new jobs. This magic %bg function is just a convenience wrapper |
|
3104 | 3091 | around jobs.new(), for expression-based jobs. If you want to create a |
|
3105 | 3092 | new job with an explicit function object and arguments, you must call |
|
3106 | 3093 | jobs.new() directly. |
|
3107 | 3094 | |
|
3108 | 3095 | The jobs.new docstring also describes in detail several important |
|
3109 | 3096 | caveats associated with a thread-based model for background job |
|
3110 | 3097 | execution. Type jobs.new? for details. |
|
3111 | 3098 | |
|
3112 | 3099 | You can check the status of all jobs with jobs.status(). |
|
3113 | 3100 | |
|
3114 | 3101 | The jobs variable is set by IPython into the Python builtin namespace. |
|
3115 | 3102 | If you ever declare a variable named 'jobs', you will shadow this |
|
3116 | 3103 | name. You can either delete your global jobs variable to regain |
|
3117 | 3104 | access to the job manager, or make a new name and assign it manually |
|
3118 | 3105 | to the manager (stored in IPython's namespace). For example, to |
|
3119 | 3106 | assign the job manager to the Jobs name, use: |
|
3120 | 3107 | |
|
3121 | 3108 | Jobs = __builtins__.jobs""" |
|
3122 | 3109 | |
|
3123 | 3110 | self.shell.jobs.new(parameter_s,self.shell.user_ns) |
|
3124 | 3111 | |
|
3125 | 3112 | def magic_r(self, parameter_s=''): |
|
3126 | 3113 | """Repeat previous input. |
|
3127 | 3114 | |
|
3128 | 3115 | Note: Consider using the more powerfull %rep instead! |
|
3129 | 3116 | |
|
3130 | 3117 | If given an argument, repeats the previous command which starts with |
|
3131 | 3118 | the same string, otherwise it just repeats the previous input. |
|
3132 | 3119 | |
|
3133 | 3120 | Shell escaped commands (with ! as first character) are not recognized |
|
3134 | 3121 | by this system, only pure python code and magic commands. |
|
3135 | 3122 | """ |
|
3136 | 3123 | |
|
3137 | 3124 | start = parameter_s.strip() |
|
3138 | 3125 | esc_magic = ESC_MAGIC |
|
3139 | 3126 | # Identify magic commands even if automagic is on (which means |
|
3140 | 3127 | # the in-memory version is different from that typed by the user). |
|
3141 | 3128 | if self.shell.automagic: |
|
3142 | 3129 | start_magic = esc_magic+start |
|
3143 | 3130 | else: |
|
3144 | 3131 | start_magic = start |
|
3145 | 3132 | # Look through the input history in reverse |
|
3146 | 3133 | for n in range(len(self.shell.input_hist)-2,0,-1): |
|
3147 | 3134 | input = self.shell.input_hist[n] |
|
3148 | 3135 | # skip plain 'r' lines so we don't recurse to infinity |
|
3149 | 3136 | if input != '_ip.magic("r")\n' and \ |
|
3150 | 3137 | (input.startswith(start) or input.startswith(start_magic)): |
|
3151 | 3138 | #print 'match',`input` # dbg |
|
3152 | 3139 | print 'Executing:',input, |
|
3153 | 3140 | self.shell.runlines(input) |
|
3154 | 3141 | return |
|
3155 | 3142 | print 'No previous input matching `%s` found.' % start |
|
3156 | 3143 | |
|
3157 | 3144 | |
|
3158 | 3145 | def magic_bookmark(self, parameter_s=''): |
|
3159 | 3146 | """Manage IPython's bookmark system. |
|
3160 | 3147 | |
|
3161 | 3148 | %bookmark <name> - set bookmark to current dir |
|
3162 | 3149 | %bookmark <name> <dir> - set bookmark to <dir> |
|
3163 | 3150 | %bookmark -l - list all bookmarks |
|
3164 | 3151 | %bookmark -d <name> - remove bookmark |
|
3165 | 3152 | %bookmark -r - remove all bookmarks |
|
3166 | 3153 | |
|
3167 | 3154 | You can later on access a bookmarked folder with: |
|
3168 | 3155 | %cd -b <name> |
|
3169 | 3156 | or simply '%cd <name>' if there is no directory called <name> AND |
|
3170 | 3157 | there is such a bookmark defined. |
|
3171 | 3158 | |
|
3172 | 3159 | Your bookmarks persist through IPython sessions, but they are |
|
3173 | 3160 | associated with each profile.""" |
|
3174 | 3161 | |
|
3175 | 3162 | opts,args = self.parse_options(parameter_s,'drl',mode='list') |
|
3176 | 3163 | if len(args) > 2: |
|
3177 | 3164 | raise UsageError("%bookmark: too many arguments") |
|
3178 | 3165 | |
|
3179 | 3166 | bkms = self.db.get('bookmarks',{}) |
|
3180 | 3167 | |
|
3181 | 3168 | if opts.has_key('d'): |
|
3182 | 3169 | try: |
|
3183 | 3170 | todel = args[0] |
|
3184 | 3171 | except IndexError: |
|
3185 | 3172 | raise UsageError( |
|
3186 | 3173 | "%bookmark -d: must provide a bookmark to delete") |
|
3187 | 3174 | else: |
|
3188 | 3175 | try: |
|
3189 | 3176 | del bkms[todel] |
|
3190 | 3177 | except KeyError: |
|
3191 | 3178 | raise UsageError( |
|
3192 | 3179 | "%%bookmark -d: Can't delete bookmark '%s'" % todel) |
|
3193 | 3180 | |
|
3194 | 3181 | elif opts.has_key('r'): |
|
3195 | 3182 | bkms = {} |
|
3196 | 3183 | elif opts.has_key('l'): |
|
3197 | 3184 | bks = bkms.keys() |
|
3198 | 3185 | bks.sort() |
|
3199 | 3186 | if bks: |
|
3200 | 3187 | size = max(map(len,bks)) |
|
3201 | 3188 | else: |
|
3202 | 3189 | size = 0 |
|
3203 | 3190 | fmt = '%-'+str(size)+'s -> %s' |
|
3204 | 3191 | print 'Current bookmarks:' |
|
3205 | 3192 | for bk in bks: |
|
3206 | 3193 | print fmt % (bk,bkms[bk]) |
|
3207 | 3194 | else: |
|
3208 | 3195 | if not args: |
|
3209 | 3196 | raise UsageError("%bookmark: You must specify the bookmark name") |
|
3210 | 3197 | elif len(args)==1: |
|
3211 | 3198 | bkms[args[0]] = os.getcwd() |
|
3212 | 3199 | elif len(args)==2: |
|
3213 | 3200 | bkms[args[0]] = args[1] |
|
3214 | 3201 | self.db['bookmarks'] = bkms |
|
3215 | 3202 | |
|
3216 | 3203 | def magic_pycat(self, parameter_s=''): |
|
3217 | 3204 | """Show a syntax-highlighted file through a pager. |
|
3218 | 3205 | |
|
3219 | 3206 | This magic is similar to the cat utility, but it will assume the file |
|
3220 | 3207 | to be Python source and will show it with syntax highlighting. """ |
|
3221 | 3208 | |
|
3222 | 3209 | try: |
|
3223 | 3210 | filename = get_py_filename(parameter_s) |
|
3224 | 3211 | cont = file_read(filename) |
|
3225 | 3212 | except IOError: |
|
3226 | 3213 | try: |
|
3227 | 3214 | cont = eval(parameter_s,self.user_ns) |
|
3228 | 3215 | except NameError: |
|
3229 | 3216 | cont = None |
|
3230 | 3217 | if cont is None: |
|
3231 | 3218 | print "Error: no such file or variable" |
|
3232 | 3219 | return |
|
3233 | 3220 | |
|
3234 | 3221 | page(self.shell.pycolorize(cont), |
|
3235 | 3222 | screen_lines=self.shell.usable_screen_length) |
|
3236 | 3223 | |
|
3237 | 3224 | def _rerun_pasted(self): |
|
3238 | 3225 | """ Rerun a previously pasted command. |
|
3239 | 3226 | """ |
|
3240 | 3227 | b = self.user_ns.get('pasted_block', None) |
|
3241 | 3228 | if b is None: |
|
3242 | 3229 | raise UsageError('No previous pasted block available') |
|
3243 | 3230 | print "Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b)) |
|
3244 | 3231 | exec b in self.user_ns |
|
3245 | 3232 | |
|
3246 | 3233 | def _get_pasted_lines(self, sentinel): |
|
3247 | 3234 | """ Yield pasted lines until the user enters the given sentinel value. |
|
3248 | 3235 | """ |
|
3249 | 3236 | from IPython.core import iplib |
|
3250 | 3237 | print "Pasting code; enter '%s' alone on the line to stop." % sentinel |
|
3251 | 3238 | while True: |
|
3252 | 3239 | l = iplib.raw_input_original(':') |
|
3253 | 3240 | if l == sentinel: |
|
3254 | 3241 | return |
|
3255 | 3242 | else: |
|
3256 | 3243 | yield l |
|
3257 | 3244 | |
|
3258 | 3245 | def _strip_pasted_lines_for_code(self, raw_lines): |
|
3259 | 3246 | """ Strip non-code parts of a sequence of lines to return a block of |
|
3260 | 3247 | code. |
|
3261 | 3248 | """ |
|
3262 | 3249 | # Regular expressions that declare text we strip from the input: |
|
3263 | 3250 | strip_re = [r'^\s*In \[\d+\]:', # IPython input prompt |
|
3264 | 3251 | r'^\s*(\s?>)+', # Python input prompt |
|
3265 | 3252 | r'^\s*\.{3,}', # Continuation prompts |
|
3266 | 3253 | r'^\++', |
|
3267 | 3254 | ] |
|
3268 | 3255 | |
|
3269 | 3256 | strip_from_start = map(re.compile,strip_re) |
|
3270 | 3257 | |
|
3271 | 3258 | lines = [] |
|
3272 | 3259 | for l in raw_lines: |
|
3273 | 3260 | for pat in strip_from_start: |
|
3274 | 3261 | l = pat.sub('',l) |
|
3275 | 3262 | lines.append(l) |
|
3276 | 3263 | |
|
3277 | 3264 | block = "\n".join(lines) + '\n' |
|
3278 | 3265 | #print "block:\n",block |
|
3279 | 3266 | return block |
|
3280 | 3267 | |
|
3281 | 3268 | def _execute_block(self, block, par): |
|
3282 | 3269 | """ Execute a block, or store it in a variable, per the user's request. |
|
3283 | 3270 | """ |
|
3284 | 3271 | if not par: |
|
3285 | 3272 | b = textwrap.dedent(block) |
|
3286 | 3273 | self.user_ns['pasted_block'] = b |
|
3287 | 3274 | exec b in self.user_ns |
|
3288 | 3275 | else: |
|
3289 | 3276 | self.user_ns[par] = SList(block.splitlines()) |
|
3290 | 3277 | print "Block assigned to '%s'" % par |
|
3291 | 3278 | |
|
3292 | 3279 | def magic_cpaste(self, parameter_s=''): |
|
3293 | 3280 | """Allows you to paste & execute a pre-formatted code block from clipboard. |
|
3294 | 3281 | |
|
3295 | 3282 | You must terminate the block with '--' (two minus-signs) alone on the |
|
3296 | 3283 | line. You can also provide your own sentinel with '%paste -s %%' ('%%' |
|
3297 | 3284 | is the new sentinel for this operation) |
|
3298 | 3285 | |
|
3299 | 3286 | The block is dedented prior to execution to enable execution of method |
|
3300 | 3287 | definitions. '>' and '+' characters at the beginning of a line are |
|
3301 | 3288 | ignored, to allow pasting directly from e-mails, diff files and |
|
3302 | 3289 | doctests (the '...' continuation prompt is also stripped). The |
|
3303 | 3290 | executed block is also assigned to variable named 'pasted_block' for |
|
3304 | 3291 | later editing with '%edit pasted_block'. |
|
3305 | 3292 | |
|
3306 | 3293 | You can also pass a variable name as an argument, e.g. '%cpaste foo'. |
|
3307 | 3294 | This assigns the pasted block to variable 'foo' as string, without |
|
3308 | 3295 | dedenting or executing it (preceding >>> and + is still stripped) |
|
3309 | 3296 | |
|
3310 | 3297 | '%cpaste -r' re-executes the block previously entered by cpaste. |
|
3311 | 3298 | |
|
3312 | 3299 | Do not be alarmed by garbled output on Windows (it's a readline bug). |
|
3313 | 3300 | Just press enter and type -- (and press enter again) and the block |
|
3314 | 3301 | will be what was just pasted. |
|
3315 | 3302 | |
|
3316 | 3303 | IPython statements (magics, shell escapes) are not supported (yet). |
|
3317 | 3304 | |
|
3318 | 3305 | See also |
|
3319 | 3306 | -------- |
|
3320 | 3307 | paste: automatically pull code from clipboard. |
|
3321 | 3308 | """ |
|
3322 | 3309 | |
|
3323 | 3310 | opts,args = self.parse_options(parameter_s,'rs:',mode='string') |
|
3324 | 3311 | par = args.strip() |
|
3325 | 3312 | if opts.has_key('r'): |
|
3326 | 3313 | self._rerun_pasted() |
|
3327 | 3314 | return |
|
3328 | 3315 | |
|
3329 | 3316 | sentinel = opts.get('s','--') |
|
3330 | 3317 | |
|
3331 | 3318 | block = self._strip_pasted_lines_for_code( |
|
3332 | 3319 | self._get_pasted_lines(sentinel)) |
|
3333 | 3320 | |
|
3334 | 3321 | self._execute_block(block, par) |
|
3335 | 3322 | |
|
3336 | 3323 | def magic_paste(self, parameter_s=''): |
|
3337 | 3324 | """Allows you to paste & execute a pre-formatted code block from clipboard. |
|
3338 | 3325 | |
|
3339 | 3326 | The text is pulled directly from the clipboard without user |
|
3340 | 3327 | intervention and printed back on the screen before execution (unless |
|
3341 | 3328 | the -q flag is given to force quiet mode). |
|
3342 | 3329 | |
|
3343 | 3330 | The block is dedented prior to execution to enable execution of method |
|
3344 | 3331 | definitions. '>' and '+' characters at the beginning of a line are |
|
3345 | 3332 | ignored, to allow pasting directly from e-mails, diff files and |
|
3346 | 3333 | doctests (the '...' continuation prompt is also stripped). The |
|
3347 | 3334 | executed block is also assigned to variable named 'pasted_block' for |
|
3348 | 3335 | later editing with '%edit pasted_block'. |
|
3349 | 3336 | |
|
3350 | 3337 | You can also pass a variable name as an argument, e.g. '%paste foo'. |
|
3351 | 3338 | This assigns the pasted block to variable 'foo' as string, without |
|
3352 | 3339 | dedenting or executing it (preceding >>> and + is still stripped) |
|
3353 | 3340 | |
|
3354 | 3341 | Options |
|
3355 | 3342 | ------- |
|
3356 | 3343 | |
|
3357 | 3344 | -r: re-executes the block previously entered by cpaste. |
|
3358 | 3345 | |
|
3359 | 3346 | -q: quiet mode: do not echo the pasted text back to the terminal. |
|
3360 | 3347 | |
|
3361 | 3348 | IPython statements (magics, shell escapes) are not supported (yet). |
|
3362 | 3349 | |
|
3363 | 3350 | See also |
|
3364 | 3351 | -------- |
|
3365 | 3352 | cpaste: manually paste code into terminal until you mark its end. |
|
3366 | 3353 | """ |
|
3367 | 3354 | opts,args = self.parse_options(parameter_s,'rq',mode='string') |
|
3368 | 3355 | par = args.strip() |
|
3369 | 3356 | if opts.has_key('r'): |
|
3370 | 3357 | self._rerun_pasted() |
|
3371 | 3358 | return |
|
3372 | 3359 | |
|
3373 | 3360 | text = self.shell.hooks.clipboard_get() |
|
3374 | 3361 | block = self._strip_pasted_lines_for_code(text.splitlines()) |
|
3375 | 3362 | |
|
3376 | 3363 | # By default, echo back to terminal unless quiet mode is requested |
|
3377 | 3364 | if not opts.has_key('q'): |
|
3378 | 3365 | write = self.shell.write |
|
3379 | 3366 | write(self.shell.pycolorize(block)) |
|
3380 | 3367 | if not block.endswith('\n'): |
|
3381 | 3368 | write('\n') |
|
3382 | 3369 | write("## -- End pasted text --\n") |
|
3383 | 3370 | |
|
3384 | 3371 | self._execute_block(block, par) |
|
3385 | 3372 | |
|
3386 | 3373 | def magic_quickref(self,arg): |
|
3387 | 3374 | """ Show a quick reference sheet """ |
|
3388 | 3375 | import IPython.core.usage |
|
3389 | 3376 | qr = IPython.core.usage.quick_reference + self.magic_magic('-brief') |
|
3390 | 3377 | |
|
3391 | 3378 | page(qr) |
|
3392 | 3379 | |
|
3393 | 3380 | def magic_doctest_mode(self,parameter_s=''): |
|
3394 | 3381 | """Toggle doctest mode on and off. |
|
3395 | 3382 | |
|
3396 | 3383 | This mode allows you to toggle the prompt behavior between normal |
|
3397 | 3384 | IPython prompts and ones that are as similar to the default IPython |
|
3398 | 3385 | interpreter as possible. |
|
3399 | 3386 | |
|
3400 | 3387 | It also supports the pasting of code snippets that have leading '>>>' |
|
3401 | 3388 | and '...' prompts in them. This means that you can paste doctests from |
|
3402 | 3389 | files or docstrings (even if they have leading whitespace), and the |
|
3403 | 3390 | code will execute correctly. You can then use '%history -tn' to see |
|
3404 | 3391 | the translated history without line numbers; this will give you the |
|
3405 | 3392 | input after removal of all the leading prompts and whitespace, which |
|
3406 | 3393 | can be pasted back into an editor. |
|
3407 | 3394 | |
|
3408 | 3395 | With these features, you can switch into this mode easily whenever you |
|
3409 | 3396 | need to do testing and changes to doctests, without having to leave |
|
3410 | 3397 | your existing IPython session. |
|
3411 | 3398 | """ |
|
3412 | 3399 | |
|
3413 | 3400 | # XXX - Fix this to have cleaner activate/deactivate calls. |
|
3414 | 3401 | from IPython.extensions import InterpreterPasteInput as ipaste |
|
3415 | 3402 | from IPython.utils.ipstruct import Struct |
|
3416 | 3403 | |
|
3417 | 3404 | # Shorthands |
|
3418 | 3405 | shell = self.shell |
|
3419 | 3406 | oc = shell.outputcache |
|
3420 | 3407 | meta = shell.meta |
|
3421 | 3408 | # dstore is a data store kept in the instance metadata bag to track any |
|
3422 | 3409 | # changes we make, so we can undo them later. |
|
3423 | 3410 | dstore = meta.setdefault('doctest_mode',Struct()) |
|
3424 | 3411 | save_dstore = dstore.setdefault |
|
3425 | 3412 | |
|
3426 | 3413 | # save a few values we'll need to recover later |
|
3427 | 3414 | mode = save_dstore('mode',False) |
|
3428 | 3415 | save_dstore('rc_pprint',shell.pprint) |
|
3429 | 3416 | save_dstore('xmode',shell.InteractiveTB.mode) |
|
3430 | 3417 | save_dstore('rc_separate_out',shell.separate_out) |
|
3431 | 3418 | save_dstore('rc_separate_out2',shell.separate_out2) |
|
3432 | 3419 | save_dstore('rc_prompts_pad_left',shell.prompts_pad_left) |
|
3433 | 3420 | save_dstore('rc_separate_in',shell.separate_in) |
|
3434 | 3421 | |
|
3435 | 3422 | if mode == False: |
|
3436 | 3423 | # turn on |
|
3437 | 3424 | ipaste.activate_prefilter() |
|
3438 | 3425 | |
|
3439 | 3426 | oc.prompt1.p_template = '>>> ' |
|
3440 | 3427 | oc.prompt2.p_template = '... ' |
|
3441 | 3428 | oc.prompt_out.p_template = '' |
|
3442 | 3429 | |
|
3443 | 3430 | # Prompt separators like plain python |
|
3444 | 3431 | oc.input_sep = oc.prompt1.sep = '' |
|
3445 | 3432 | oc.output_sep = '' |
|
3446 | 3433 | oc.output_sep2 = '' |
|
3447 | 3434 | |
|
3448 | 3435 | oc.prompt1.pad_left = oc.prompt2.pad_left = \ |
|
3449 | 3436 | oc.prompt_out.pad_left = False |
|
3450 | 3437 | |
|
3451 | 3438 | shell.pprint = False |
|
3452 | 3439 | |
|
3453 | 3440 | shell.magic_xmode('Plain') |
|
3454 | 3441 | |
|
3455 | 3442 | else: |
|
3456 | 3443 | # turn off |
|
3457 | 3444 | ipaste.deactivate_prefilter() |
|
3458 | 3445 | |
|
3459 | 3446 | oc.prompt1.p_template = shell.prompt_in1 |
|
3460 | 3447 | oc.prompt2.p_template = shell.prompt_in2 |
|
3461 | 3448 | oc.prompt_out.p_template = shell.prompt_out |
|
3462 | 3449 | |
|
3463 | 3450 | oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in |
|
3464 | 3451 | |
|
3465 | 3452 | oc.output_sep = dstore.rc_separate_out |
|
3466 | 3453 | oc.output_sep2 = dstore.rc_separate_out2 |
|
3467 | 3454 | |
|
3468 | 3455 | oc.prompt1.pad_left = oc.prompt2.pad_left = \ |
|
3469 | 3456 | oc.prompt_out.pad_left = dstore.rc_prompts_pad_left |
|
3470 | 3457 | |
|
3471 | 3458 | rc.pprint = dstore.rc_pprint |
|
3472 | 3459 | |
|
3473 | 3460 | shell.magic_xmode(dstore.xmode) |
|
3474 | 3461 | |
|
3475 | 3462 | # Store new mode and inform |
|
3476 | 3463 | dstore.mode = bool(1-int(mode)) |
|
3477 | 3464 | print 'Doctest mode is:', |
|
3478 | 3465 | print ['OFF','ON'][dstore.mode] |
|
3479 | 3466 | |
|
3480 | 3467 | def magic_gui(self, parameter_s=''): |
|
3481 | 3468 | """Enable or disable IPython GUI event loop integration. |
|
3482 | 3469 | |
|
3483 | 3470 | %gui [-a] [GUINAME] |
|
3484 | 3471 | |
|
3485 | 3472 | This magic replaces IPython's threaded shells that were activated |
|
3486 | 3473 | using the (pylab/wthread/etc.) command line flags. GUI toolkits |
|
3487 | 3474 | can now be enabled, disabled and swtiched at runtime and keyboard |
|
3488 | 3475 | interrupts should work without any problems. The following toolkits |
|
3489 | 3476 | are supported: wxPython, PyQt4, PyGTK, and Tk:: |
|
3490 | 3477 | |
|
3491 | 3478 | %gui wx # enable wxPython event loop integration |
|
3492 | 3479 | %gui qt4|qt # enable PyQt4 event loop integration |
|
3493 | 3480 | %gui gtk # enable PyGTK event loop integration |
|
3494 | 3481 | %gui tk # enable Tk event loop integration |
|
3495 | 3482 | %gui # disable all event loop integration |
|
3496 | 3483 | |
|
3497 | 3484 | WARNING: after any of these has been called you can simply create |
|
3498 | 3485 | an application object, but DO NOT start the event loop yourself, as |
|
3499 | 3486 | we have already handled that. |
|
3500 | 3487 | |
|
3501 | 3488 | If you want us to create an appropriate application object add the |
|
3502 | 3489 | "-a" flag to your command:: |
|
3503 | 3490 | |
|
3504 | 3491 | %gui -a wx |
|
3505 | 3492 | |
|
3506 | 3493 | This is highly recommended for most users. |
|
3507 | 3494 | """ |
|
3508 | 3495 | opts, arg = self.parse_options(parameter_s,'a') |
|
3509 | 3496 | if arg=='': arg = None |
|
3510 | 3497 | return enable_gui(arg, 'a' in opts) |
|
3511 | 3498 | |
|
3512 | 3499 | def magic_load_ext(self, module_str): |
|
3513 | 3500 | """Load an IPython extension by its module name.""" |
|
3514 | 3501 | self.load_extension(module_str) |
|
3515 | 3502 | |
|
3516 | 3503 | def magic_unload_ext(self, module_str): |
|
3517 | 3504 | """Unload an IPython extension by its module name.""" |
|
3518 | 3505 | self.unload_extension(module_str) |
|
3519 | 3506 | |
|
3520 | 3507 | def magic_reload_ext(self, module_str): |
|
3521 | 3508 | """Reload an IPython extension by its module name.""" |
|
3522 | 3509 | self.reload_extension(module_str) |
|
3523 | 3510 | |
|
3524 | 3511 | def magic_install_profiles(self, s): |
|
3525 | 3512 | """Install the default IPython profiles into the .ipython dir. |
|
3526 | 3513 | |
|
3527 | 3514 | If the default profiles have already been installed, they will not |
|
3528 | 3515 | be overwritten. You can force overwriting them by using the ``-o`` |
|
3529 | 3516 | option:: |
|
3530 | 3517 | |
|
3531 | 3518 | In [1]: %install_profiles -o |
|
3532 | 3519 | """ |
|
3533 | 3520 | if '-o' in s: |
|
3534 | 3521 | overwrite = True |
|
3535 | 3522 | else: |
|
3536 | 3523 | overwrite = False |
|
3537 | 3524 | from IPython.config import profile |
|
3538 | 3525 | profile_dir = os.path.split(profile.__file__)[0] |
|
3539 | 3526 | ipython_dir = self.ipython_dir |
|
3540 | 3527 | files = os.listdir(profile_dir) |
|
3541 | 3528 | |
|
3542 | 3529 | to_install = [] |
|
3543 | 3530 | for f in files: |
|
3544 | 3531 | if f.startswith('ipython_config'): |
|
3545 | 3532 | src = os.path.join(profile_dir, f) |
|
3546 | 3533 | dst = os.path.join(ipython_dir, f) |
|
3547 | 3534 | if (not os.path.isfile(dst)) or overwrite: |
|
3548 | 3535 | to_install.append((f, src, dst)) |
|
3549 | 3536 | if len(to_install)>0: |
|
3550 | 3537 | print "Installing profiles to: ", ipython_dir |
|
3551 | 3538 | for (f, src, dst) in to_install: |
|
3552 | 3539 | shutil.copy(src, dst) |
|
3553 | 3540 | print " %s" % f |
|
3554 | 3541 | |
|
3555 | 3542 | def magic_install_default_config(self, s): |
|
3556 | 3543 | """Install IPython's default config file into the .ipython dir. |
|
3557 | 3544 | |
|
3558 | 3545 | If the default config file (:file:`ipython_config.py`) is already |
|
3559 | 3546 | installed, it will not be overwritten. You can force overwriting |
|
3560 | 3547 | by using the ``-o`` option:: |
|
3561 | 3548 | |
|
3562 | 3549 | In [1]: %install_default_config |
|
3563 | 3550 | """ |
|
3564 | 3551 | if '-o' in s: |
|
3565 | 3552 | overwrite = True |
|
3566 | 3553 | else: |
|
3567 | 3554 | overwrite = False |
|
3568 | 3555 | from IPython.config import default |
|
3569 | 3556 | config_dir = os.path.split(default.__file__)[0] |
|
3570 | 3557 | ipython_dir = self.ipython_dir |
|
3571 | 3558 | default_config_file_name = 'ipython_config.py' |
|
3572 | 3559 | src = os.path.join(config_dir, default_config_file_name) |
|
3573 | 3560 | dst = os.path.join(ipython_dir, default_config_file_name) |
|
3574 | 3561 | if (not os.path.isfile(dst)) or overwrite: |
|
3575 | 3562 | shutil.copy(src, dst) |
|
3576 | 3563 | print "Installing default config file: %s" % dst |
|
3577 | 3564 | |
|
3578 | 3565 | # Pylab support: simple wrappers that activate pylab, load gui input |
|
3579 | 3566 | # handling and modify slightly %run |
|
3580 | 3567 | |
|
3581 | 3568 | @testdec.skip_doctest |
|
3582 | 3569 | def _pylab_magic_run(self, parameter_s=''): |
|
3583 | 3570 | Magic.magic_run(self, parameter_s, |
|
3584 | 3571 | runner=mpl_runner(self.shell.safe_execfile)) |
|
3585 | 3572 | |
|
3586 | 3573 | _pylab_magic_run.__doc__ = magic_run.__doc__ |
|
3587 | 3574 | |
|
3588 | 3575 | @testdec.skip_doctest |
|
3589 | 3576 | def magic_pylab(self, s): |
|
3590 | 3577 | """Load numpy and matplotlib to work interactively. |
|
3591 | 3578 | |
|
3592 | 3579 | %pylab [GUINAME] |
|
3593 | 3580 | |
|
3594 | 3581 | This function lets you activate pylab (matplotlib, numpy and |
|
3595 | 3582 | interactive support) at any point during an IPython session. |
|
3596 | 3583 | |
|
3597 | 3584 | It will import at the top level numpy as np, pyplot as plt, matplotlib, |
|
3598 | 3585 | pylab and mlab, as well as all names from numpy and pylab. |
|
3599 | 3586 | |
|
3600 | 3587 | Parameters |
|
3601 | 3588 | ---------- |
|
3602 | 3589 | guiname : optional |
|
3603 | 3590 | One of the valid arguments to the %gui magic ('qt', 'wx', 'gtk' or |
|
3604 | 3591 | 'tk'). If given, the corresponding Matplotlib backend is used, |
|
3605 | 3592 | otherwise matplotlib's default (which you can override in your |
|
3606 | 3593 | matplotlib config file) is used. |
|
3607 | 3594 | |
|
3608 | 3595 | Examples |
|
3609 | 3596 | -------- |
|
3610 | 3597 | In this case, where the MPL default is TkAgg: |
|
3611 | 3598 | In [2]: %pylab |
|
3612 | 3599 | |
|
3613 | 3600 | Welcome to pylab, a matplotlib-based Python environment. |
|
3614 | 3601 | Backend in use: TkAgg |
|
3615 | 3602 | For more information, type 'help(pylab)'. |
|
3616 | 3603 | |
|
3617 | 3604 | But you can explicitly request a different backend: |
|
3618 | 3605 | In [3]: %pylab qt |
|
3619 | 3606 | |
|
3620 | 3607 | Welcome to pylab, a matplotlib-based Python environment. |
|
3621 | 3608 | Backend in use: Qt4Agg |
|
3622 | 3609 | For more information, type 'help(pylab)'. |
|
3623 | 3610 | """ |
|
3624 | 3611 | self.shell.enable_pylab(s) |
|
3625 | 3612 | |
|
3626 | 3613 | # end Magic |
@@ -1,630 +1,635 b'' | |||
|
1 | 1 | # -*- coding: utf-8 -*- |
|
2 | 2 | """ |
|
3 | 3 | Classes for handling input/output prompts. |
|
4 | 4 | """ |
|
5 | 5 | |
|
6 | 6 | #***************************************************************************** |
|
7 | 7 | # Copyright (C) 2008-2009 The IPython Development Team |
|
8 | 8 | # Copyright (C) 2001-2007 Fernando Perez <fperez@colorado.edu> |
|
9 | 9 | # |
|
10 | 10 | # Distributed under the terms of the BSD License. The full license is in |
|
11 | 11 | # the file COPYING, distributed as part of this software. |
|
12 | 12 | #***************************************************************************** |
|
13 | 13 | |
|
14 | 14 | #**************************************************************************** |
|
15 | 15 | # Required modules |
|
16 | 16 | import __builtin__ |
|
17 | 17 | import os |
|
18 | 18 | import socket |
|
19 | 19 | import sys |
|
20 | 20 | import time |
|
21 | 21 | |
|
22 | 22 | # IPython's own |
|
23 | 23 | from IPython.utils import coloransi |
|
24 | 24 | from IPython.core import release |
|
25 | 25 | from IPython.external.Itpl import ItplNS |
|
26 | 26 | from IPython.core.error import TryNext |
|
27 | 27 | from IPython.utils.ipstruct import Struct |
|
28 | 28 | from IPython.core.macro import Macro |
|
29 | 29 | import IPython.utils.generics |
|
30 | 30 | |
|
31 | 31 | from IPython.utils.genutils import * |
|
32 | 32 | |
|
33 | 33 | #**************************************************************************** |
|
34 | 34 | #Color schemes for Prompts. |
|
35 | 35 | |
|
36 | 36 | PromptColors = coloransi.ColorSchemeTable() |
|
37 | 37 | InputColors = coloransi.InputTermColors # just a shorthand |
|
38 | 38 | Colors = coloransi.TermColors # just a shorthand |
|
39 | 39 | |
|
40 | 40 | PromptColors.add_scheme(coloransi.ColorScheme( |
|
41 | 41 | 'NoColor', |
|
42 | 42 | in_prompt = InputColors.NoColor, # Input prompt |
|
43 | 43 | in_number = InputColors.NoColor, # Input prompt number |
|
44 | 44 | in_prompt2 = InputColors.NoColor, # Continuation prompt |
|
45 | 45 | in_normal = InputColors.NoColor, # color off (usu. Colors.Normal) |
|
46 | 46 | |
|
47 | 47 | out_prompt = Colors.NoColor, # Output prompt |
|
48 | 48 | out_number = Colors.NoColor, # Output prompt number |
|
49 | 49 | |
|
50 | 50 | normal = Colors.NoColor # color off (usu. Colors.Normal) |
|
51 | 51 | )) |
|
52 | 52 | |
|
53 | 53 | # make some schemes as instances so we can copy them for modification easily: |
|
54 | 54 | __PColLinux = coloransi.ColorScheme( |
|
55 | 55 | 'Linux', |
|
56 | 56 | in_prompt = InputColors.Green, |
|
57 | 57 | in_number = InputColors.LightGreen, |
|
58 | 58 | in_prompt2 = InputColors.Green, |
|
59 | 59 | in_normal = InputColors.Normal, # color off (usu. Colors.Normal) |
|
60 | 60 | |
|
61 | 61 | out_prompt = Colors.Red, |
|
62 | 62 | out_number = Colors.LightRed, |
|
63 | 63 | |
|
64 | 64 | normal = Colors.Normal |
|
65 | 65 | ) |
|
66 | 66 | # Don't forget to enter it into the table! |
|
67 | 67 | PromptColors.add_scheme(__PColLinux) |
|
68 | 68 | |
|
69 | 69 | # Slightly modified Linux for light backgrounds |
|
70 | 70 | __PColLightBG = __PColLinux.copy('LightBG') |
|
71 | 71 | |
|
72 | 72 | __PColLightBG.colors.update( |
|
73 | 73 | in_prompt = InputColors.Blue, |
|
74 | 74 | in_number = InputColors.LightBlue, |
|
75 | 75 | in_prompt2 = InputColors.Blue |
|
76 | 76 | ) |
|
77 | 77 | PromptColors.add_scheme(__PColLightBG) |
|
78 | 78 | |
|
79 | 79 | del Colors,InputColors |
|
80 | 80 | |
|
81 | 81 | #----------------------------------------------------------------------------- |
|
82 | 82 | def multiple_replace(dict, text): |
|
83 | 83 | """ Replace in 'text' all occurences of any key in the given |
|
84 | 84 | dictionary by its corresponding value. Returns the new string.""" |
|
85 | 85 | |
|
86 | 86 | # Function by Xavier Defrang, originally found at: |
|
87 | 87 | # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81330 |
|
88 | 88 | |
|
89 | 89 | # Create a regular expression from the dictionary keys |
|
90 | 90 | regex = re.compile("(%s)" % "|".join(map(re.escape, dict.keys()))) |
|
91 | 91 | # For each match, look-up corresponding value in dictionary |
|
92 | 92 | return regex.sub(lambda mo: dict[mo.string[mo.start():mo.end()]], text) |
|
93 | 93 | |
|
94 | 94 | #----------------------------------------------------------------------------- |
|
95 | 95 | # Special characters that can be used in prompt templates, mainly bash-like |
|
96 | 96 | |
|
97 | 97 | # If $HOME isn't defined (Windows), make it an absurd string so that it can |
|
98 | 98 | # never be expanded out into '~'. Basically anything which can never be a |
|
99 | 99 | # reasonable directory name will do, we just want the $HOME -> '~' operation |
|
100 | 100 | # to become a no-op. We pre-compute $HOME here so it's not done on every |
|
101 | 101 | # prompt call. |
|
102 | 102 | |
|
103 | 103 | # FIXME: |
|
104 | 104 | |
|
105 | 105 | # - This should be turned into a class which does proper namespace management, |
|
106 | 106 | # since the prompt specials need to be evaluated in a certain namespace. |
|
107 | 107 | # Currently it's just globals, which need to be managed manually by code |
|
108 | 108 | # below. |
|
109 | 109 | |
|
110 | 110 | # - I also need to split up the color schemes from the prompt specials |
|
111 | 111 | # somehow. I don't have a clean design for that quite yet. |
|
112 | 112 | |
|
113 | 113 | HOME = os.environ.get("HOME","//////:::::ZZZZZ,,,~~~") |
|
114 | 114 | |
|
115 | 115 | # We precompute a few more strings here for the prompt_specials, which are |
|
116 | 116 | # fixed once ipython starts. This reduces the runtime overhead of computing |
|
117 | 117 | # prompt strings. |
|
118 | 118 | USER = os.environ.get("USER") |
|
119 | 119 | HOSTNAME = socket.gethostname() |
|
120 | 120 | HOSTNAME_SHORT = HOSTNAME.split(".")[0] |
|
121 | 121 | ROOT_SYMBOL = "$#"[os.name=='nt' or os.getuid()==0] |
|
122 | 122 | |
|
123 | 123 | prompt_specials_color = { |
|
124 | 124 | # Prompt/history count |
|
125 | 125 | '%n' : '${self.col_num}' '${self.cache.prompt_count}' '${self.col_p}', |
|
126 | 126 | r'\#': '${self.col_num}' '${self.cache.prompt_count}' '${self.col_p}', |
|
127 | 127 | # Just the prompt counter number, WITHOUT any coloring wrappers, so users |
|
128 | 128 | # can get numbers displayed in whatever color they want. |
|
129 | 129 | r'\N': '${self.cache.prompt_count}', |
|
130 | 130 | |
|
131 | 131 | # Prompt/history count, with the actual digits replaced by dots. Used |
|
132 | 132 | # mainly in continuation prompts (prompt_in2) |
|
133 | 133 | #r'\D': '${"."*len(str(self.cache.prompt_count))}', |
|
134 | 134 | # More robust form of the above expression, that uses __builtins__ |
|
135 | 135 | r'\D': '${"."*__builtins__.len(__builtins__.str(self.cache.prompt_count))}', |
|
136 | 136 | |
|
137 | 137 | # Current working directory |
|
138 | 138 | r'\w': '${os.getcwd()}', |
|
139 | 139 | # Current time |
|
140 | 140 | r'\t' : '${time.strftime("%H:%M:%S")}', |
|
141 | 141 | # Basename of current working directory. |
|
142 | 142 | # (use os.sep to make this portable across OSes) |
|
143 | 143 | r'\W' : '${os.getcwd().split("%s")[-1]}' % os.sep, |
|
144 | 144 | # These X<N> are an extension to the normal bash prompts. They return |
|
145 | 145 | # N terms of the path, after replacing $HOME with '~' |
|
146 | 146 | r'\X0': '${os.getcwd().replace("%s","~")}' % HOME, |
|
147 | 147 | r'\X1': '${self.cwd_filt(1)}', |
|
148 | 148 | r'\X2': '${self.cwd_filt(2)}', |
|
149 | 149 | r'\X3': '${self.cwd_filt(3)}', |
|
150 | 150 | r'\X4': '${self.cwd_filt(4)}', |
|
151 | 151 | r'\X5': '${self.cwd_filt(5)}', |
|
152 | 152 | # Y<N> are similar to X<N>, but they show '~' if it's the directory |
|
153 | 153 | # N+1 in the list. Somewhat like %cN in tcsh. |
|
154 | 154 | r'\Y0': '${self.cwd_filt2(0)}', |
|
155 | 155 | r'\Y1': '${self.cwd_filt2(1)}', |
|
156 | 156 | r'\Y2': '${self.cwd_filt2(2)}', |
|
157 | 157 | r'\Y3': '${self.cwd_filt2(3)}', |
|
158 | 158 | r'\Y4': '${self.cwd_filt2(4)}', |
|
159 | 159 | r'\Y5': '${self.cwd_filt2(5)}', |
|
160 | 160 | # Hostname up to first . |
|
161 | 161 | r'\h': HOSTNAME_SHORT, |
|
162 | 162 | # Full hostname |
|
163 | 163 | r'\H': HOSTNAME, |
|
164 | 164 | # Username of current user |
|
165 | 165 | r'\u': USER, |
|
166 | 166 | # Escaped '\' |
|
167 | 167 | '\\\\': '\\', |
|
168 | 168 | # Newline |
|
169 | 169 | r'\n': '\n', |
|
170 | 170 | # Carriage return |
|
171 | 171 | r'\r': '\r', |
|
172 | 172 | # Release version |
|
173 | 173 | r'\v': release.version, |
|
174 | 174 | # Root symbol ($ or #) |
|
175 | 175 | r'\$': ROOT_SYMBOL, |
|
176 | 176 | } |
|
177 | 177 | |
|
178 | 178 | # A copy of the prompt_specials dictionary but with all color escapes removed, |
|
179 | 179 | # so we can correctly compute the prompt length for the auto_rewrite method. |
|
180 | 180 | prompt_specials_nocolor = prompt_specials_color.copy() |
|
181 | 181 | prompt_specials_nocolor['%n'] = '${self.cache.prompt_count}' |
|
182 | 182 | prompt_specials_nocolor[r'\#'] = '${self.cache.prompt_count}' |
|
183 | 183 | |
|
184 | 184 | # Add in all the InputTermColors color escapes as valid prompt characters. |
|
185 | 185 | # They all get added as \\C_COLORNAME, so that we don't have any conflicts |
|
186 | 186 | # with a color name which may begin with a letter used by any other of the |
|
187 | 187 | # allowed specials. This of course means that \\C will never be allowed for |
|
188 | 188 | # anything else. |
|
189 | 189 | input_colors = coloransi.InputTermColors |
|
190 | 190 | for _color in dir(input_colors): |
|
191 | 191 | if _color[0] != '_': |
|
192 | 192 | c_name = r'\C_'+_color |
|
193 | 193 | prompt_specials_color[c_name] = getattr(input_colors,_color) |
|
194 | 194 | prompt_specials_nocolor[c_name] = '' |
|
195 | 195 | |
|
196 | 196 | # we default to no color for safety. Note that prompt_specials is a global |
|
197 | 197 | # variable used by all prompt objects. |
|
198 | 198 | prompt_specials = prompt_specials_nocolor |
|
199 | 199 | |
|
200 | 200 | #----------------------------------------------------------------------------- |
|
201 | 201 | def str_safe(arg): |
|
202 | 202 | """Convert to a string, without ever raising an exception. |
|
203 | 203 | |
|
204 | 204 | If str(arg) fails, <ERROR: ... > is returned, where ... is the exception |
|
205 | 205 | error message.""" |
|
206 | 206 | |
|
207 | 207 | try: |
|
208 | 208 | out = str(arg) |
|
209 | 209 | except UnicodeError: |
|
210 | 210 | try: |
|
211 | 211 | out = arg.encode('utf_8','replace') |
|
212 | 212 | except Exception,msg: |
|
213 | 213 | # let's keep this little duplication here, so that the most common |
|
214 | 214 | # case doesn't suffer from a double try wrapping. |
|
215 | 215 | out = '<ERROR: %s>' % msg |
|
216 | 216 | except Exception,msg: |
|
217 | 217 | out = '<ERROR: %s>' % msg |
|
218 | 218 | return out |
|
219 | 219 | |
|
220 | 220 | class BasePrompt(object): |
|
221 | 221 | """Interactive prompt similar to Mathematica's.""" |
|
222 | 222 | |
|
223 | 223 | def _get_p_template(self): |
|
224 | 224 | return self._p_template |
|
225 | 225 | |
|
226 | 226 | def _set_p_template(self,val): |
|
227 | 227 | self._p_template = val |
|
228 | 228 | self.set_p_str() |
|
229 | 229 | |
|
230 | 230 | p_template = property(_get_p_template,_set_p_template, |
|
231 | 231 | doc='Template for prompt string creation') |
|
232 | 232 | |
|
233 | 233 | def __init__(self,cache,sep,prompt,pad_left=False): |
|
234 | 234 | |
|
235 | 235 | # Hack: we access information about the primary prompt through the |
|
236 | 236 | # cache argument. We need this, because we want the secondary prompt |
|
237 | 237 | # to be aligned with the primary one. Color table info is also shared |
|
238 | 238 | # by all prompt classes through the cache. Nice OO spaghetti code! |
|
239 | 239 | self.cache = cache |
|
240 | 240 | self.sep = sep |
|
241 | 241 | |
|
242 | 242 | # regexp to count the number of spaces at the end of a prompt |
|
243 | 243 | # expression, useful for prompt auto-rewriting |
|
244 | 244 | self.rspace = re.compile(r'(\s*)$') |
|
245 | 245 | # Flag to left-pad prompt strings to match the length of the primary |
|
246 | 246 | # prompt |
|
247 | 247 | self.pad_left = pad_left |
|
248 | 248 | |
|
249 | 249 | # Set template to create each actual prompt (where numbers change). |
|
250 | 250 | # Use a property |
|
251 | 251 | self.p_template = prompt |
|
252 | 252 | self.set_p_str() |
|
253 | 253 | |
|
254 | 254 | def set_p_str(self): |
|
255 | 255 | """ Set the interpolating prompt strings. |
|
256 | 256 | |
|
257 | 257 | This must be called every time the color settings change, because the |
|
258 | 258 | prompt_specials global may have changed.""" |
|
259 | 259 | |
|
260 | 260 | import os,time # needed in locals for prompt string handling |
|
261 | 261 | loc = locals() |
|
262 | 262 | try: |
|
263 | 263 | self.p_str = ItplNS('%s%s%s' % |
|
264 | 264 | ('${self.sep}${self.col_p}', |
|
265 | 265 | multiple_replace(prompt_specials, self.p_template), |
|
266 | 266 | '${self.col_norm}'),self.cache.user_ns,loc) |
|
267 | 267 | |
|
268 | 268 | self.p_str_nocolor = ItplNS(multiple_replace(prompt_specials_nocolor, |
|
269 | 269 | self.p_template), |
|
270 | 270 | self.cache.user_ns,loc) |
|
271 | 271 | except: |
|
272 | 272 | print "Illegal prompt template (check $ usage!):",self.p_template |
|
273 | 273 | self.p_str = self.p_template |
|
274 | 274 | self.p_str_nocolor = self.p_template |
|
275 | 275 | |
|
276 | 276 | def write(self,msg): # dbg |
|
277 | 277 | sys.stdout.write(msg) |
|
278 | 278 | return '' |
|
279 | 279 | |
|
280 | 280 | def __str__(self): |
|
281 | 281 | """Return a string form of the prompt. |
|
282 | 282 | |
|
283 | 283 | This for is useful for continuation and output prompts, since it is |
|
284 | 284 | left-padded to match lengths with the primary one (if the |
|
285 | 285 | self.pad_left attribute is set).""" |
|
286 | 286 | |
|
287 | 287 | out_str = str_safe(self.p_str) |
|
288 | 288 | if self.pad_left: |
|
289 | 289 | # We must find the amount of padding required to match lengths, |
|
290 | 290 | # taking the color escapes (which are invisible on-screen) into |
|
291 | 291 | # account. |
|
292 | 292 | esc_pad = len(out_str) - len(str_safe(self.p_str_nocolor)) |
|
293 | 293 | format = '%%%ss' % (len(str(self.cache.last_prompt))+esc_pad) |
|
294 | 294 | return format % out_str |
|
295 | 295 | else: |
|
296 | 296 | return out_str |
|
297 | 297 | |
|
298 | 298 | # these path filters are put in as methods so that we can control the |
|
299 | 299 | # namespace where the prompt strings get evaluated |
|
300 | 300 | def cwd_filt(self,depth): |
|
301 | 301 | """Return the last depth elements of the current working directory. |
|
302 | 302 | |
|
303 | 303 | $HOME is always replaced with '~'. |
|
304 | 304 | If depth==0, the full path is returned.""" |
|
305 | 305 | |
|
306 | 306 | cwd = os.getcwd().replace(HOME,"~") |
|
307 | 307 | out = os.sep.join(cwd.split(os.sep)[-depth:]) |
|
308 | 308 | if out: |
|
309 | 309 | return out |
|
310 | 310 | else: |
|
311 | 311 | return os.sep |
|
312 | 312 | |
|
313 | 313 | def cwd_filt2(self,depth): |
|
314 | 314 | """Return the last depth elements of the current working directory. |
|
315 | 315 | |
|
316 | 316 | $HOME is always replaced with '~'. |
|
317 | 317 | If depth==0, the full path is returned.""" |
|
318 | 318 | |
|
319 | 319 | full_cwd = os.getcwd() |
|
320 | 320 | cwd = full_cwd.replace(HOME,"~").split(os.sep) |
|
321 | 321 | if '~' in cwd and len(cwd) == depth+1: |
|
322 | 322 | depth += 1 |
|
323 | 323 | drivepart = '' |
|
324 | 324 | if sys.platform == 'win32' and len(cwd) > depth: |
|
325 | 325 | drivepart = os.path.splitdrive(full_cwd)[0] |
|
326 | 326 | out = drivepart + '/'.join(cwd[-depth:]) |
|
327 | 327 | |
|
328 | 328 | if out: |
|
329 | 329 | return out |
|
330 | 330 | else: |
|
331 | 331 | return os.sep |
|
332 | 332 | |
|
333 | 333 | def __nonzero__(self): |
|
334 | 334 | """Implement boolean behavior. |
|
335 | 335 | |
|
336 | 336 | Checks whether the p_str attribute is non-empty""" |
|
337 | 337 | |
|
338 | 338 | return bool(self.p_template) |
|
339 | 339 | |
|
340 | 340 | class Prompt1(BasePrompt): |
|
341 | 341 | """Input interactive prompt similar to Mathematica's.""" |
|
342 | 342 | |
|
343 | 343 | def __init__(self,cache,sep='\n',prompt='In [\\#]: ',pad_left=True): |
|
344 | 344 | BasePrompt.__init__(self,cache,sep,prompt,pad_left) |
|
345 | 345 | |
|
346 | 346 | def set_colors(self): |
|
347 | 347 | self.set_p_str() |
|
348 | 348 | Colors = self.cache.color_table.active_colors # shorthand |
|
349 | 349 | self.col_p = Colors.in_prompt |
|
350 | 350 | self.col_num = Colors.in_number |
|
351 | 351 | self.col_norm = Colors.in_normal |
|
352 | 352 | # We need a non-input version of these escapes for the '--->' |
|
353 | 353 | # auto-call prompts used in the auto_rewrite() method. |
|
354 | 354 | self.col_p_ni = self.col_p.replace('\001','').replace('\002','') |
|
355 | 355 | self.col_norm_ni = Colors.normal |
|
356 | 356 | |
|
357 | 357 | def __str__(self): |
|
358 | 358 | self.cache.prompt_count += 1 |
|
359 | 359 | self.cache.last_prompt = str_safe(self.p_str_nocolor).split('\n')[-1] |
|
360 | 360 | return str_safe(self.p_str) |
|
361 | 361 | |
|
362 | 362 | def auto_rewrite(self): |
|
363 | 363 | """Print a string of the form '--->' which lines up with the previous |
|
364 | 364 | input string. Useful for systems which re-write the user input when |
|
365 | 365 | handling automatically special syntaxes.""" |
|
366 | 366 | |
|
367 | 367 | curr = str(self.cache.last_prompt) |
|
368 | 368 | nrspaces = len(self.rspace.search(curr).group()) |
|
369 | 369 | return '%s%s>%s%s' % (self.col_p_ni,'-'*(len(curr)-nrspaces-1), |
|
370 | 370 | ' '*nrspaces,self.col_norm_ni) |
|
371 | 371 | |
|
372 | 372 | class PromptOut(BasePrompt): |
|
373 | 373 | """Output interactive prompt similar to Mathematica's.""" |
|
374 | 374 | |
|
375 | 375 | def __init__(self,cache,sep='',prompt='Out[\\#]: ',pad_left=True): |
|
376 | 376 | BasePrompt.__init__(self,cache,sep,prompt,pad_left) |
|
377 | 377 | if not self.p_template: |
|
378 | 378 | self.__str__ = lambda: '' |
|
379 | 379 | |
|
380 | 380 | def set_colors(self): |
|
381 | 381 | self.set_p_str() |
|
382 | 382 | Colors = self.cache.color_table.active_colors # shorthand |
|
383 | 383 | self.col_p = Colors.out_prompt |
|
384 | 384 | self.col_num = Colors.out_number |
|
385 | 385 | self.col_norm = Colors.normal |
|
386 | 386 | |
|
387 | 387 | class Prompt2(BasePrompt): |
|
388 | 388 | """Interactive continuation prompt.""" |
|
389 | 389 | |
|
390 | 390 | def __init__(self,cache,prompt=' .\\D.: ',pad_left=True): |
|
391 | 391 | self.cache = cache |
|
392 | 392 | self.p_template = prompt |
|
393 | 393 | self.pad_left = pad_left |
|
394 | 394 | self.set_p_str() |
|
395 | 395 | |
|
396 | 396 | def set_p_str(self): |
|
397 | 397 | import os,time # needed in locals for prompt string handling |
|
398 | 398 | loc = locals() |
|
399 | 399 | self.p_str = ItplNS('%s%s%s' % |
|
400 | 400 | ('${self.col_p2}', |
|
401 | 401 | multiple_replace(prompt_specials, self.p_template), |
|
402 | 402 | '$self.col_norm'), |
|
403 | 403 | self.cache.user_ns,loc) |
|
404 | 404 | self.p_str_nocolor = ItplNS(multiple_replace(prompt_specials_nocolor, |
|
405 | 405 | self.p_template), |
|
406 | 406 | self.cache.user_ns,loc) |
|
407 | 407 | |
|
408 | 408 | def set_colors(self): |
|
409 | 409 | self.set_p_str() |
|
410 | 410 | Colors = self.cache.color_table.active_colors |
|
411 | 411 | self.col_p2 = Colors.in_prompt2 |
|
412 | 412 | self.col_norm = Colors.in_normal |
|
413 | 413 | # FIXME (2004-06-16) HACK: prevent crashes for users who haven't |
|
414 | 414 | # updated their prompt_in2 definitions. Remove eventually. |
|
415 | 415 | self.col_p = Colors.out_prompt |
|
416 | 416 | self.col_num = Colors.out_number |
|
417 | 417 | |
|
418 | 418 | |
|
419 | 419 | #----------------------------------------------------------------------------- |
|
420 | 420 | class CachedOutput: |
|
421 | 421 | """Class for printing output from calculations while keeping a cache of |
|
422 | 422 | reults. It dynamically creates global variables prefixed with _ which |
|
423 | 423 | contain these results. |
|
424 | 424 | |
|
425 | 425 | Meant to be used as a sys.displayhook replacement, providing numbered |
|
426 | 426 | prompts and cache services. |
|
427 | 427 | |
|
428 | 428 | Initialize with initial and final values for cache counter (this defines |
|
429 | 429 | the maximum size of the cache.""" |
|
430 | 430 | |
|
431 | 431 | def __init__(self,shell,cache_size,Pprint, |
|
432 | 432 | colors='NoColor',input_sep='\n', |
|
433 | 433 | output_sep='\n',output_sep2='', |
|
434 | 434 | ps1 = None, ps2 = None,ps_out = None,pad_left=True): |
|
435 | 435 | |
|
436 | 436 | cache_size_min = 3 |
|
437 | 437 | if cache_size <= 0: |
|
438 | 438 | self.do_full_cache = 0 |
|
439 | 439 | cache_size = 0 |
|
440 | 440 | elif cache_size < cache_size_min: |
|
441 | 441 | self.do_full_cache = 0 |
|
442 | 442 | cache_size = 0 |
|
443 | 443 | warn('caching was disabled (min value for cache size is %s).' % |
|
444 | 444 | cache_size_min,level=3) |
|
445 | 445 | else: |
|
446 | 446 | self.do_full_cache = 1 |
|
447 | 447 | |
|
448 | 448 | self.cache_size = cache_size |
|
449 | 449 | self.input_sep = input_sep |
|
450 | 450 | |
|
451 | 451 | # we need a reference to the user-level namespace |
|
452 | 452 | self.shell = shell |
|
453 | 453 | self.user_ns = shell.user_ns |
|
454 | 454 | # and to the user's input |
|
455 | 455 | self.input_hist = shell.input_hist |
|
456 | 456 | # and to the user's logger, for logging output |
|
457 | 457 | self.logger = shell.logger |
|
458 | 458 | |
|
459 | 459 | # Set input prompt strings and colors |
|
460 | 460 | if cache_size == 0: |
|
461 | 461 | if ps1.find('%n') > -1 or ps1.find(r'\#') > -1 \ |
|
462 | 462 | or ps1.find(r'\N') > -1: |
|
463 | 463 | ps1 = '>>> ' |
|
464 | 464 | if ps2.find('%n') > -1 or ps2.find(r'\#') > -1 \ |
|
465 | 465 | or ps2.find(r'\N') > -1: |
|
466 | 466 | ps2 = '... ' |
|
467 | 467 | self.ps1_str = self._set_prompt_str(ps1,'In [\\#]: ','>>> ') |
|
468 | 468 | self.ps2_str = self._set_prompt_str(ps2,' .\\D.: ','... ') |
|
469 | 469 | self.ps_out_str = self._set_prompt_str(ps_out,'Out[\\#]: ','') |
|
470 | 470 | |
|
471 | 471 | self.color_table = PromptColors |
|
472 | 472 | self.prompt1 = Prompt1(self,sep=input_sep,prompt=self.ps1_str, |
|
473 | 473 | pad_left=pad_left) |
|
474 | 474 | self.prompt2 = Prompt2(self,prompt=self.ps2_str,pad_left=pad_left) |
|
475 | 475 | self.prompt_out = PromptOut(self,sep='',prompt=self.ps_out_str, |
|
476 | 476 | pad_left=pad_left) |
|
477 | 477 | self.set_colors(colors) |
|
478 | 478 | |
|
479 | 479 | # other more normal stuff |
|
480 | 480 | # b/c each call to the In[] prompt raises it by 1, even the first. |
|
481 | 481 | self.prompt_count = 0 |
|
482 | 482 | # Store the last prompt string each time, we need it for aligning |
|
483 | 483 | # continuation and auto-rewrite prompts |
|
484 | 484 | self.last_prompt = '' |
|
485 | 485 | self.Pprint = Pprint |
|
486 | 486 | self.output_sep = output_sep |
|
487 | 487 | self.output_sep2 = output_sep2 |
|
488 | 488 | self._,self.__,self.___ = '','','' |
|
489 | 489 | self.pprint_types = map(type,[(),[],{}]) |
|
490 | 490 | |
|
491 | 491 | # these are deliberately global: |
|
492 | 492 | to_user_ns = {'_':self._,'__':self.__,'___':self.___} |
|
493 | 493 | self.user_ns.update(to_user_ns) |
|
494 | 494 | |
|
495 | 495 | def _set_prompt_str(self,p_str,cache_def,no_cache_def): |
|
496 | 496 | if p_str is None: |
|
497 | 497 | if self.do_full_cache: |
|
498 | 498 | return cache_def |
|
499 | 499 | else: |
|
500 | 500 | return no_cache_def |
|
501 | 501 | else: |
|
502 | 502 | return p_str |
|
503 | 503 | |
|
504 | 504 | def set_colors(self,colors): |
|
505 | 505 | """Set the active color scheme and configure colors for the three |
|
506 | 506 | prompt subsystems.""" |
|
507 | 507 | |
|
508 | 508 | # FIXME: the prompt_specials global should be gobbled inside this |
|
509 | 509 | # class instead. Do it when cleaning up the whole 3-prompt system. |
|
510 | 510 | global prompt_specials |
|
511 | 511 | if colors.lower()=='nocolor': |
|
512 | 512 | prompt_specials = prompt_specials_nocolor |
|
513 | 513 | else: |
|
514 | 514 | prompt_specials = prompt_specials_color |
|
515 | 515 | |
|
516 | 516 | self.color_table.set_active_scheme(colors) |
|
517 | 517 | self.prompt1.set_colors() |
|
518 | 518 | self.prompt2.set_colors() |
|
519 | 519 | self.prompt_out.set_colors() |
|
520 | 520 | |
|
521 | 521 | def __call__(self,arg=None): |
|
522 | 522 | """Printing with history cache management. |
|
523 | 523 | |
|
524 | 524 | This is invoked everytime the interpreter needs to print, and is |
|
525 | 525 | activated by setting the variable sys.displayhook to it.""" |
|
526 | 526 | |
|
527 | 527 | # If something injected a '_' variable in __builtin__, delete |
|
528 | 528 | # ipython's automatic one so we don't clobber that. gettext() in |
|
529 | 529 | # particular uses _, so we need to stay away from it. |
|
530 | 530 | if '_' in __builtin__.__dict__: |
|
531 | 531 | try: |
|
532 | 532 | del self.user_ns['_'] |
|
533 | 533 | except KeyError: |
|
534 | 534 | pass |
|
535 | 535 | if arg is not None: |
|
536 | ||
|
537 | # and now call a possibly user-defined print mechanism | |
|
538 | try: | |
|
539 | manipulated_val = self.display(arg) | |
|
540 | except TypeError: | |
|
541 | # If the user's display hook didn't return a string we can | |
|
542 | # print, we're done. Happens commonly if they return None | |
|
543 | return | |
|
544 | ||
|
545 | # user display hooks can change the variable to be stored in | |
|
546 | # output history | |
|
547 | if manipulated_val is not None: | |
|
548 | arg = manipulated_val | |
|
549 | ||
|
536 | 550 | cout_write = Term.cout.write # fast lookup |
|
537 | 551 | # first handle the cache and counters |
|
538 | 552 | |
|
539 | 553 | # do not print output if input ends in ';' |
|
540 | 554 | try: |
|
541 | 555 | if self.input_hist[self.prompt_count].endswith(';\n'): |
|
542 | 556 | return |
|
543 | 557 | except IndexError: |
|
544 | 558 | # some uses of ipshellembed may fail here |
|
545 | 559 | pass |
|
546 | 560 | # don't use print, puts an extra space |
|
547 | 561 | cout_write(self.output_sep) |
|
548 | 562 | outprompt = self.shell.hooks.generate_output_prompt() |
|
549 | 563 | # print "Got prompt: ", outprompt |
|
550 | 564 | if self.do_full_cache: |
|
551 | 565 | cout_write(outprompt) |
|
552 | 566 | else: |
|
553 | 567 | print "self.do_full_cache = False" |
|
554 | 568 | |
|
555 | # and now call a possibly user-defined print mechanism | |
|
556 | manipulated_val = self.display(arg) | |
|
557 | ||
|
558 | # user display hooks can change the variable to be stored in | |
|
559 | # output history | |
|
560 | ||
|
561 | if manipulated_val is not None: | |
|
562 | arg = manipulated_val | |
|
563 | ||
|
564 | 569 | # avoid recursive reference when displaying _oh/Out |
|
565 | 570 | if arg is not self.user_ns['_oh']: |
|
566 | 571 | self.update(arg) |
|
567 | 572 | |
|
568 | 573 | if self.logger.log_output: |
|
569 | 574 | self.logger.log_write(repr(arg),'output') |
|
570 | 575 | cout_write(self.output_sep2) |
|
571 | 576 | Term.cout.flush() |
|
572 | 577 | |
|
573 | 578 | def _display(self,arg): |
|
574 | 579 | """Default printer method, uses pprint. |
|
575 | 580 | |
|
576 | 581 | Do ip.set_hook("result_display", my_displayhook) for custom result |
|
577 | 582 | display, e.g. when your own objects need special formatting. |
|
578 | 583 | """ |
|
579 | 584 | try: |
|
580 | 585 | return IPython.utils.generics.result_display(arg) |
|
581 | 586 | except TryNext: |
|
582 | 587 | return self.shell.hooks.result_display(arg) |
|
583 | 588 | |
|
584 | 589 | # Assign the default display method: |
|
585 | 590 | display = _display |
|
586 | 591 | |
|
587 | 592 | def update(self,arg): |
|
588 | 593 | #print '***cache_count', self.cache_count # dbg |
|
589 | 594 | if len(self.user_ns['_oh']) >= self.cache_size and self.do_full_cache: |
|
590 | 595 | warn('Output cache limit (currently '+ |
|
591 | 596 | `self.cache_size`+' entries) hit.\n' |
|
592 | 597 | 'Flushing cache and resetting history counter...\n' |
|
593 | 598 | 'The only history variables available will be _,__,___ and _1\n' |
|
594 | 599 | 'with the current result.') |
|
595 | 600 | |
|
596 | 601 | self.flush() |
|
597 | 602 | # Don't overwrite '_' and friends if '_' is in __builtin__ (otherwise |
|
598 | 603 | # we cause buggy behavior for things like gettext). |
|
599 | 604 | if '_' not in __builtin__.__dict__: |
|
600 | 605 | self.___ = self.__ |
|
601 | 606 | self.__ = self._ |
|
602 | 607 | self._ = arg |
|
603 | 608 | self.user_ns.update({'_':self._,'__':self.__,'___':self.___}) |
|
604 | 609 | |
|
605 | 610 | # hackish access to top-level namespace to create _1,_2... dynamically |
|
606 | 611 | to_main = {} |
|
607 | 612 | if self.do_full_cache: |
|
608 | 613 | new_result = '_'+`self.prompt_count` |
|
609 | 614 | to_main[new_result] = arg |
|
610 | 615 | self.user_ns.update(to_main) |
|
611 | 616 | self.user_ns['_oh'][self.prompt_count] = arg |
|
612 | 617 | |
|
613 | 618 | def flush(self): |
|
614 | 619 | if not self.do_full_cache: |
|
615 | 620 | raise ValueError,"You shouldn't have reached the cache flush "\ |
|
616 | 621 | "if full caching is not enabled!" |
|
617 | 622 | # delete auto-generated vars from global namespace |
|
618 | 623 | |
|
619 | 624 | for n in range(1,self.prompt_count + 1): |
|
620 | 625 | key = '_'+`n` |
|
621 | 626 | try: |
|
622 | 627 | del self.user_ns[key] |
|
623 | 628 | except: pass |
|
624 | 629 | self.user_ns['_oh'].clear() |
|
625 | 630 | |
|
626 | 631 | if '_' not in __builtin__.__dict__: |
|
627 | 632 | self.user_ns.update({'_':None,'__':None, '___':None}) |
|
628 | 633 | import gc |
|
629 | 634 | gc.collect() # xxx needed? |
|
630 | 635 |
@@ -1,38 +1,40 b'' | |||
|
1 | #!/usr/bin/env python | |
|
2 | # encoding: utf-8 | |
|
1 | # coding: utf-8 | |
|
3 | 2 | """ |
|
4 | 3 | A simple class for quitting IPython. |
|
5 | 4 | |
|
6 |
Authors |
|
|
7 | ||
|
5 | Authors | |
|
6 | ------- | |
|
7 | * Fernando Perez | |
|
8 | 8 | * Brian Granger |
|
9 | 9 | """ |
|
10 | 10 | |
|
11 | 11 | #----------------------------------------------------------------------------- |
|
12 | 12 | # Copyright (C) 2008-2009 The IPython Development Team |
|
13 | 13 | # |
|
14 | 14 | # Distributed under the terms of the BSD License. The full license is in |
|
15 | 15 | # the file COPYING, distributed as part of this software. |
|
16 | 16 | #----------------------------------------------------------------------------- |
|
17 | 17 | |
|
18 | 18 | #----------------------------------------------------------------------------- |
|
19 | 19 | # Imports |
|
20 | 20 | #----------------------------------------------------------------------------- |
|
21 | 21 | |
|
22 | import sys | |
|
22 | 23 | |
|
23 | 24 | class Quitter(object): |
|
24 | 25 | """Simple class to handle exit, similar to Python 2.5's. |
|
25 | 26 | |
|
26 | 27 | It handles exiting in an ipython-safe manner, which the one in Python 2.5 |
|
27 | 28 | doesn't do (obviously, since it doesn't know about ipython).""" |
|
28 | 29 | |
|
29 | 30 | def __init__(self, shell, name): |
|
30 | 31 | self.shell = shell |
|
31 | 32 | self.name = name |
|
32 | 33 | |
|
33 |
def __ |
|
|
34 | def __str__(self): | |
|
34 | 35 | return 'Type %s() to exit.' % self.name |
|
35 | __str__ = __repr__ | |
|
36 | 36 | |
|
37 | 37 | def __call__(self): |
|
38 | self.shell.exit() No newline at end of file | |
|
38 | self.shell.ask_exit() | |
|
39 | ||
|
40 | __repr__ = __call__ |
@@ -1,331 +1,332 b'' | |||
|
1 | 1 | """Tests for various magic functions. |
|
2 | 2 | |
|
3 | 3 | Needs to be run by nose (to make ipython session available). |
|
4 | 4 | """ |
|
5 | 5 | |
|
6 | 6 | import os |
|
7 | 7 | import sys |
|
8 | 8 | import tempfile |
|
9 | 9 | import types |
|
10 | 10 | from cStringIO import StringIO |
|
11 | 11 | |
|
12 | 12 | import nose.tools as nt |
|
13 | 13 | |
|
14 | from IPython.core.iplib import get_ipython | |
|
14 | 15 | from IPython.utils.platutils import find_cmd, get_long_path_name |
|
15 | 16 | from IPython.testing import decorators as dec |
|
16 | 17 | from IPython.testing import tools as tt |
|
17 | 18 | |
|
18 | 19 | #----------------------------------------------------------------------------- |
|
19 | 20 | # Test functions begin |
|
20 | 21 | |
|
21 | 22 | def test_rehashx(): |
|
22 | 23 | # clear up everything |
|
23 | 24 | _ip = get_ipython() |
|
24 | 25 | _ip.alias_manager.alias_table.clear() |
|
25 | 26 | del _ip.db['syscmdlist'] |
|
26 | 27 | |
|
27 | 28 | _ip.magic('rehashx') |
|
28 | 29 | # Practically ALL ipython development systems will have more than 10 aliases |
|
29 | 30 | |
|
30 | 31 | yield (nt.assert_true, len(_ip.alias_manager.alias_table) > 10) |
|
31 | 32 | for key, val in _ip.alias_manager.alias_table.items(): |
|
32 | 33 | # we must strip dots from alias names |
|
33 | 34 | nt.assert_true('.' not in key) |
|
34 | 35 | |
|
35 | 36 | # rehashx must fill up syscmdlist |
|
36 | 37 | scoms = _ip.db['syscmdlist'] |
|
37 | 38 | yield (nt.assert_true, len(scoms) > 10) |
|
38 | 39 | |
|
39 | 40 | |
|
40 | 41 | def doctest_hist_f(): |
|
41 | 42 | """Test %hist -f with temporary filename. |
|
42 | 43 | |
|
43 | 44 | In [9]: import tempfile |
|
44 | 45 | |
|
45 | 46 | In [10]: tfile = tempfile.mktemp('.py','tmp-ipython-') |
|
46 | 47 | |
|
47 | 48 | In [11]: %hist -n -f $tfile 3 |
|
48 | 49 | """ |
|
49 | 50 | |
|
50 | 51 | |
|
51 | 52 | def doctest_hist_r(): |
|
52 | 53 | """Test %hist -r |
|
53 | 54 | |
|
54 | 55 | XXX - This test is not recording the output correctly. Not sure why... |
|
55 | 56 | |
|
56 | 57 | In [20]: 'hist' in _ip.lsmagic() |
|
57 | 58 | Out[20]: True |
|
58 | 59 | |
|
59 | 60 | In [6]: x=1 |
|
60 | 61 | |
|
61 | 62 | In [7]: %hist -n -r 2 |
|
62 | 63 | x=1 # random |
|
63 | 64 | hist -n -r 2 # random |
|
64 | 65 | """ |
|
65 | 66 | |
|
66 | 67 | # This test is known to fail on win32. |
|
67 | 68 | # See ticket https://bugs.launchpad.net/bugs/366334 |
|
68 | 69 | def test_obj_del(): |
|
69 | 70 | _ip = get_ipython() |
|
70 | 71 | """Test that object's __del__ methods are called on exit.""" |
|
71 | 72 | test_dir = os.path.dirname(__file__) |
|
72 | 73 | del_file = os.path.join(test_dir,'obj_del.py') |
|
73 | 74 | ipython_cmd = find_cmd('ipython') |
|
74 | 75 | out = _ip.getoutput('%s %s' % (ipython_cmd, del_file)) |
|
75 | 76 | nt.assert_equals(out,'obj_del.py: object A deleted') |
|
76 | 77 | |
|
77 | 78 | |
|
78 | 79 | def test_shist(): |
|
79 | 80 | # Simple tests of ShadowHist class - test generator. |
|
80 | 81 | import os, shutil, tempfile |
|
81 | 82 | |
|
82 | 83 | from IPython.utils import pickleshare |
|
83 | 84 | from IPython.core.history import ShadowHist |
|
84 | 85 | |
|
85 | 86 | tfile = tempfile.mktemp('','tmp-ipython-') |
|
86 | 87 | |
|
87 | 88 | db = pickleshare.PickleShareDB(tfile) |
|
88 | 89 | s = ShadowHist(db) |
|
89 | 90 | s.add('hello') |
|
90 | 91 | s.add('world') |
|
91 | 92 | s.add('hello') |
|
92 | 93 | s.add('hello') |
|
93 | 94 | s.add('karhu') |
|
94 | 95 | |
|
95 | 96 | yield nt.assert_equals,s.all(),[(1, 'hello'), (2, 'world'), (3, 'karhu')] |
|
96 | 97 | |
|
97 | 98 | yield nt.assert_equal,s.get(2),'world' |
|
98 | 99 | |
|
99 | 100 | shutil.rmtree(tfile) |
|
100 | 101 | |
|
101 | 102 | @dec.skipif_not_numpy |
|
102 | 103 | def test_numpy_clear_array_undec(): |
|
103 | 104 | from IPython.extensions import clearcmd |
|
104 | 105 | |
|
105 | 106 | _ip.ex('import numpy as np') |
|
106 | 107 | _ip.ex('a = np.empty(2)') |
|
107 | 108 | yield (nt.assert_true, 'a' in _ip.user_ns) |
|
108 | 109 | _ip.magic('clear array') |
|
109 | 110 | yield (nt.assert_false, 'a' in _ip.user_ns) |
|
110 | 111 | |
|
111 | 112 | |
|
112 | 113 | @dec.skip() |
|
113 | 114 | def test_fail_dec(*a,**k): |
|
114 | 115 | yield nt.assert_true, False |
|
115 | 116 | |
|
116 | 117 | @dec.skip('This one shouldn not run') |
|
117 | 118 | def test_fail_dec2(*a,**k): |
|
118 | 119 | yield nt.assert_true, False |
|
119 | 120 | |
|
120 | 121 | @dec.skipknownfailure |
|
121 | 122 | def test_fail_dec3(*a,**k): |
|
122 | 123 | yield nt.assert_true, False |
|
123 | 124 | |
|
124 | 125 | |
|
125 | 126 | def doctest_refbug(): |
|
126 | 127 | """Very nasty problem with references held by multiple runs of a script. |
|
127 | 128 | See: https://bugs.launchpad.net/ipython/+bug/269966 |
|
128 | 129 | |
|
129 | 130 | In [1]: _ip.clear_main_mod_cache() |
|
130 | 131 | |
|
131 | 132 | In [2]: run refbug |
|
132 | 133 | |
|
133 | 134 | In [3]: call_f() |
|
134 | 135 | lowercased: hello |
|
135 | 136 | |
|
136 | 137 | In [4]: run refbug |
|
137 | 138 | |
|
138 | 139 | In [5]: call_f() |
|
139 | 140 | lowercased: hello |
|
140 | 141 | lowercased: hello |
|
141 | 142 | """ |
|
142 | 143 | |
|
143 | 144 | #----------------------------------------------------------------------------- |
|
144 | 145 | # Tests for %run |
|
145 | 146 | #----------------------------------------------------------------------------- |
|
146 | 147 | |
|
147 | 148 | # %run is critical enough that it's a good idea to have a solid collection of |
|
148 | 149 | # tests for it, some as doctests and some as normal tests. |
|
149 | 150 | |
|
150 | 151 | def doctest_run_ns(): |
|
151 | 152 | """Classes declared %run scripts must be instantiable afterwards. |
|
152 | 153 | |
|
153 | 154 | In [11]: run tclass foo |
|
154 | 155 | |
|
155 | 156 | In [12]: isinstance(f(),foo) |
|
156 | 157 | Out[12]: True |
|
157 | 158 | """ |
|
158 | 159 | |
|
159 | 160 | |
|
160 | 161 | def doctest_run_ns2(): |
|
161 | 162 | """Classes declared %run scripts must be instantiable afterwards. |
|
162 | 163 | |
|
163 | 164 | In [4]: run tclass C-first_pass |
|
164 | 165 | |
|
165 | 166 | In [5]: run tclass C-second_pass |
|
166 | 167 | tclass.py: deleting object: C-first_pass |
|
167 | 168 | """ |
|
168 | 169 | |
|
169 | 170 | def doctest_run_builtins(): |
|
170 | 171 | """Check that %run doesn't damage __builtins__ via a doctest. |
|
171 | 172 | |
|
172 | 173 | This is similar to the test_run_builtins, but I want *both* forms of the |
|
173 | 174 | test to catch any possible glitches in our testing machinery, since that |
|
174 | 175 | modifies %run somewhat. So for this, we have both a normal test (below) |
|
175 | 176 | and a doctest (this one). |
|
176 | 177 | |
|
177 | 178 | In [1]: import tempfile |
|
178 | 179 | |
|
179 | 180 | In [2]: bid1 = id(__builtins__) |
|
180 | 181 | |
|
181 | 182 | In [3]: fname = tempfile.mkstemp()[1] |
|
182 | 183 | |
|
183 | 184 | In [3]: f = open(fname,'w') |
|
184 | 185 | |
|
185 | 186 | In [4]: f.write('pass\\n') |
|
186 | 187 | |
|
187 | 188 | In [5]: f.flush() |
|
188 | 189 | |
|
189 | 190 | In [6]: print type(__builtins__) |
|
190 | 191 | <type 'module'> |
|
191 | 192 | |
|
192 | 193 | In [7]: %run "$fname" |
|
193 | 194 | |
|
194 | 195 | In [7]: f.close() |
|
195 | 196 | |
|
196 | 197 | In [8]: bid2 = id(__builtins__) |
|
197 | 198 | |
|
198 | 199 | In [9]: print type(__builtins__) |
|
199 | 200 | <type 'module'> |
|
200 | 201 | |
|
201 | 202 | In [10]: bid1 == bid2 |
|
202 | 203 | Out[10]: True |
|
203 | 204 | |
|
204 | 205 | In [12]: try: |
|
205 | 206 | ....: os.unlink(fname) |
|
206 | 207 | ....: except: |
|
207 | 208 | ....: pass |
|
208 | 209 | ....: |
|
209 | 210 | """ |
|
210 | 211 | |
|
211 | 212 | # For some tests, it will be handy to organize them in a class with a common |
|
212 | 213 | # setup that makes a temp file |
|
213 | 214 | |
|
214 | 215 | class TestMagicRun(object): |
|
215 | 216 | |
|
216 | 217 | def setup(self): |
|
217 | 218 | """Make a valid python temp file.""" |
|
218 | 219 | fname = tempfile.mkstemp()[1] |
|
219 | 220 | f = open(fname,'w') |
|
220 | 221 | f.write('pass\n') |
|
221 | 222 | f.flush() |
|
222 | 223 | self.tmpfile = f |
|
223 | 224 | self.fname = fname |
|
224 | 225 | |
|
225 | 226 | def run_tmpfile(self): |
|
226 | 227 | _ip = get_ipython() |
|
227 | 228 | # This fails on Windows if self.tmpfile.name has spaces or "~" in it. |
|
228 | 229 | # See below and ticket https://bugs.launchpad.net/bugs/366353 |
|
229 | 230 | _ip.magic('run "%s"' % self.fname) |
|
230 | 231 | |
|
231 | 232 | def test_builtins_id(self): |
|
232 | 233 | """Check that %run doesn't damage __builtins__ """ |
|
233 | 234 | _ip = get_ipython() |
|
234 | 235 | # Test that the id of __builtins__ is not modified by %run |
|
235 | 236 | bid1 = id(_ip.user_ns['__builtins__']) |
|
236 | 237 | self.run_tmpfile() |
|
237 | 238 | bid2 = id(_ip.user_ns['__builtins__']) |
|
238 | 239 | tt.assert_equals(bid1, bid2) |
|
239 | 240 | |
|
240 | 241 | def test_builtins_type(self): |
|
241 | 242 | """Check that the type of __builtins__ doesn't change with %run. |
|
242 | 243 | |
|
243 | 244 | However, the above could pass if __builtins__ was already modified to |
|
244 | 245 | be a dict (it should be a module) by a previous use of %run. So we |
|
245 | 246 | also check explicitly that it really is a module: |
|
246 | 247 | """ |
|
247 | 248 | _ip = get_ipython() |
|
248 | 249 | self.run_tmpfile() |
|
249 | 250 | tt.assert_equals(type(_ip.user_ns['__builtins__']),type(sys)) |
|
250 | 251 | |
|
251 | 252 | def test_prompts(self): |
|
252 | 253 | """Test that prompts correctly generate after %run""" |
|
253 | 254 | self.run_tmpfile() |
|
254 | 255 | _ip = get_ipython() |
|
255 | 256 | p2 = str(_ip.outputcache.prompt2).strip() |
|
256 | 257 | nt.assert_equals(p2[:3], '...') |
|
257 | 258 | |
|
258 | 259 | def teardown(self): |
|
259 | 260 | self.tmpfile.close() |
|
260 | 261 | try: |
|
261 | 262 | os.unlink(self.fname) |
|
262 | 263 | except: |
|
263 | 264 | # On Windows, even though we close the file, we still can't delete |
|
264 | 265 | # it. I have no clue why |
|
265 | 266 | pass |
|
266 | 267 | |
|
267 | 268 | # Multiple tests for clipboard pasting |
|
268 | 269 | def test_paste(): |
|
269 | 270 | _ip = get_ipython() |
|
270 | 271 | def paste(txt, flags='-q'): |
|
271 | 272 | """Paste input text, by default in quiet mode""" |
|
272 | 273 | hooks.clipboard_get = lambda : txt |
|
273 | 274 | _ip.magic('paste '+flags) |
|
274 | 275 | |
|
275 | 276 | # Inject fake clipboard hook but save original so we can restore it later |
|
276 | 277 | hooks = _ip.hooks |
|
277 | 278 | user_ns = _ip.user_ns |
|
278 | 279 | original_clip = hooks.clipboard_get |
|
279 | 280 | |
|
280 | 281 | try: |
|
281 | 282 | # This try/except with an emtpy except clause is here only because |
|
282 | 283 | # try/yield/finally is invalid syntax in Python 2.4. This will be |
|
283 | 284 | # removed when we drop 2.4-compatibility, and the emtpy except below |
|
284 | 285 | # will be changed to a finally. |
|
285 | 286 | |
|
286 | 287 | # Run tests with fake clipboard function |
|
287 | 288 | user_ns.pop('x', None) |
|
288 | 289 | paste('x=1') |
|
289 | 290 | yield (nt.assert_equal, user_ns['x'], 1) |
|
290 | 291 | |
|
291 | 292 | user_ns.pop('x', None) |
|
292 | 293 | paste('>>> x=2') |
|
293 | 294 | yield (nt.assert_equal, user_ns['x'], 2) |
|
294 | 295 | |
|
295 | 296 | paste(""" |
|
296 | 297 | >>> x = [1,2,3] |
|
297 | 298 | >>> y = [] |
|
298 | 299 | >>> for i in x: |
|
299 | 300 | ... y.append(i**2) |
|
300 | 301 | ... |
|
301 | 302 | """) |
|
302 | 303 | yield (nt.assert_equal, user_ns['x'], [1,2,3]) |
|
303 | 304 | yield (nt.assert_equal, user_ns['y'], [1,4,9]) |
|
304 | 305 | |
|
305 | 306 | # Now, test that paste -r works |
|
306 | 307 | user_ns.pop('x', None) |
|
307 | 308 | yield (nt.assert_false, 'x' in user_ns) |
|
308 | 309 | _ip.magic('paste -r') |
|
309 | 310 | yield (nt.assert_equal, user_ns['x'], [1,2,3]) |
|
310 | 311 | |
|
311 | 312 | # Also test paste echoing, by temporarily faking the writer |
|
312 | 313 | w = StringIO() |
|
313 | 314 | writer = _ip.write |
|
314 | 315 | _ip.write = w.write |
|
315 | 316 | code = """ |
|
316 | 317 | a = 100 |
|
317 | 318 | b = 200""" |
|
318 | 319 | try: |
|
319 | 320 | paste(code,'') |
|
320 | 321 | out = w.getvalue() |
|
321 | 322 | finally: |
|
322 | 323 | _ip.write = writer |
|
323 | 324 | yield (nt.assert_equal, user_ns['a'], 100) |
|
324 | 325 | yield (nt.assert_equal, user_ns['b'], 200) |
|
325 | 326 | yield (nt.assert_equal, out, code+"\n## -- End pasted text --\n") |
|
326 | 327 | |
|
327 | 328 | finally: |
|
328 | 329 | # This should be in a finally clause, instead of the bare except above. |
|
329 | 330 | # Restore original hook |
|
330 | 331 | hooks.clipboard_get = original_clip |
|
331 | 332 |
General Comments 0
You need to be logged in to leave comments.
Login now