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