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