##// END OF EJS Templates
Use instances of traits instead of trait classes
Jason Grout -
Show More
@@ -1,397 +1,397
1 1 # encoding: utf-8
2 2 """
3 3 An application for IPython.
4 4
5 5 All top-level applications should use the classes in this module for
6 6 handling configuration and creating configurables.
7 7
8 8 The job of an :class:`Application` is to create the master configuration
9 9 object and then create the configurable objects, passing the config to them.
10 10 """
11 11
12 12 # Copyright (c) IPython Development Team.
13 13 # Distributed under the terms of the Modified BSD License.
14 14
15 15 import atexit
16 16 import glob
17 17 import logging
18 18 import os
19 19 import shutil
20 20 import sys
21 21
22 22 from traitlets.config.application import Application, catch_config_error
23 23 from traitlets.config.loader import ConfigFileNotFound, PyFileConfigLoader
24 24 from IPython.core import release, crashhandler
25 25 from IPython.core.profiledir import ProfileDir, ProfileDirError
26 26 from IPython.paths import get_ipython_dir, get_ipython_package_dir
27 27 from IPython.utils.path import ensure_dir_exists
28 28 from IPython.utils import py3compat
29 29 from traitlets import List, Unicode, Type, Bool, Dict, Set, Instance, Undefined
30 30
31 31 if os.name == 'nt':
32 32 programdata = os.environ.get('PROGRAMDATA', None)
33 33 if programdata:
34 34 SYSTEM_CONFIG_DIRS = [os.path.join(programdata, 'ipython')]
35 35 else: # PROGRAMDATA is not defined by default on XP.
36 36 SYSTEM_CONFIG_DIRS = []
37 37 else:
38 38 SYSTEM_CONFIG_DIRS = [
39 39 "/usr/local/etc/ipython",
40 40 "/etc/ipython",
41 41 ]
42 42
43 43
44 44 # aliases and flags
45 45
46 46 base_aliases = {
47 47 'profile-dir' : 'ProfileDir.location',
48 48 'profile' : 'BaseIPythonApplication.profile',
49 49 'ipython-dir' : 'BaseIPythonApplication.ipython_dir',
50 50 'log-level' : 'Application.log_level',
51 51 'config' : 'BaseIPythonApplication.extra_config_file',
52 52 }
53 53
54 54 base_flags = dict(
55 55 debug = ({'Application' : {'log_level' : logging.DEBUG}},
56 56 "set log level to logging.DEBUG (maximize logging output)"),
57 57 quiet = ({'Application' : {'log_level' : logging.CRITICAL}},
58 58 "set log level to logging.CRITICAL (minimize logging output)"),
59 59 init = ({'BaseIPythonApplication' : {
60 60 'copy_config_files' : True,
61 61 'auto_create' : True}
62 62 }, """Initialize profile with default config files. This is equivalent
63 63 to running `ipython profile create <profile>` prior to startup.
64 64 """)
65 65 )
66 66
67 67 class ProfileAwareConfigLoader(PyFileConfigLoader):
68 68 """A Python file config loader that is aware of IPython profiles."""
69 69 def load_subconfig(self, fname, path=None, profile=None):
70 70 if profile is not None:
71 71 try:
72 72 profile_dir = ProfileDir.find_profile_dir_by_name(
73 73 get_ipython_dir(),
74 74 profile,
75 75 )
76 76 except ProfileDirError:
77 77 return
78 78 path = profile_dir.location
79 79 return super(ProfileAwareConfigLoader, self).load_subconfig(fname, path=path)
80 80
81 81 class BaseIPythonApplication(Application):
82 82
83 83 name = Unicode(u'ipython')
84 84 description = Unicode(u'IPython: an enhanced interactive Python shell.')
85 85 version = Unicode(release.version)
86 86
87 87 aliases = Dict(base_aliases)
88 88 flags = Dict(base_flags)
89 89 classes = List([ProfileDir])
90 90
91 91 # enable `load_subconfig('cfg.py', profile='name')`
92 92 python_config_loader_class = ProfileAwareConfigLoader
93 93
94 94 # Track whether the config_file has changed,
95 95 # because some logic happens only if we aren't using the default.
96 96 config_file_specified = Set()
97 97
98 98 config_file_name = Unicode()
99 99 def _config_file_name_default(self):
100 100 return self.name.replace('-','_') + u'_config.py'
101 101 def _config_file_name_changed(self, name, old, new):
102 102 if new != old:
103 103 self.config_file_specified.add(new)
104 104
105 105 # The directory that contains IPython's builtin profiles.
106 106 builtin_profile_dir = Unicode(
107 107 os.path.join(get_ipython_package_dir(), u'config', u'profile', u'default')
108 108 )
109 109
110 config_file_paths = List(Unicode)
110 config_file_paths = List(Unicode())
111 111 def _config_file_paths_default(self):
112 112 return [py3compat.getcwd()]
113 113
114 114 extra_config_file = Unicode(config=True,
115 115 help="""Path to an extra config file to load.
116 116
117 117 If specified, load this config file in addition to any other IPython config.
118 118 """)
119 119 def _extra_config_file_changed(self, name, old, new):
120 120 try:
121 121 self.config_files.remove(old)
122 122 except ValueError:
123 123 pass
124 124 self.config_file_specified.add(new)
125 125 self.config_files.append(new)
126 126
127 127 profile = Unicode(u'default', config=True,
128 128 help="""The IPython profile to use."""
129 129 )
130 130
131 131 def _profile_changed(self, name, old, new):
132 132 self.builtin_profile_dir = os.path.join(
133 133 get_ipython_package_dir(), u'config', u'profile', new
134 134 )
135 135
136 136 ipython_dir = Unicode(config=True,
137 137 help="""
138 138 The name of the IPython directory. This directory is used for logging
139 139 configuration (through profiles), history storage, etc. The default
140 140 is usually $HOME/.ipython. This option can also be specified through
141 141 the environment variable IPYTHONDIR.
142 142 """
143 143 )
144 144 def _ipython_dir_default(self):
145 145 d = get_ipython_dir()
146 146 self._ipython_dir_changed('ipython_dir', d, d)
147 147 return d
148 148
149 149 _in_init_profile_dir = False
150 150 profile_dir = Instance(ProfileDir, allow_none=True)
151 151 def _profile_dir_default(self):
152 152 # avoid recursion
153 153 if self._in_init_profile_dir:
154 154 return
155 155 # profile_dir requested early, force initialization
156 156 self.init_profile_dir()
157 157 return self.profile_dir
158 158
159 159 overwrite = Bool(False, config=True,
160 160 help="""Whether to overwrite existing config files when copying""")
161 161 auto_create = Bool(False, config=True,
162 162 help="""Whether to create profile dir if it doesn't exist""")
163 163
164 config_files = List(Unicode)
164 config_files = List(Unicode())
165 165 def _config_files_default(self):
166 166 return [self.config_file_name]
167 167
168 168 copy_config_files = Bool(False, config=True,
169 169 help="""Whether to install the default config files into the profile dir.
170 170 If a new profile is being created, and IPython contains config files for that
171 171 profile, then they will be staged into the new directory. Otherwise,
172 172 default config files will be automatically generated.
173 173 """)
174 174
175 175 verbose_crash = Bool(False, config=True,
176 176 help="""Create a massive crash report when IPython encounters what may be an
177 177 internal error. The default is to append a short message to the
178 178 usual traceback""")
179 179
180 180 # The class to use as the crash handler.
181 181 crash_handler_class = Type(crashhandler.CrashHandler)
182 182
183 183 @catch_config_error
184 184 def __init__(self, **kwargs):
185 185 super(BaseIPythonApplication, self).__init__(**kwargs)
186 186 # ensure current working directory exists
187 187 try:
188 188 directory = py3compat.getcwd()
189 189 except:
190 190 # exit if cwd doesn't exist
191 191 self.log.error("Current working directory doesn't exist.")
192 192 self.exit(1)
193 193
194 194 #-------------------------------------------------------------------------
195 195 # Various stages of Application creation
196 196 #-------------------------------------------------------------------------
197 197
198 198 def init_crash_handler(self):
199 199 """Create a crash handler, typically setting sys.excepthook to it."""
200 200 self.crash_handler = self.crash_handler_class(self)
201 201 sys.excepthook = self.excepthook
202 202 def unset_crashhandler():
203 203 sys.excepthook = sys.__excepthook__
204 204 atexit.register(unset_crashhandler)
205 205
206 206 def excepthook(self, etype, evalue, tb):
207 207 """this is sys.excepthook after init_crashhandler
208 208
209 209 set self.verbose_crash=True to use our full crashhandler, instead of
210 210 a regular traceback with a short message (crash_handler_lite)
211 211 """
212 212
213 213 if self.verbose_crash:
214 214 return self.crash_handler(etype, evalue, tb)
215 215 else:
216 216 return crashhandler.crash_handler_lite(etype, evalue, tb)
217 217
218 218 def _ipython_dir_changed(self, name, old, new):
219 219 if old is not Undefined:
220 220 str_old = py3compat.cast_bytes_py2(os.path.abspath(old),
221 221 sys.getfilesystemencoding()
222 222 )
223 223 if str_old in sys.path:
224 224 sys.path.remove(str_old)
225 225 str_path = py3compat.cast_bytes_py2(os.path.abspath(new),
226 226 sys.getfilesystemencoding()
227 227 )
228 228 sys.path.append(str_path)
229 229 ensure_dir_exists(new)
230 230 readme = os.path.join(new, 'README')
231 231 readme_src = os.path.join(get_ipython_package_dir(), u'config', u'profile', 'README')
232 232 if not os.path.exists(readme) and os.path.exists(readme_src):
233 233 shutil.copy(readme_src, readme)
234 234 for d in ('extensions', 'nbextensions'):
235 235 path = os.path.join(new, d)
236 236 try:
237 237 ensure_dir_exists(path)
238 238 except OSError as e:
239 239 # this will not be EEXIST
240 240 self.log.error("couldn't create path %s: %s", path, e)
241 241 self.log.debug("IPYTHONDIR set to: %s" % new)
242 242
243 243 def load_config_file(self, suppress_errors=True):
244 244 """Load the config file.
245 245
246 246 By default, errors in loading config are handled, and a warning
247 247 printed on screen. For testing, the suppress_errors option is set
248 248 to False, so errors will make tests fail.
249 249 """
250 250 self.log.debug("Searching path %s for config files", self.config_file_paths)
251 251 base_config = 'ipython_config.py'
252 252 self.log.debug("Attempting to load config file: %s" %
253 253 base_config)
254 254 try:
255 255 Application.load_config_file(
256 256 self,
257 257 base_config,
258 258 path=self.config_file_paths
259 259 )
260 260 except ConfigFileNotFound:
261 261 # ignore errors loading parent
262 262 self.log.debug("Config file %s not found", base_config)
263 263 pass
264 264
265 265 for config_file_name in self.config_files:
266 266 if not config_file_name or config_file_name == base_config:
267 267 continue
268 268 self.log.debug("Attempting to load config file: %s" %
269 269 self.config_file_name)
270 270 try:
271 271 Application.load_config_file(
272 272 self,
273 273 config_file_name,
274 274 path=self.config_file_paths
275 275 )
276 276 except ConfigFileNotFound:
277 277 # Only warn if the default config file was NOT being used.
278 278 if config_file_name in self.config_file_specified:
279 279 msg = self.log.warn
280 280 else:
281 281 msg = self.log.debug
282 282 msg("Config file not found, skipping: %s", config_file_name)
283 283 except Exception:
284 284 # For testing purposes.
285 285 if not suppress_errors:
286 286 raise
287 287 self.log.warn("Error loading config file: %s" %
288 288 self.config_file_name, exc_info=True)
289 289
290 290 def init_profile_dir(self):
291 291 """initialize the profile dir"""
292 292 self._in_init_profile_dir = True
293 293 if self.profile_dir is not None:
294 294 # already ran
295 295 return
296 296 if 'ProfileDir.location' not in self.config:
297 297 # location not specified, find by profile name
298 298 try:
299 299 p = ProfileDir.find_profile_dir_by_name(self.ipython_dir, self.profile, self.config)
300 300 except ProfileDirError:
301 301 # not found, maybe create it (always create default profile)
302 302 if self.auto_create or self.profile == 'default':
303 303 try:
304 304 p = ProfileDir.create_profile_dir_by_name(self.ipython_dir, self.profile, self.config)
305 305 except ProfileDirError:
306 306 self.log.fatal("Could not create profile: %r"%self.profile)
307 307 self.exit(1)
308 308 else:
309 309 self.log.info("Created profile dir: %r"%p.location)
310 310 else:
311 311 self.log.fatal("Profile %r not found."%self.profile)
312 312 self.exit(1)
313 313 else:
314 314 self.log.debug("Using existing profile dir: %r"%p.location)
315 315 else:
316 316 location = self.config.ProfileDir.location
317 317 # location is fully specified
318 318 try:
319 319 p = ProfileDir.find_profile_dir(location, self.config)
320 320 except ProfileDirError:
321 321 # not found, maybe create it
322 322 if self.auto_create:
323 323 try:
324 324 p = ProfileDir.create_profile_dir(location, self.config)
325 325 except ProfileDirError:
326 326 self.log.fatal("Could not create profile directory: %r"%location)
327 327 self.exit(1)
328 328 else:
329 329 self.log.debug("Creating new profile dir: %r"%location)
330 330 else:
331 331 self.log.fatal("Profile directory %r not found."%location)
332 332 self.exit(1)
333 333 else:
334 334 self.log.info("Using existing profile dir: %r"%location)
335 335 # if profile_dir is specified explicitly, set profile name
336 336 dir_name = os.path.basename(p.location)
337 337 if dir_name.startswith('profile_'):
338 338 self.profile = dir_name[8:]
339 339
340 340 self.profile_dir = p
341 341 self.config_file_paths.append(p.location)
342 342 self._in_init_profile_dir = False
343 343
344 344 def init_config_files(self):
345 345 """[optionally] copy default config files into profile dir."""
346 346 self.config_file_paths.extend(SYSTEM_CONFIG_DIRS)
347 347 # copy config files
348 348 path = self.builtin_profile_dir
349 349 if self.copy_config_files:
350 350 src = self.profile
351 351
352 352 cfg = self.config_file_name
353 353 if path and os.path.exists(os.path.join(path, cfg)):
354 354 self.log.warn("Staging %r from %s into %r [overwrite=%s]"%(
355 355 cfg, src, self.profile_dir.location, self.overwrite)
356 356 )
357 357 self.profile_dir.copy_config_file(cfg, path=path, overwrite=self.overwrite)
358 358 else:
359 359 self.stage_default_config_file()
360 360 else:
361 361 # Still stage *bundled* config files, but not generated ones
362 362 # This is necessary for `ipython profile=sympy` to load the profile
363 363 # on the first go
364 364 files = glob.glob(os.path.join(path, '*.py'))
365 365 for fullpath in files:
366 366 cfg = os.path.basename(fullpath)
367 367 if self.profile_dir.copy_config_file(cfg, path=path, overwrite=False):
368 368 # file was copied
369 369 self.log.warn("Staging bundled %s from %s into %r"%(
370 370 cfg, self.profile, self.profile_dir.location)
371 371 )
372 372
373 373
374 374 def stage_default_config_file(self):
375 375 """auto generate default config file, and stage it into the profile."""
376 376 s = self.generate_config_file()
377 377 fname = os.path.join(self.profile_dir.location, self.config_file_name)
378 378 if self.overwrite or not os.path.exists(fname):
379 379 self.log.warn("Generating default config file: %r"%(fname))
380 380 with open(fname, 'w') as f:
381 381 f.write(s)
382 382
383 383 @catch_config_error
384 384 def initialize(self, argv=None):
385 385 # don't hook up crash handler before parsing command-line
386 386 self.parse_command_line(argv)
387 387 self.init_crash_handler()
388 388 if self.subapp is not None:
389 389 # stop here if subapp is taking over
390 390 return
391 391 cl_config = self.config
392 392 self.init_profile_dir()
393 393 self.init_config_files()
394 394 self.load_config_file()
395 395 # enforce cl-opts override configfile opts:
396 396 self.update_config(cl_config)
397 397
@@ -1,70 +1,70
1 1 # encoding: utf-8
2 2 """
3 3 A context manager for handling sys.displayhook.
4 4
5 5 Authors:
6 6
7 7 * Robert Kern
8 8 * Brian Granger
9 9 """
10 10
11 11 #-----------------------------------------------------------------------------
12 12 # Copyright (C) 2008-2011 The IPython Development Team
13 13 #
14 14 # Distributed under the terms of the BSD License. The full license is in
15 15 # the file COPYING, distributed as part of this software.
16 16 #-----------------------------------------------------------------------------
17 17
18 18 #-----------------------------------------------------------------------------
19 19 # Imports
20 20 #-----------------------------------------------------------------------------
21 21
22 22 import sys
23 23
24 24 from traitlets.config.configurable import Configurable
25 25 from traitlets import Any
26 26
27 27 #-----------------------------------------------------------------------------
28 28 # Classes and functions
29 29 #-----------------------------------------------------------------------------
30 30
31 31
32 32 class DisplayTrap(Configurable):
33 33 """Object to manage sys.displayhook.
34 34
35 35 This came from IPython.core.kernel.display_hook, but is simplified
36 36 (no callbacks or formatters) until more of the core is refactored.
37 37 """
38 38
39 hook = Any
39 hook = Any()
40 40
41 41 def __init__(self, hook=None):
42 42 super(DisplayTrap, self).__init__(hook=hook, config=None)
43 43 self.old_hook = None
44 44 # We define this to track if a single BuiltinTrap is nested.
45 45 # Only turn off the trap when the outermost call to __exit__ is made.
46 46 self._nested_level = 0
47 47
48 48 def __enter__(self):
49 49 if self._nested_level == 0:
50 50 self.set()
51 51 self._nested_level += 1
52 52 return self
53 53
54 54 def __exit__(self, type, value, traceback):
55 55 if self._nested_level == 1:
56 56 self.unset()
57 57 self._nested_level -= 1
58 58 # Returning False will cause exceptions to propagate
59 59 return False
60 60
61 61 def set(self):
62 62 """Set the hook."""
63 63 if sys.displayhook is not self.hook:
64 64 self.old_hook = sys.displayhook
65 65 sys.displayhook = self.hook
66 66
67 67 def unset(self):
68 68 """Unset the hook."""
69 69 sys.displayhook = self.old_hook
70 70
@@ -1,972 +1,972
1 1 # -*- coding: utf-8 -*-
2 2 """Display formatters.
3 3
4 4 Inheritance diagram:
5 5
6 6 .. inheritance-diagram:: IPython.core.formatters
7 7 :parts: 3
8 8 """
9 9
10 10 # Copyright (c) IPython Development Team.
11 11 # Distributed under the terms of the Modified BSD License.
12 12
13 13 import abc
14 14 import inspect
15 15 import json
16 16 import sys
17 17 import traceback
18 18 import warnings
19 19
20 20 from decorator import decorator
21 21
22 22 from traitlets.config.configurable import Configurable
23 23 from IPython.core.getipython import get_ipython
24 24 from IPython.utils.sentinel import Sentinel
25 25 from IPython.lib import pretty
26 26 from traitlets import (
27 27 Bool, Dict, Integer, Unicode, CUnicode, ObjectName, List,
28 28 ForwardDeclaredInstance,
29 29 )
30 30 from IPython.utils.py3compat import (
31 31 with_metaclass, string_types, unicode_type,
32 32 )
33 33
34 34
35 35 #-----------------------------------------------------------------------------
36 36 # The main DisplayFormatter class
37 37 #-----------------------------------------------------------------------------
38 38
39 39
40 40 def _safe_get_formatter_method(obj, name):
41 41 """Safely get a formatter method
42 42
43 43 - Classes cannot have formatter methods, only instance
44 44 - protect against proxy objects that claim to have everything
45 45 """
46 46 if inspect.isclass(obj):
47 47 # repr methods only make sense on instances, not classes
48 48 return None
49 49 method = pretty._safe_getattr(obj, name, None)
50 50 if callable(method):
51 51 # obj claims to have repr method...
52 52 if callable(pretty._safe_getattr(obj, '_ipython_canary_method_should_not_exist_', None)):
53 53 # ...but don't trust proxy objects that claim to have everything
54 54 return None
55 55 return method
56 56
57 57
58 58 class DisplayFormatter(Configurable):
59 59
60 60 # When set to true only the default plain text formatter will be used.
61 61 plain_text_only = Bool(False, config=True)
62 62 def _plain_text_only_changed(self, name, old, new):
63 63 warnings.warn("""DisplayFormatter.plain_text_only is deprecated.
64 64
65 65 Use DisplayFormatter.active_types = ['text/plain']
66 66 for the same effect.
67 67 """, DeprecationWarning)
68 68 if new:
69 69 self.active_types = ['text/plain']
70 70 else:
71 71 self.active_types = self.format_types
72 72
73 active_types = List(Unicode, config=True,
73 active_types = List(Unicode(), config=True,
74 74 help="""List of currently active mime-types to display.
75 75 You can use this to set a white-list for formats to display.
76 76
77 77 Most users will not need to change this value.
78 78 """)
79 79 def _active_types_default(self):
80 80 return self.format_types
81 81
82 82 def _active_types_changed(self, name, old, new):
83 83 for key, formatter in self.formatters.items():
84 84 if key in new:
85 85 formatter.enabled = True
86 86 else:
87 87 formatter.enabled = False
88 88
89 89 ipython_display_formatter = ForwardDeclaredInstance('FormatterABC')
90 90 def _ipython_display_formatter_default(self):
91 91 return IPythonDisplayFormatter(parent=self)
92 92
93 93 # A dict of formatter whose keys are format types (MIME types) and whose
94 94 # values are subclasses of BaseFormatter.
95 95 formatters = Dict()
96 96 def _formatters_default(self):
97 97 """Activate the default formatters."""
98 98 formatter_classes = [
99 99 PlainTextFormatter,
100 100 HTMLFormatter,
101 101 MarkdownFormatter,
102 102 SVGFormatter,
103 103 PNGFormatter,
104 104 PDFFormatter,
105 105 JPEGFormatter,
106 106 LatexFormatter,
107 107 JSONFormatter,
108 108 JavascriptFormatter
109 109 ]
110 110 d = {}
111 111 for cls in formatter_classes:
112 112 f = cls(parent=self)
113 113 d[f.format_type] = f
114 114 return d
115 115
116 116 def format(self, obj, include=None, exclude=None):
117 117 """Return a format data dict for an object.
118 118
119 119 By default all format types will be computed.
120 120
121 121 The following MIME types are currently implemented:
122 122
123 123 * text/plain
124 124 * text/html
125 125 * text/markdown
126 126 * text/latex
127 127 * application/json
128 128 * application/javascript
129 129 * application/pdf
130 130 * image/png
131 131 * image/jpeg
132 132 * image/svg+xml
133 133
134 134 Parameters
135 135 ----------
136 136 obj : object
137 137 The Python object whose format data will be computed.
138 138 include : list or tuple, optional
139 139 A list of format type strings (MIME types) to include in the
140 140 format data dict. If this is set *only* the format types included
141 141 in this list will be computed.
142 142 exclude : list or tuple, optional
143 143 A list of format type string (MIME types) to exclude in the format
144 144 data dict. If this is set all format types will be computed,
145 145 except for those included in this argument.
146 146
147 147 Returns
148 148 -------
149 149 (format_dict, metadata_dict) : tuple of two dicts
150 150
151 151 format_dict is a dictionary of key/value pairs, one of each format that was
152 152 generated for the object. The keys are the format types, which
153 153 will usually be MIME type strings and the values and JSON'able
154 154 data structure containing the raw data for the representation in
155 155 that format.
156 156
157 157 metadata_dict is a dictionary of metadata about each mime-type output.
158 158 Its keys will be a strict subset of the keys in format_dict.
159 159 """
160 160 format_dict = {}
161 161 md_dict = {}
162 162
163 163 if self.ipython_display_formatter(obj):
164 164 # object handled itself, don't proceed
165 165 return {}, {}
166 166
167 167 for format_type, formatter in self.formatters.items():
168 168 if include and format_type not in include:
169 169 continue
170 170 if exclude and format_type in exclude:
171 171 continue
172 172
173 173 md = None
174 174 try:
175 175 data = formatter(obj)
176 176 except:
177 177 # FIXME: log the exception
178 178 raise
179 179
180 180 # formatters can return raw data or (data, metadata)
181 181 if isinstance(data, tuple) and len(data) == 2:
182 182 data, md = data
183 183
184 184 if data is not None:
185 185 format_dict[format_type] = data
186 186 if md is not None:
187 187 md_dict[format_type] = md
188 188
189 189 return format_dict, md_dict
190 190
191 191 @property
192 192 def format_types(self):
193 193 """Return the format types (MIME types) of the active formatters."""
194 194 return list(self.formatters.keys())
195 195
196 196
197 197 #-----------------------------------------------------------------------------
198 198 # Formatters for specific format types (text, html, svg, etc.)
199 199 #-----------------------------------------------------------------------------
200 200
201 201
202 202 def _safe_repr(obj):
203 203 """Try to return a repr of an object
204 204
205 205 always returns a string, at least.
206 206 """
207 207 try:
208 208 return repr(obj)
209 209 except Exception as e:
210 210 return "un-repr-able object (%r)" % e
211 211
212 212
213 213 class FormatterWarning(UserWarning):
214 214 """Warning class for errors in formatters"""
215 215
216 216 @decorator
217 217 def catch_format_error(method, self, *args, **kwargs):
218 218 """show traceback on failed format call"""
219 219 try:
220 220 r = method(self, *args, **kwargs)
221 221 except NotImplementedError:
222 222 # don't warn on NotImplementedErrors
223 223 return None
224 224 except Exception:
225 225 exc_info = sys.exc_info()
226 226 ip = get_ipython()
227 227 if ip is not None:
228 228 ip.showtraceback(exc_info)
229 229 else:
230 230 traceback.print_exception(*exc_info)
231 231 return None
232 232 return self._check_return(r, args[0])
233 233
234 234
235 235 class FormatterABC(with_metaclass(abc.ABCMeta, object)):
236 236 """ Abstract base class for Formatters.
237 237
238 238 A formatter is a callable class that is responsible for computing the
239 239 raw format data for a particular format type (MIME type). For example,
240 240 an HTML formatter would have a format type of `text/html` and would return
241 241 the HTML representation of the object when called.
242 242 """
243 243
244 244 # The format type of the data returned, usually a MIME type.
245 245 format_type = 'text/plain'
246 246
247 247 # Is the formatter enabled...
248 248 enabled = True
249 249
250 250 @abc.abstractmethod
251 251 def __call__(self, obj):
252 252 """Return a JSON'able representation of the object.
253 253
254 254 If the object cannot be formatted by this formatter,
255 255 warn and return None.
256 256 """
257 257 return repr(obj)
258 258
259 259
260 260 def _mod_name_key(typ):
261 261 """Return a (__module__, __name__) tuple for a type.
262 262
263 263 Used as key in Formatter.deferred_printers.
264 264 """
265 265 module = getattr(typ, '__module__', None)
266 266 name = getattr(typ, '__name__', None)
267 267 return (module, name)
268 268
269 269
270 270 def _get_type(obj):
271 271 """Return the type of an instance (old and new-style)"""
272 272 return getattr(obj, '__class__', None) or type(obj)
273 273
274 274
275 275 _raise_key_error = Sentinel('_raise_key_error', __name__,
276 276 """
277 277 Special value to raise a KeyError
278 278
279 279 Raise KeyError in `BaseFormatter.pop` if passed as the default value to `pop`
280 280 """)
281 281
282 282
283 283 class BaseFormatter(Configurable):
284 284 """A base formatter class that is configurable.
285 285
286 286 This formatter should usually be used as the base class of all formatters.
287 287 It is a traited :class:`Configurable` class and includes an extensible
288 288 API for users to determine how their objects are formatted. The following
289 289 logic is used to find a function to format an given object.
290 290
291 291 1. The object is introspected to see if it has a method with the name
292 292 :attr:`print_method`. If is does, that object is passed to that method
293 293 for formatting.
294 294 2. If no print method is found, three internal dictionaries are consulted
295 295 to find print method: :attr:`singleton_printers`, :attr:`type_printers`
296 296 and :attr:`deferred_printers`.
297 297
298 298 Users should use these dictionaries to register functions that will be
299 299 used to compute the format data for their objects (if those objects don't
300 300 have the special print methods). The easiest way of using these
301 301 dictionaries is through the :meth:`for_type` and :meth:`for_type_by_name`
302 302 methods.
303 303
304 304 If no function/callable is found to compute the format data, ``None`` is
305 305 returned and this format type is not used.
306 306 """
307 307
308 308 format_type = Unicode('text/plain')
309 309 _return_type = string_types
310 310
311 311 enabled = Bool(True, config=True)
312 312
313 313 print_method = ObjectName('__repr__')
314 314
315 315 # The singleton printers.
316 316 # Maps the IDs of the builtin singleton objects to the format functions.
317 317 singleton_printers = Dict(config=True)
318 318
319 319 # The type-specific printers.
320 320 # Map type objects to the format functions.
321 321 type_printers = Dict(config=True)
322 322
323 323 # The deferred-import type-specific printers.
324 324 # Map (modulename, classname) pairs to the format functions.
325 325 deferred_printers = Dict(config=True)
326 326
327 327 @catch_format_error
328 328 def __call__(self, obj):
329 329 """Compute the format for an object."""
330 330 if self.enabled:
331 331 # lookup registered printer
332 332 try:
333 333 printer = self.lookup(obj)
334 334 except KeyError:
335 335 pass
336 336 else:
337 337 return printer(obj)
338 338 # Finally look for special method names
339 339 method = _safe_get_formatter_method(obj, self.print_method)
340 340 if method is not None:
341 341 return method()
342 342 return None
343 343 else:
344 344 return None
345 345
346 346 def __contains__(self, typ):
347 347 """map in to lookup_by_type"""
348 348 try:
349 349 self.lookup_by_type(typ)
350 350 except KeyError:
351 351 return False
352 352 else:
353 353 return True
354 354
355 355 def _check_return(self, r, obj):
356 356 """Check that a return value is appropriate
357 357
358 358 Return the value if so, None otherwise, warning if invalid.
359 359 """
360 360 if r is None or isinstance(r, self._return_type) or \
361 361 (isinstance(r, tuple) and r and isinstance(r[0], self._return_type)):
362 362 return r
363 363 else:
364 364 warnings.warn(
365 365 "%s formatter returned invalid type %s (expected %s) for object: %s" % \
366 366 (self.format_type, type(r), self._return_type, _safe_repr(obj)),
367 367 FormatterWarning
368 368 )
369 369
370 370 def lookup(self, obj):
371 371 """Look up the formatter for a given instance.
372 372
373 373 Parameters
374 374 ----------
375 375 obj : object instance
376 376
377 377 Returns
378 378 -------
379 379 f : callable
380 380 The registered formatting callable for the type.
381 381
382 382 Raises
383 383 ------
384 384 KeyError if the type has not been registered.
385 385 """
386 386 # look for singleton first
387 387 obj_id = id(obj)
388 388 if obj_id in self.singleton_printers:
389 389 return self.singleton_printers[obj_id]
390 390 # then lookup by type
391 391 return self.lookup_by_type(_get_type(obj))
392 392
393 393 def lookup_by_type(self, typ):
394 394 """Look up the registered formatter for a type.
395 395
396 396 Parameters
397 397 ----------
398 398 typ : type or '__module__.__name__' string for a type
399 399
400 400 Returns
401 401 -------
402 402 f : callable
403 403 The registered formatting callable for the type.
404 404
405 405 Raises
406 406 ------
407 407 KeyError if the type has not been registered.
408 408 """
409 409 if isinstance(typ, string_types):
410 410 typ_key = tuple(typ.rsplit('.',1))
411 411 if typ_key not in self.deferred_printers:
412 412 # We may have it cached in the type map. We will have to
413 413 # iterate over all of the types to check.
414 414 for cls in self.type_printers:
415 415 if _mod_name_key(cls) == typ_key:
416 416 return self.type_printers[cls]
417 417 else:
418 418 return self.deferred_printers[typ_key]
419 419 else:
420 420 for cls in pretty._get_mro(typ):
421 421 if cls in self.type_printers or self._in_deferred_types(cls):
422 422 return self.type_printers[cls]
423 423
424 424 # If we have reached here, the lookup failed.
425 425 raise KeyError("No registered printer for {0!r}".format(typ))
426 426
427 427 def for_type(self, typ, func=None):
428 428 """Add a format function for a given type.
429 429
430 430 Parameters
431 431 -----------
432 432 typ : type or '__module__.__name__' string for a type
433 433 The class of the object that will be formatted using `func`.
434 434 func : callable
435 435 A callable for computing the format data.
436 436 `func` will be called with the object to be formatted,
437 437 and will return the raw data in this formatter's format.
438 438 Subclasses may use a different call signature for the
439 439 `func` argument.
440 440
441 441 If `func` is None or not specified, there will be no change,
442 442 only returning the current value.
443 443
444 444 Returns
445 445 -------
446 446 oldfunc : callable
447 447 The currently registered callable.
448 448 If you are registering a new formatter,
449 449 this will be the previous value (to enable restoring later).
450 450 """
451 451 # if string given, interpret as 'pkg.module.class_name'
452 452 if isinstance(typ, string_types):
453 453 type_module, type_name = typ.rsplit('.', 1)
454 454 return self.for_type_by_name(type_module, type_name, func)
455 455
456 456 try:
457 457 oldfunc = self.lookup_by_type(typ)
458 458 except KeyError:
459 459 oldfunc = None
460 460
461 461 if func is not None:
462 462 self.type_printers[typ] = func
463 463
464 464 return oldfunc
465 465
466 466 def for_type_by_name(self, type_module, type_name, func=None):
467 467 """Add a format function for a type specified by the full dotted
468 468 module and name of the type, rather than the type of the object.
469 469
470 470 Parameters
471 471 ----------
472 472 type_module : str
473 473 The full dotted name of the module the type is defined in, like
474 474 ``numpy``.
475 475 type_name : str
476 476 The name of the type (the class name), like ``dtype``
477 477 func : callable
478 478 A callable for computing the format data.
479 479 `func` will be called with the object to be formatted,
480 480 and will return the raw data in this formatter's format.
481 481 Subclasses may use a different call signature for the
482 482 `func` argument.
483 483
484 484 If `func` is None or unspecified, there will be no change,
485 485 only returning the current value.
486 486
487 487 Returns
488 488 -------
489 489 oldfunc : callable
490 490 The currently registered callable.
491 491 If you are registering a new formatter,
492 492 this will be the previous value (to enable restoring later).
493 493 """
494 494 key = (type_module, type_name)
495 495
496 496 try:
497 497 oldfunc = self.lookup_by_type("%s.%s" % key)
498 498 except KeyError:
499 499 oldfunc = None
500 500
501 501 if func is not None:
502 502 self.deferred_printers[key] = func
503 503 return oldfunc
504 504
505 505 def pop(self, typ, default=_raise_key_error):
506 506 """Pop a formatter for the given type.
507 507
508 508 Parameters
509 509 ----------
510 510 typ : type or '__module__.__name__' string for a type
511 511 default : object
512 512 value to be returned if no formatter is registered for typ.
513 513
514 514 Returns
515 515 -------
516 516 obj : object
517 517 The last registered object for the type.
518 518
519 519 Raises
520 520 ------
521 521 KeyError if the type is not registered and default is not specified.
522 522 """
523 523
524 524 if isinstance(typ, string_types):
525 525 typ_key = tuple(typ.rsplit('.',1))
526 526 if typ_key not in self.deferred_printers:
527 527 # We may have it cached in the type map. We will have to
528 528 # iterate over all of the types to check.
529 529 for cls in self.type_printers:
530 530 if _mod_name_key(cls) == typ_key:
531 531 old = self.type_printers.pop(cls)
532 532 break
533 533 else:
534 534 old = default
535 535 else:
536 536 old = self.deferred_printers.pop(typ_key)
537 537 else:
538 538 if typ in self.type_printers:
539 539 old = self.type_printers.pop(typ)
540 540 else:
541 541 old = self.deferred_printers.pop(_mod_name_key(typ), default)
542 542 if old is _raise_key_error:
543 543 raise KeyError("No registered value for {0!r}".format(typ))
544 544 return old
545 545
546 546 def _in_deferred_types(self, cls):
547 547 """
548 548 Check if the given class is specified in the deferred type registry.
549 549
550 550 Successful matches will be moved to the regular type registry for future use.
551 551 """
552 552 mod = getattr(cls, '__module__', None)
553 553 name = getattr(cls, '__name__', None)
554 554 key = (mod, name)
555 555 if key in self.deferred_printers:
556 556 # Move the printer over to the regular registry.
557 557 printer = self.deferred_printers.pop(key)
558 558 self.type_printers[cls] = printer
559 559 return True
560 560 return False
561 561
562 562
563 563 class PlainTextFormatter(BaseFormatter):
564 564 """The default pretty-printer.
565 565
566 566 This uses :mod:`IPython.lib.pretty` to compute the format data of
567 567 the object. If the object cannot be pretty printed, :func:`repr` is used.
568 568 See the documentation of :mod:`IPython.lib.pretty` for details on
569 569 how to write pretty printers. Here is a simple example::
570 570
571 571 def dtype_pprinter(obj, p, cycle):
572 572 if cycle:
573 573 return p.text('dtype(...)')
574 574 if hasattr(obj, 'fields'):
575 575 if obj.fields is None:
576 576 p.text(repr(obj))
577 577 else:
578 578 p.begin_group(7, 'dtype([')
579 579 for i, field in enumerate(obj.descr):
580 580 if i > 0:
581 581 p.text(',')
582 582 p.breakable()
583 583 p.pretty(field)
584 584 p.end_group(7, '])')
585 585 """
586 586
587 587 # The format type of data returned.
588 588 format_type = Unicode('text/plain')
589 589
590 590 # This subclass ignores this attribute as it always need to return
591 591 # something.
592 592 enabled = Bool(True, config=False)
593 593
594 594 max_seq_length = Integer(pretty.MAX_SEQ_LENGTH, config=True,
595 595 help="""Truncate large collections (lists, dicts, tuples, sets) to this size.
596 596
597 597 Set to 0 to disable truncation.
598 598 """
599 599 )
600 600
601 601 # Look for a _repr_pretty_ methods to use for pretty printing.
602 602 print_method = ObjectName('_repr_pretty_')
603 603
604 604 # Whether to pretty-print or not.
605 605 pprint = Bool(True, config=True)
606 606
607 607 # Whether to be verbose or not.
608 608 verbose = Bool(False, config=True)
609 609
610 610 # The maximum width.
611 611 max_width = Integer(79, config=True)
612 612
613 613 # The newline character.
614 614 newline = Unicode('\n', config=True)
615 615
616 616 # format-string for pprinting floats
617 617 float_format = Unicode('%r')
618 618 # setter for float precision, either int or direct format-string
619 619 float_precision = CUnicode('', config=True)
620 620
621 621 def _float_precision_changed(self, name, old, new):
622 622 """float_precision changed, set float_format accordingly.
623 623
624 624 float_precision can be set by int or str.
625 625 This will set float_format, after interpreting input.
626 626 If numpy has been imported, numpy print precision will also be set.
627 627
628 628 integer `n` sets format to '%.nf', otherwise, format set directly.
629 629
630 630 An empty string returns to defaults (repr for float, 8 for numpy).
631 631
632 632 This parameter can be set via the '%precision' magic.
633 633 """
634 634
635 635 if '%' in new:
636 636 # got explicit format string
637 637 fmt = new
638 638 try:
639 639 fmt%3.14159
640 640 except Exception:
641 641 raise ValueError("Precision must be int or format string, not %r"%new)
642 642 elif new:
643 643 # otherwise, should be an int
644 644 try:
645 645 i = int(new)
646 646 assert i >= 0
647 647 except ValueError:
648 648 raise ValueError("Precision must be int or format string, not %r"%new)
649 649 except AssertionError:
650 650 raise ValueError("int precision must be non-negative, not %r"%i)
651 651
652 652 fmt = '%%.%if'%i
653 653 if 'numpy' in sys.modules:
654 654 # set numpy precision if it has been imported
655 655 import numpy
656 656 numpy.set_printoptions(precision=i)
657 657 else:
658 658 # default back to repr
659 659 fmt = '%r'
660 660 if 'numpy' in sys.modules:
661 661 import numpy
662 662 # numpy default is 8
663 663 numpy.set_printoptions(precision=8)
664 664 self.float_format = fmt
665 665
666 666 # Use the default pretty printers from IPython.lib.pretty.
667 667 def _singleton_printers_default(self):
668 668 return pretty._singleton_pprinters.copy()
669 669
670 670 def _type_printers_default(self):
671 671 d = pretty._type_pprinters.copy()
672 672 d[float] = lambda obj,p,cycle: p.text(self.float_format%obj)
673 673 return d
674 674
675 675 def _deferred_printers_default(self):
676 676 return pretty._deferred_type_pprinters.copy()
677 677
678 678 #### FormatterABC interface ####
679 679
680 680 @catch_format_error
681 681 def __call__(self, obj):
682 682 """Compute the pretty representation of the object."""
683 683 if not self.pprint:
684 684 return repr(obj)
685 685 else:
686 686 # handle str and unicode on Python 2
687 687 # io.StringIO only accepts unicode,
688 688 # cStringIO doesn't handle unicode on py2,
689 689 # StringIO allows str, unicode but only ascii str
690 690 stream = pretty.CUnicodeIO()
691 691 printer = pretty.RepresentationPrinter(stream, self.verbose,
692 692 self.max_width, self.newline,
693 693 max_seq_length=self.max_seq_length,
694 694 singleton_pprinters=self.singleton_printers,
695 695 type_pprinters=self.type_printers,
696 696 deferred_pprinters=self.deferred_printers)
697 697 printer.pretty(obj)
698 698 printer.flush()
699 699 return stream.getvalue()
700 700
701 701
702 702 class HTMLFormatter(BaseFormatter):
703 703 """An HTML formatter.
704 704
705 705 To define the callables that compute the HTML representation of your
706 706 objects, define a :meth:`_repr_html_` method or use the :meth:`for_type`
707 707 or :meth:`for_type_by_name` methods to register functions that handle
708 708 this.
709 709
710 710 The return value of this formatter should be a valid HTML snippet that
711 711 could be injected into an existing DOM. It should *not* include the
712 712 ```<html>`` or ```<body>`` tags.
713 713 """
714 714 format_type = Unicode('text/html')
715 715
716 716 print_method = ObjectName('_repr_html_')
717 717
718 718
719 719 class MarkdownFormatter(BaseFormatter):
720 720 """A Markdown formatter.
721 721
722 722 To define the callables that compute the Markdown representation of your
723 723 objects, define a :meth:`_repr_markdown_` method or use the :meth:`for_type`
724 724 or :meth:`for_type_by_name` methods to register functions that handle
725 725 this.
726 726
727 727 The return value of this formatter should be a valid Markdown.
728 728 """
729 729 format_type = Unicode('text/markdown')
730 730
731 731 print_method = ObjectName('_repr_markdown_')
732 732
733 733 class SVGFormatter(BaseFormatter):
734 734 """An SVG formatter.
735 735
736 736 To define the callables that compute the SVG representation of your
737 737 objects, define a :meth:`_repr_svg_` method or use the :meth:`for_type`
738 738 or :meth:`for_type_by_name` methods to register functions that handle
739 739 this.
740 740
741 741 The return value of this formatter should be valid SVG enclosed in
742 742 ```<svg>``` tags, that could be injected into an existing DOM. It should
743 743 *not* include the ```<html>`` or ```<body>`` tags.
744 744 """
745 745 format_type = Unicode('image/svg+xml')
746 746
747 747 print_method = ObjectName('_repr_svg_')
748 748
749 749
750 750 class PNGFormatter(BaseFormatter):
751 751 """A PNG formatter.
752 752
753 753 To define the callables that compute the PNG representation of your
754 754 objects, define a :meth:`_repr_png_` method or use the :meth:`for_type`
755 755 or :meth:`for_type_by_name` methods to register functions that handle
756 756 this.
757 757
758 758 The return value of this formatter should be raw PNG data, *not*
759 759 base64 encoded.
760 760 """
761 761 format_type = Unicode('image/png')
762 762
763 763 print_method = ObjectName('_repr_png_')
764 764
765 765 _return_type = (bytes, unicode_type)
766 766
767 767
768 768 class JPEGFormatter(BaseFormatter):
769 769 """A JPEG formatter.
770 770
771 771 To define the callables that compute the JPEG representation of your
772 772 objects, define a :meth:`_repr_jpeg_` method or use the :meth:`for_type`
773 773 or :meth:`for_type_by_name` methods to register functions that handle
774 774 this.
775 775
776 776 The return value of this formatter should be raw JPEG data, *not*
777 777 base64 encoded.
778 778 """
779 779 format_type = Unicode('image/jpeg')
780 780
781 781 print_method = ObjectName('_repr_jpeg_')
782 782
783 783 _return_type = (bytes, unicode_type)
784 784
785 785
786 786 class LatexFormatter(BaseFormatter):
787 787 """A LaTeX formatter.
788 788
789 789 To define the callables that compute the LaTeX representation of your
790 790 objects, define a :meth:`_repr_latex_` method or use the :meth:`for_type`
791 791 or :meth:`for_type_by_name` methods to register functions that handle
792 792 this.
793 793
794 794 The return value of this formatter should be a valid LaTeX equation,
795 795 enclosed in either ```$```, ```$$``` or another LaTeX equation
796 796 environment.
797 797 """
798 798 format_type = Unicode('text/latex')
799 799
800 800 print_method = ObjectName('_repr_latex_')
801 801
802 802
803 803 class JSONFormatter(BaseFormatter):
804 804 """A JSON string formatter.
805 805
806 806 To define the callables that compute the JSONable representation of
807 807 your objects, define a :meth:`_repr_json_` method or use the :meth:`for_type`
808 808 or :meth:`for_type_by_name` methods to register functions that handle
809 809 this.
810 810
811 811 The return value of this formatter should be a JSONable list or dict.
812 812 JSON scalars (None, number, string) are not allowed, only dict or list containers.
813 813 """
814 814 format_type = Unicode('application/json')
815 815 _return_type = (list, dict)
816 816
817 817 print_method = ObjectName('_repr_json_')
818 818
819 819 def _check_return(self, r, obj):
820 820 """Check that a return value is appropriate
821 821
822 822 Return the value if so, None otherwise, warning if invalid.
823 823 """
824 824 if r is None:
825 825 return
826 826 md = None
827 827 if isinstance(r, tuple):
828 828 # unpack data, metadata tuple for type checking on first element
829 829 r, md = r
830 830
831 831 # handle deprecated JSON-as-string form from IPython < 3
832 832 if isinstance(r, string_types):
833 833 warnings.warn("JSON expects JSONable list/dict containers, not JSON strings",
834 834 FormatterWarning)
835 835 r = json.loads(r)
836 836
837 837 if md is not None:
838 838 # put the tuple back together
839 839 r = (r, md)
840 840 return super(JSONFormatter, self)._check_return(r, obj)
841 841
842 842
843 843 class JavascriptFormatter(BaseFormatter):
844 844 """A Javascript formatter.
845 845
846 846 To define the callables that compute the Javascript representation of
847 847 your objects, define a :meth:`_repr_javascript_` method or use the
848 848 :meth:`for_type` or :meth:`for_type_by_name` methods to register functions
849 849 that handle this.
850 850
851 851 The return value of this formatter should be valid Javascript code and
852 852 should *not* be enclosed in ```<script>``` tags.
853 853 """
854 854 format_type = Unicode('application/javascript')
855 855
856 856 print_method = ObjectName('_repr_javascript_')
857 857
858 858
859 859 class PDFFormatter(BaseFormatter):
860 860 """A PDF formatter.
861 861
862 862 To define the callables that compute the PDF representation of your
863 863 objects, define a :meth:`_repr_pdf_` method or use the :meth:`for_type`
864 864 or :meth:`for_type_by_name` methods to register functions that handle
865 865 this.
866 866
867 867 The return value of this formatter should be raw PDF data, *not*
868 868 base64 encoded.
869 869 """
870 870 format_type = Unicode('application/pdf')
871 871
872 872 print_method = ObjectName('_repr_pdf_')
873 873
874 874 _return_type = (bytes, unicode_type)
875 875
876 876 class IPythonDisplayFormatter(BaseFormatter):
877 877 """A Formatter for objects that know how to display themselves.
878 878
879 879 To define the callables that compute the representation of your
880 880 objects, define a :meth:`_ipython_display_` method or use the :meth:`for_type`
881 881 or :meth:`for_type_by_name` methods to register functions that handle
882 882 this. Unlike mime-type displays, this method should not return anything,
883 883 instead calling any appropriate display methods itself.
884 884
885 885 This display formatter has highest priority.
886 886 If it fires, no other display formatter will be called.
887 887 """
888 888 print_method = ObjectName('_ipython_display_')
889 889 _return_type = (type(None), bool)
890 890
891 891
892 892 @catch_format_error
893 893 def __call__(self, obj):
894 894 """Compute the format for an object."""
895 895 if self.enabled:
896 896 # lookup registered printer
897 897 try:
898 898 printer = self.lookup(obj)
899 899 except KeyError:
900 900 pass
901 901 else:
902 902 printer(obj)
903 903 return True
904 904 # Finally look for special method names
905 905 method = _safe_get_formatter_method(obj, self.print_method)
906 906 if method is not None:
907 907 method()
908 908 return True
909 909
910 910
911 911 FormatterABC.register(BaseFormatter)
912 912 FormatterABC.register(PlainTextFormatter)
913 913 FormatterABC.register(HTMLFormatter)
914 914 FormatterABC.register(MarkdownFormatter)
915 915 FormatterABC.register(SVGFormatter)
916 916 FormatterABC.register(PNGFormatter)
917 917 FormatterABC.register(PDFFormatter)
918 918 FormatterABC.register(JPEGFormatter)
919 919 FormatterABC.register(LatexFormatter)
920 920 FormatterABC.register(JSONFormatter)
921 921 FormatterABC.register(JavascriptFormatter)
922 922 FormatterABC.register(IPythonDisplayFormatter)
923 923
924 924
925 925 def format_display_data(obj, include=None, exclude=None):
926 926 """Return a format data dict for an object.
927 927
928 928 By default all format types will be computed.
929 929
930 930 The following MIME types are currently implemented:
931 931
932 932 * text/plain
933 933 * text/html
934 934 * text/markdown
935 935 * text/latex
936 936 * application/json
937 937 * application/javascript
938 938 * application/pdf
939 939 * image/png
940 940 * image/jpeg
941 941 * image/svg+xml
942 942
943 943 Parameters
944 944 ----------
945 945 obj : object
946 946 The Python object whose format data will be computed.
947 947
948 948 Returns
949 949 -------
950 950 format_dict : dict
951 951 A dictionary of key/value pairs, one or each format that was
952 952 generated for the object. The keys are the format types, which
953 953 will usually be MIME type strings and the values and JSON'able
954 954 data structure containing the raw data for the representation in
955 955 that format.
956 956 include : list or tuple, optional
957 957 A list of format type strings (MIME types) to include in the
958 958 format data dict. If this is set *only* the format types included
959 959 in this list will be computed.
960 960 exclude : list or tuple, optional
961 961 A list of format type string (MIME types) to exclue in the format
962 962 data dict. If this is set all format types will be computed,
963 963 except for those included in this argument.
964 964 """
965 965 from IPython.core.interactiveshell import InteractiveShell
966 966
967 967 InteractiveShell.instance().display_formatter.format(
968 968 obj,
969 969 include,
970 970 exclude
971 971 )
972 972
@@ -1,702 +1,702
1 1 # encoding: utf-8
2 2 """Magic functions for InteractiveShell.
3 3 """
4 4 from __future__ import print_function
5 5
6 6 #-----------------------------------------------------------------------------
7 7 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
8 8 # Copyright (C) 2001 Fernando Perez <fperez@colorado.edu>
9 9 # Copyright (C) 2008 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 # Stdlib
19 19 import os
20 20 import re
21 21 import sys
22 22 import types
23 23 from getopt import getopt, GetoptError
24 24
25 25 # Our own
26 26 from traitlets.config.configurable import Configurable
27 27 from IPython.core import oinspect
28 28 from IPython.core.error import UsageError
29 29 from IPython.core.inputsplitter import ESC_MAGIC, ESC_MAGIC2
30 30 from decorator import decorator
31 31 from IPython.utils.ipstruct import Struct
32 32 from IPython.utils.process import arg_split
33 33 from IPython.utils.py3compat import string_types, iteritems
34 34 from IPython.utils.text import dedent
35 35 from traitlets import Bool, Dict, Instance, MetaHasTraits
36 36 from IPython.utils.warn import error
37 37
38 38 #-----------------------------------------------------------------------------
39 39 # Globals
40 40 #-----------------------------------------------------------------------------
41 41
42 42 # A dict we'll use for each class that has magics, used as temporary storage to
43 43 # pass information between the @line/cell_magic method decorators and the
44 44 # @magics_class class decorator, because the method decorators have no
45 45 # access to the class when they run. See for more details:
46 46 # http://stackoverflow.com/questions/2366713/can-a-python-decorator-of-an-instance-method-access-the-class
47 47
48 48 magics = dict(line={}, cell={})
49 49
50 50 magic_kinds = ('line', 'cell')
51 51 magic_spec = ('line', 'cell', 'line_cell')
52 52 magic_escapes = dict(line=ESC_MAGIC, cell=ESC_MAGIC2)
53 53
54 54 #-----------------------------------------------------------------------------
55 55 # Utility classes and functions
56 56 #-----------------------------------------------------------------------------
57 57
58 58 class Bunch: pass
59 59
60 60
61 61 def on_off(tag):
62 62 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
63 63 return ['OFF','ON'][tag]
64 64
65 65
66 66 def compress_dhist(dh):
67 67 """Compress a directory history into a new one with at most 20 entries.
68 68
69 69 Return a new list made from the first and last 10 elements of dhist after
70 70 removal of duplicates.
71 71 """
72 72 head, tail = dh[:-10], dh[-10:]
73 73
74 74 newhead = []
75 75 done = set()
76 76 for h in head:
77 77 if h in done:
78 78 continue
79 79 newhead.append(h)
80 80 done.add(h)
81 81
82 82 return newhead + tail
83 83
84 84
85 85 def needs_local_scope(func):
86 86 """Decorator to mark magic functions which need to local scope to run."""
87 87 func.needs_local_scope = True
88 88 return func
89 89
90 90 #-----------------------------------------------------------------------------
91 91 # Class and method decorators for registering magics
92 92 #-----------------------------------------------------------------------------
93 93
94 94 def magics_class(cls):
95 95 """Class decorator for all subclasses of the main Magics class.
96 96
97 97 Any class that subclasses Magics *must* also apply this decorator, to
98 98 ensure that all the methods that have been decorated as line/cell magics
99 99 get correctly registered in the class instance. This is necessary because
100 100 when method decorators run, the class does not exist yet, so they
101 101 temporarily store their information into a module global. Application of
102 102 this class decorator copies that global data to the class instance and
103 103 clears the global.
104 104
105 105 Obviously, this mechanism is not thread-safe, which means that the
106 106 *creation* of subclasses of Magic should only be done in a single-thread
107 107 context. Instantiation of the classes has no restrictions. Given that
108 108 these classes are typically created at IPython startup time and before user
109 109 application code becomes active, in practice this should not pose any
110 110 problems.
111 111 """
112 112 cls.registered = True
113 113 cls.magics = dict(line = magics['line'],
114 114 cell = magics['cell'])
115 115 magics['line'] = {}
116 116 magics['cell'] = {}
117 117 return cls
118 118
119 119
120 120 def record_magic(dct, magic_kind, magic_name, func):
121 121 """Utility function to store a function as a magic of a specific kind.
122 122
123 123 Parameters
124 124 ----------
125 125 dct : dict
126 126 A dictionary with 'line' and 'cell' subdicts.
127 127
128 128 magic_kind : str
129 129 Kind of magic to be stored.
130 130
131 131 magic_name : str
132 132 Key to store the magic as.
133 133
134 134 func : function
135 135 Callable object to store.
136 136 """
137 137 if magic_kind == 'line_cell':
138 138 dct['line'][magic_name] = dct['cell'][magic_name] = func
139 139 else:
140 140 dct[magic_kind][magic_name] = func
141 141
142 142
143 143 def validate_type(magic_kind):
144 144 """Ensure that the given magic_kind is valid.
145 145
146 146 Check that the given magic_kind is one of the accepted spec types (stored
147 147 in the global `magic_spec`), raise ValueError otherwise.
148 148 """
149 149 if magic_kind not in magic_spec:
150 150 raise ValueError('magic_kind must be one of %s, %s given' %
151 151 magic_kinds, magic_kind)
152 152
153 153
154 154 # The docstrings for the decorator below will be fairly similar for the two
155 155 # types (method and function), so we generate them here once and reuse the
156 156 # templates below.
157 157 _docstring_template = \
158 158 """Decorate the given {0} as {1} magic.
159 159
160 160 The decorator can be used with or without arguments, as follows.
161 161
162 162 i) without arguments: it will create a {1} magic named as the {0} being
163 163 decorated::
164 164
165 165 @deco
166 166 def foo(...)
167 167
168 168 will create a {1} magic named `foo`.
169 169
170 170 ii) with one string argument: which will be used as the actual name of the
171 171 resulting magic::
172 172
173 173 @deco('bar')
174 174 def foo(...)
175 175
176 176 will create a {1} magic named `bar`.
177 177 """
178 178
179 179 # These two are decorator factories. While they are conceptually very similar,
180 180 # there are enough differences in the details that it's simpler to have them
181 181 # written as completely standalone functions rather than trying to share code
182 182 # and make a single one with convoluted logic.
183 183
184 184 def _method_magic_marker(magic_kind):
185 185 """Decorator factory for methods in Magics subclasses.
186 186 """
187 187
188 188 validate_type(magic_kind)
189 189
190 190 # This is a closure to capture the magic_kind. We could also use a class,
191 191 # but it's overkill for just that one bit of state.
192 192 def magic_deco(arg):
193 193 call = lambda f, *a, **k: f(*a, **k)
194 194
195 195 if callable(arg):
196 196 # "Naked" decorator call (just @foo, no args)
197 197 func = arg
198 198 name = func.__name__
199 199 retval = decorator(call, func)
200 200 record_magic(magics, magic_kind, name, name)
201 201 elif isinstance(arg, string_types):
202 202 # Decorator called with arguments (@foo('bar'))
203 203 name = arg
204 204 def mark(func, *a, **kw):
205 205 record_magic(magics, magic_kind, name, func.__name__)
206 206 return decorator(call, func)
207 207 retval = mark
208 208 else:
209 209 raise TypeError("Decorator can only be called with "
210 210 "string or function")
211 211 return retval
212 212
213 213 # Ensure the resulting decorator has a usable docstring
214 214 magic_deco.__doc__ = _docstring_template.format('method', magic_kind)
215 215 return magic_deco
216 216
217 217
218 218 def _function_magic_marker(magic_kind):
219 219 """Decorator factory for standalone functions.
220 220 """
221 221 validate_type(magic_kind)
222 222
223 223 # This is a closure to capture the magic_kind. We could also use a class,
224 224 # but it's overkill for just that one bit of state.
225 225 def magic_deco(arg):
226 226 call = lambda f, *a, **k: f(*a, **k)
227 227
228 228 # Find get_ipython() in the caller's namespace
229 229 caller = sys._getframe(1)
230 230 for ns in ['f_locals', 'f_globals', 'f_builtins']:
231 231 get_ipython = getattr(caller, ns).get('get_ipython')
232 232 if get_ipython is not None:
233 233 break
234 234 else:
235 235 raise NameError('Decorator can only run in context where '
236 236 '`get_ipython` exists')
237 237
238 238 ip = get_ipython()
239 239
240 240 if callable(arg):
241 241 # "Naked" decorator call (just @foo, no args)
242 242 func = arg
243 243 name = func.__name__
244 244 ip.register_magic_function(func, magic_kind, name)
245 245 retval = decorator(call, func)
246 246 elif isinstance(arg, string_types):
247 247 # Decorator called with arguments (@foo('bar'))
248 248 name = arg
249 249 def mark(func, *a, **kw):
250 250 ip.register_magic_function(func, magic_kind, name)
251 251 return decorator(call, func)
252 252 retval = mark
253 253 else:
254 254 raise TypeError("Decorator can only be called with "
255 255 "string or function")
256 256 return retval
257 257
258 258 # Ensure the resulting decorator has a usable docstring
259 259 ds = _docstring_template.format('function', magic_kind)
260 260
261 261 ds += dedent("""
262 262 Note: this decorator can only be used in a context where IPython is already
263 263 active, so that the `get_ipython()` call succeeds. You can therefore use
264 264 it in your startup files loaded after IPython initializes, but *not* in the
265 265 IPython configuration file itself, which is executed before IPython is
266 266 fully up and running. Any file located in the `startup` subdirectory of
267 267 your configuration profile will be OK in this sense.
268 268 """)
269 269
270 270 magic_deco.__doc__ = ds
271 271 return magic_deco
272 272
273 273
274 274 # Create the actual decorators for public use
275 275
276 276 # These three are used to decorate methods in class definitions
277 277 line_magic = _method_magic_marker('line')
278 278 cell_magic = _method_magic_marker('cell')
279 279 line_cell_magic = _method_magic_marker('line_cell')
280 280
281 281 # These three decorate standalone functions and perform the decoration
282 282 # immediately. They can only run where get_ipython() works
283 283 register_line_magic = _function_magic_marker('line')
284 284 register_cell_magic = _function_magic_marker('cell')
285 285 register_line_cell_magic = _function_magic_marker('line_cell')
286 286
287 287 #-----------------------------------------------------------------------------
288 288 # Core Magic classes
289 289 #-----------------------------------------------------------------------------
290 290
291 291 class MagicsManager(Configurable):
292 292 """Object that handles all magic-related functionality for IPython.
293 293 """
294 294 # Non-configurable class attributes
295 295
296 296 # A two-level dict, first keyed by magic type, then by magic function, and
297 297 # holding the actual callable object as value. This is the dict used for
298 298 # magic function dispatch
299 magics = Dict
299 magics = Dict()
300 300
301 301 # A registry of the original objects that we've been given holding magics.
302 registry = Dict
302 registry = Dict()
303 303
304 304 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', allow_none=True)
305 305
306 306 auto_magic = Bool(True, config=True, help=
307 307 "Automatically call line magics without requiring explicit % prefix")
308 308
309 309 def _auto_magic_changed(self, name, value):
310 310 self.shell.automagic = value
311 311
312 312 _auto_status = [
313 313 'Automagic is OFF, % prefix IS needed for line magics.',
314 314 'Automagic is ON, % prefix IS NOT needed for line magics.']
315 315
316 316 user_magics = Instance('IPython.core.magics.UserMagics', allow_none=True)
317 317
318 318 def __init__(self, shell=None, config=None, user_magics=None, **traits):
319 319
320 320 super(MagicsManager, self).__init__(shell=shell, config=config,
321 321 user_magics=user_magics, **traits)
322 322 self.magics = dict(line={}, cell={})
323 323 # Let's add the user_magics to the registry for uniformity, so *all*
324 324 # registered magic containers can be found there.
325 325 self.registry[user_magics.__class__.__name__] = user_magics
326 326
327 327 def auto_status(self):
328 328 """Return descriptive string with automagic status."""
329 329 return self._auto_status[self.auto_magic]
330 330
331 331 def lsmagic(self):
332 332 """Return a dict of currently available magic functions.
333 333
334 334 The return dict has the keys 'line' and 'cell', corresponding to the
335 335 two types of magics we support. Each value is a list of names.
336 336 """
337 337 return self.magics
338 338
339 339 def lsmagic_docs(self, brief=False, missing=''):
340 340 """Return dict of documentation of magic functions.
341 341
342 342 The return dict has the keys 'line' and 'cell', corresponding to the
343 343 two types of magics we support. Each value is a dict keyed by magic
344 344 name whose value is the function docstring. If a docstring is
345 345 unavailable, the value of `missing` is used instead.
346 346
347 347 If brief is True, only the first line of each docstring will be returned.
348 348 """
349 349 docs = {}
350 350 for m_type in self.magics:
351 351 m_docs = {}
352 352 for m_name, m_func in iteritems(self.magics[m_type]):
353 353 if m_func.__doc__:
354 354 if brief:
355 355 m_docs[m_name] = m_func.__doc__.split('\n', 1)[0]
356 356 else:
357 357 m_docs[m_name] = m_func.__doc__.rstrip()
358 358 else:
359 359 m_docs[m_name] = missing
360 360 docs[m_type] = m_docs
361 361 return docs
362 362
363 363 def register(self, *magic_objects):
364 364 """Register one or more instances of Magics.
365 365
366 366 Take one or more classes or instances of classes that subclass the main
367 367 `core.Magic` class, and register them with IPython to use the magic
368 368 functions they provide. The registration process will then ensure that
369 369 any methods that have decorated to provide line and/or cell magics will
370 370 be recognized with the `%x`/`%%x` syntax as a line/cell magic
371 371 respectively.
372 372
373 373 If classes are given, they will be instantiated with the default
374 374 constructor. If your classes need a custom constructor, you should
375 375 instanitate them first and pass the instance.
376 376
377 377 The provided arguments can be an arbitrary mix of classes and instances.
378 378
379 379 Parameters
380 380 ----------
381 381 magic_objects : one or more classes or instances
382 382 """
383 383 # Start by validating them to ensure they have all had their magic
384 384 # methods registered at the instance level
385 385 for m in magic_objects:
386 386 if not m.registered:
387 387 raise ValueError("Class of magics %r was constructed without "
388 388 "the @register_magics class decorator")
389 389 if type(m) in (type, MetaHasTraits):
390 390 # If we're given an uninstantiated class
391 391 m = m(shell=self.shell)
392 392
393 393 # Now that we have an instance, we can register it and update the
394 394 # table of callables
395 395 self.registry[m.__class__.__name__] = m
396 396 for mtype in magic_kinds:
397 397 self.magics[mtype].update(m.magics[mtype])
398 398
399 399 def register_function(self, func, magic_kind='line', magic_name=None):
400 400 """Expose a standalone function as magic function for IPython.
401 401
402 402 This will create an IPython magic (line, cell or both) from a
403 403 standalone function. The functions should have the following
404 404 signatures:
405 405
406 406 * For line magics: `def f(line)`
407 407 * For cell magics: `def f(line, cell)`
408 408 * For a function that does both: `def f(line, cell=None)`
409 409
410 410 In the latter case, the function will be called with `cell==None` when
411 411 invoked as `%f`, and with cell as a string when invoked as `%%f`.
412 412
413 413 Parameters
414 414 ----------
415 415 func : callable
416 416 Function to be registered as a magic.
417 417
418 418 magic_kind : str
419 419 Kind of magic, one of 'line', 'cell' or 'line_cell'
420 420
421 421 magic_name : optional str
422 422 If given, the name the magic will have in the IPython namespace. By
423 423 default, the name of the function itself is used.
424 424 """
425 425
426 426 # Create the new method in the user_magics and register it in the
427 427 # global table
428 428 validate_type(magic_kind)
429 429 magic_name = func.__name__ if magic_name is None else magic_name
430 430 setattr(self.user_magics, magic_name, func)
431 431 record_magic(self.magics, magic_kind, magic_name, func)
432 432
433 433 def define_magic(self, name, func):
434 434 """[Deprecated] Expose own function as magic function for IPython.
435 435
436 436 Example::
437 437
438 438 def foo_impl(self, parameter_s=''):
439 439 'My very own magic!. (Use docstrings, IPython reads them).'
440 440 print 'Magic function. Passed parameter is between < >:'
441 441 print '<%s>' % parameter_s
442 442 print 'The self object is:', self
443 443
444 444 ip.define_magic('foo',foo_impl)
445 445 """
446 446 meth = types.MethodType(func, self.user_magics)
447 447 setattr(self.user_magics, name, meth)
448 448 record_magic(self.magics, 'line', name, meth)
449 449
450 450 def register_alias(self, alias_name, magic_name, magic_kind='line'):
451 451 """Register an alias to a magic function.
452 452
453 453 The alias is an instance of :class:`MagicAlias`, which holds the
454 454 name and kind of the magic it should call. Binding is done at
455 455 call time, so if the underlying magic function is changed the alias
456 456 will call the new function.
457 457
458 458 Parameters
459 459 ----------
460 460 alias_name : str
461 461 The name of the magic to be registered.
462 462
463 463 magic_name : str
464 464 The name of an existing magic.
465 465
466 466 magic_kind : str
467 467 Kind of magic, one of 'line' or 'cell'
468 468 """
469 469
470 470 # `validate_type` is too permissive, as it allows 'line_cell'
471 471 # which we do not handle.
472 472 if magic_kind not in magic_kinds:
473 473 raise ValueError('magic_kind must be one of %s, %s given' %
474 474 magic_kinds, magic_kind)
475 475
476 476 alias = MagicAlias(self.shell, magic_name, magic_kind)
477 477 setattr(self.user_magics, alias_name, alias)
478 478 record_magic(self.magics, magic_kind, alias_name, alias)
479 479
480 480 # Key base class that provides the central functionality for magics.
481 481
482 482
483 483 class Magics(Configurable):
484 484 """Base class for implementing magic functions.
485 485
486 486 Shell functions which can be reached as %function_name. All magic
487 487 functions should accept a string, which they can parse for their own
488 488 needs. This can make some functions easier to type, eg `%cd ../`
489 489 vs. `%cd("../")`
490 490
491 491 Classes providing magic functions need to subclass this class, and they
492 492 MUST:
493 493
494 494 - Use the method decorators `@line_magic` and `@cell_magic` to decorate
495 495 individual methods as magic functions, AND
496 496
497 497 - Use the class decorator `@magics_class` to ensure that the magic
498 498 methods are properly registered at the instance level upon instance
499 499 initialization.
500 500
501 501 See :mod:`magic_functions` for examples of actual implementation classes.
502 502 """
503 503 # Dict holding all command-line options for each magic.
504 504 options_table = None
505 505 # Dict for the mapping of magic names to methods, set by class decorator
506 506 magics = None
507 507 # Flag to check that the class decorator was properly applied
508 508 registered = False
509 509 # Instance of IPython shell
510 510 shell = None
511 511
512 512 def __init__(self, shell=None, **kwargs):
513 513 if not(self.__class__.registered):
514 514 raise ValueError('Magics subclass without registration - '
515 515 'did you forget to apply @magics_class?')
516 516 if shell is not None:
517 517 if hasattr(shell, 'configurables'):
518 518 shell.configurables.append(self)
519 519 if hasattr(shell, 'config'):
520 520 kwargs.setdefault('parent', shell)
521 521 kwargs['shell'] = shell
522 522
523 523 self.shell = shell
524 524 self.options_table = {}
525 525 # The method decorators are run when the instance doesn't exist yet, so
526 526 # they can only record the names of the methods they are supposed to
527 527 # grab. Only now, that the instance exists, can we create the proper
528 528 # mapping to bound methods. So we read the info off the original names
529 529 # table and replace each method name by the actual bound method.
530 530 # But we mustn't clobber the *class* mapping, in case of multiple instances.
531 531 class_magics = self.magics
532 532 self.magics = {}
533 533 for mtype in magic_kinds:
534 534 tab = self.magics[mtype] = {}
535 535 cls_tab = class_magics[mtype]
536 536 for magic_name, meth_name in iteritems(cls_tab):
537 537 if isinstance(meth_name, string_types):
538 538 # it's a method name, grab it
539 539 tab[magic_name] = getattr(self, meth_name)
540 540 else:
541 541 # it's the real thing
542 542 tab[magic_name] = meth_name
543 543 # Configurable **needs** to be initiated at the end or the config
544 544 # magics get screwed up.
545 545 super(Magics, self).__init__(**kwargs)
546 546
547 547 def arg_err(self,func):
548 548 """Print docstring if incorrect arguments were passed"""
549 549 print('Error in arguments:')
550 550 print(oinspect.getdoc(func))
551 551
552 552 def format_latex(self, strng):
553 553 """Format a string for latex inclusion."""
554 554
555 555 # Characters that need to be escaped for latex:
556 556 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
557 557 # Magic command names as headers:
558 558 cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC,
559 559 re.MULTILINE)
560 560 # Magic commands
561 561 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC,
562 562 re.MULTILINE)
563 563 # Paragraph continue
564 564 par_re = re.compile(r'\\$',re.MULTILINE)
565 565
566 566 # The "\n" symbol
567 567 newline_re = re.compile(r'\\n')
568 568
569 569 # Now build the string for output:
570 570 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
571 571 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
572 572 strng)
573 573 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
574 574 strng = par_re.sub(r'\\\\',strng)
575 575 strng = escape_re.sub(r'\\\1',strng)
576 576 strng = newline_re.sub(r'\\textbackslash{}n',strng)
577 577 return strng
578 578
579 579 def parse_options(self, arg_str, opt_str, *long_opts, **kw):
580 580 """Parse options passed to an argument string.
581 581
582 582 The interface is similar to that of :func:`getopt.getopt`, but it
583 583 returns a :class:`~IPython.utils.struct.Struct` with the options as keys
584 584 and the stripped argument string still as a string.
585 585
586 586 arg_str is quoted as a true sys.argv vector by using shlex.split.
587 587 This allows us to easily expand variables, glob files, quote
588 588 arguments, etc.
589 589
590 590 Parameters
591 591 ----------
592 592
593 593 arg_str : str
594 594 The arguments to parse.
595 595
596 596 opt_str : str
597 597 The options specification.
598 598
599 599 mode : str, default 'string'
600 600 If given as 'list', the argument string is returned as a list (split
601 601 on whitespace) instead of a string.
602 602
603 603 list_all : bool, default False
604 604 Put all option values in lists. Normally only options
605 605 appearing more than once are put in a list.
606 606
607 607 posix : bool, default True
608 608 Whether to split the input line in POSIX mode or not, as per the
609 609 conventions outlined in the :mod:`shlex` module from the standard
610 610 library.
611 611 """
612 612
613 613 # inject default options at the beginning of the input line
614 614 caller = sys._getframe(1).f_code.co_name
615 615 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
616 616
617 617 mode = kw.get('mode','string')
618 618 if mode not in ['string','list']:
619 619 raise ValueError('incorrect mode given: %s' % mode)
620 620 # Get options
621 621 list_all = kw.get('list_all',0)
622 622 posix = kw.get('posix', os.name == 'posix')
623 623 strict = kw.get('strict', True)
624 624
625 625 # Check if we have more than one argument to warrant extra processing:
626 626 odict = {} # Dictionary with options
627 627 args = arg_str.split()
628 628 if len(args) >= 1:
629 629 # If the list of inputs only has 0 or 1 thing in it, there's no
630 630 # need to look for options
631 631 argv = arg_split(arg_str, posix, strict)
632 632 # Do regular option processing
633 633 try:
634 634 opts,args = getopt(argv, opt_str, long_opts)
635 635 except GetoptError as e:
636 636 raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
637 637 " ".join(long_opts)))
638 638 for o,a in opts:
639 639 if o.startswith('--'):
640 640 o = o[2:]
641 641 else:
642 642 o = o[1:]
643 643 try:
644 644 odict[o].append(a)
645 645 except AttributeError:
646 646 odict[o] = [odict[o],a]
647 647 except KeyError:
648 648 if list_all:
649 649 odict[o] = [a]
650 650 else:
651 651 odict[o] = a
652 652
653 653 # Prepare opts,args for return
654 654 opts = Struct(odict)
655 655 if mode == 'string':
656 656 args = ' '.join(args)
657 657
658 658 return opts,args
659 659
660 660 def default_option(self, fn, optstr):
661 661 """Make an entry in the options_table for fn, with value optstr"""
662 662
663 663 if fn not in self.lsmagic():
664 664 error("%s is not a magic function" % fn)
665 665 self.options_table[fn] = optstr
666 666
667 667
668 668 class MagicAlias(object):
669 669 """An alias to another magic function.
670 670
671 671 An alias is determined by its magic name and magic kind. Lookup
672 672 is done at call time, so if the underlying magic changes the alias
673 673 will call the new function.
674 674
675 675 Use the :meth:`MagicsManager.register_alias` method or the
676 676 `%alias_magic` magic function to create and register a new alias.
677 677 """
678 678 def __init__(self, shell, magic_name, magic_kind):
679 679 self.shell = shell
680 680 self.magic_name = magic_name
681 681 self.magic_kind = magic_kind
682 682
683 683 self.pretty_target = '%s%s' % (magic_escapes[self.magic_kind], self.magic_name)
684 684 self.__doc__ = "Alias for `%s`." % self.pretty_target
685 685
686 686 self._in_call = False
687 687
688 688 def __call__(self, *args, **kwargs):
689 689 """Call the magic alias."""
690 690 fn = self.shell.find_magic(self.magic_name, self.magic_kind)
691 691 if fn is None:
692 692 raise UsageError("Magic `%s` not found." % self.pretty_target)
693 693
694 694 # Protect against infinite recursion.
695 695 if self._in_call:
696 696 raise UsageError("Infinite recursion detected; "
697 697 "magic aliases cannot call themselves.")
698 698 self._in_call = True
699 699 try:
700 700 return fn(*args, **kwargs)
701 701 finally:
702 702 self._in_call = False
@@ -1,433 +1,433
1 1 # encoding: utf-8
2 2 """
3 3 A mixin for :class:`~IPython.core.application.Application` classes that
4 4 launch InteractiveShell instances, load extensions, etc.
5 5 """
6 6
7 7 # Copyright (c) IPython Development Team.
8 8 # Distributed under the terms of the Modified BSD License.
9 9
10 10 from __future__ import absolute_import
11 11 from __future__ import print_function
12 12
13 13 import glob
14 14 import os
15 15 import sys
16 16
17 17 from traitlets.config.application import boolean_flag
18 18 from traitlets.config.configurable import Configurable
19 19 from traitlets.config.loader import Config
20 20 from IPython.core import pylabtools
21 21 from IPython.utils import py3compat
22 22 from IPython.utils.contexts import preserve_keys
23 23 from IPython.utils.path import filefind
24 24 from traitlets import (
25 25 Unicode, Instance, List, Bool, CaselessStrEnum
26 26 )
27 27 from IPython.lib.inputhook import guis
28 28
29 29 #-----------------------------------------------------------------------------
30 30 # Aliases and Flags
31 31 #-----------------------------------------------------------------------------
32 32
33 33 gui_keys = tuple(sorted([ key for key in guis if key is not None ]))
34 34
35 35 backend_keys = sorted(pylabtools.backends.keys())
36 36 backend_keys.insert(0, 'auto')
37 37
38 38 shell_flags = {}
39 39
40 40 addflag = lambda *args: shell_flags.update(boolean_flag(*args))
41 41 addflag('autoindent', 'InteractiveShell.autoindent',
42 42 'Turn on autoindenting.', 'Turn off autoindenting.'
43 43 )
44 44 addflag('automagic', 'InteractiveShell.automagic',
45 45 """Turn on the auto calling of magic commands. Type %%magic at the
46 46 IPython prompt for more information.""",
47 47 'Turn off the auto calling of magic commands.'
48 48 )
49 49 addflag('pdb', 'InteractiveShell.pdb',
50 50 "Enable auto calling the pdb debugger after every exception.",
51 51 "Disable auto calling the pdb debugger after every exception."
52 52 )
53 53 # pydb flag doesn't do any config, as core.debugger switches on import,
54 54 # which is before parsing. This just allows the flag to be passed.
55 55 shell_flags.update(dict(
56 56 pydb = ({},
57 57 """Use the third party 'pydb' package as debugger, instead of pdb.
58 58 Requires that pydb is installed."""
59 59 )
60 60 ))
61 61 addflag('pprint', 'PlainTextFormatter.pprint',
62 62 "Enable auto pretty printing of results.",
63 63 "Disable auto pretty printing of results."
64 64 )
65 65 addflag('color-info', 'InteractiveShell.color_info',
66 66 """IPython can display information about objects via a set of functions,
67 67 and optionally can use colors for this, syntax highlighting
68 68 source code and various other elements. This is on by default, but can cause
69 69 problems with some pagers. If you see such problems, you can disable the
70 70 colours.""",
71 71 "Disable using colors for info related things."
72 72 )
73 73 addflag('deep-reload', 'InteractiveShell.deep_reload',
74 74 """ **Deprecated** Enable deep (recursive) reloading by default. IPython can use the
75 75 deep_reload module which reloads changes in modules recursively (it
76 76 replaces the reload() function, so you don't need to change anything to
77 77 use it). deep_reload() forces a full reload of modules whose code may
78 78 have changed, which the default reload() function does not. When
79 79 deep_reload is off, IPython will use the normal reload(), but
80 80 deep_reload will still be available as dreload(). This feature is off
81 81 by default [which means that you have both normal reload() and
82 82 dreload()].""",
83 83 "Disable deep (recursive) reloading by default."
84 84 )
85 85 nosep_config = Config()
86 86 nosep_config.InteractiveShell.separate_in = ''
87 87 nosep_config.InteractiveShell.separate_out = ''
88 88 nosep_config.InteractiveShell.separate_out2 = ''
89 89
90 90 shell_flags['nosep']=(nosep_config, "Eliminate all spacing between prompts.")
91 91 shell_flags['pylab'] = (
92 92 {'InteractiveShellApp' : {'pylab' : 'auto'}},
93 93 """Pre-load matplotlib and numpy for interactive use with
94 94 the default matplotlib backend."""
95 95 )
96 96 shell_flags['matplotlib'] = (
97 97 {'InteractiveShellApp' : {'matplotlib' : 'auto'}},
98 98 """Configure matplotlib for interactive use with
99 99 the default matplotlib backend."""
100 100 )
101 101
102 102 # it's possible we don't want short aliases for *all* of these:
103 103 shell_aliases = dict(
104 104 autocall='InteractiveShell.autocall',
105 105 colors='InteractiveShell.colors',
106 106 logfile='InteractiveShell.logfile',
107 107 logappend='InteractiveShell.logappend',
108 108 c='InteractiveShellApp.code_to_run',
109 109 m='InteractiveShellApp.module_to_run',
110 110 ext='InteractiveShellApp.extra_extension',
111 111 gui='InteractiveShellApp.gui',
112 112 pylab='InteractiveShellApp.pylab',
113 113 matplotlib='InteractiveShellApp.matplotlib',
114 114 )
115 115 shell_aliases['cache-size'] = 'InteractiveShell.cache_size'
116 116
117 117 #-----------------------------------------------------------------------------
118 118 # Main classes and functions
119 119 #-----------------------------------------------------------------------------
120 120
121 121 class InteractiveShellApp(Configurable):
122 122 """A Mixin for applications that start InteractiveShell instances.
123 123
124 124 Provides configurables for loading extensions and executing files
125 125 as part of configuring a Shell environment.
126 126
127 127 The following methods should be called by the :meth:`initialize` method
128 128 of the subclass:
129 129
130 130 - :meth:`init_path`
131 131 - :meth:`init_shell` (to be implemented by the subclass)
132 132 - :meth:`init_gui_pylab`
133 133 - :meth:`init_extensions`
134 134 - :meth:`init_code`
135 135 """
136 extensions = List(Unicode, config=True,
136 extensions = List(Unicode(), config=True,
137 137 help="A list of dotted module names of IPython extensions to load."
138 138 )
139 139 extra_extension = Unicode('', config=True,
140 140 help="dotted module name of an IPython extension to load."
141 141 )
142 142
143 143 reraise_ipython_extension_failures = Bool(
144 144 False,
145 145 config=True,
146 146 help="Reraise exceptions encountered loading IPython extensions?",
147 147 )
148 148
149 149 # Extensions that are always loaded (not configurable)
150 default_extensions = List(Unicode, [u'storemagic'], config=False)
150 default_extensions = List(Unicode(), [u'storemagic'], config=False)
151 151
152 152 hide_initial_ns = Bool(True, config=True,
153 153 help="""Should variables loaded at startup (by startup files, exec_lines, etc.)
154 154 be hidden from tools like %who?"""
155 155 )
156 156
157 exec_files = List(Unicode, config=True,
157 exec_files = List(Unicode(), config=True,
158 158 help="""List of files to run at IPython startup."""
159 159 )
160 160 exec_PYTHONSTARTUP = Bool(True, config=True,
161 161 help="""Run the file referenced by the PYTHONSTARTUP environment
162 162 variable at IPython startup."""
163 163 )
164 164 file_to_run = Unicode('', config=True,
165 165 help="""A file to be run""")
166 166
167 exec_lines = List(Unicode, config=True,
167 exec_lines = List(Unicode(), config=True,
168 168 help="""lines of code to run at IPython startup."""
169 169 )
170 170 code_to_run = Unicode('', config=True,
171 171 help="Execute the given command string."
172 172 )
173 173 module_to_run = Unicode('', config=True,
174 174 help="Run the module as a script."
175 175 )
176 176 gui = CaselessStrEnum(gui_keys, config=True, allow_none=True,
177 177 help="Enable GUI event loop integration with any of {0}.".format(gui_keys)
178 178 )
179 179 matplotlib = CaselessStrEnum(backend_keys, allow_none=True,
180 180 config=True,
181 181 help="""Configure matplotlib for interactive use with
182 182 the default matplotlib backend."""
183 183 )
184 184 pylab = CaselessStrEnum(backend_keys, allow_none=True,
185 185 config=True,
186 186 help="""Pre-load matplotlib and numpy for interactive use,
187 187 selecting a particular matplotlib backend and loop integration.
188 188 """
189 189 )
190 190 pylab_import_all = Bool(True, config=True,
191 191 help="""If true, IPython will populate the user namespace with numpy, pylab, etc.
192 192 and an ``import *`` is done from numpy and pylab, when using pylab mode.
193 193
194 194 When False, pylab mode should not import any names into the user namespace.
195 195 """
196 196 )
197 197 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC',
198 198 allow_none=True)
199 199
200 200 user_ns = Instance(dict, args=None, allow_none=True)
201 201 def _user_ns_changed(self, name, old, new):
202 202 if self.shell is not None:
203 203 self.shell.user_ns = new
204 204 self.shell.init_user_ns()
205 205
206 206 def init_path(self):
207 207 """Add current working directory, '', to sys.path"""
208 208 if sys.path[0] != '':
209 209 sys.path.insert(0, '')
210 210
211 211 def init_shell(self):
212 212 raise NotImplementedError("Override in subclasses")
213 213
214 214 def init_gui_pylab(self):
215 215 """Enable GUI event loop integration, taking pylab into account."""
216 216 enable = False
217 217 shell = self.shell
218 218 if self.pylab:
219 219 enable = lambda key: shell.enable_pylab(key, import_all=self.pylab_import_all)
220 220 key = self.pylab
221 221 elif self.matplotlib:
222 222 enable = shell.enable_matplotlib
223 223 key = self.matplotlib
224 224 elif self.gui:
225 225 enable = shell.enable_gui
226 226 key = self.gui
227 227
228 228 if not enable:
229 229 return
230 230
231 231 try:
232 232 r = enable(key)
233 233 except ImportError:
234 234 self.log.warn("Eventloop or matplotlib integration failed. Is matplotlib installed?")
235 235 self.shell.showtraceback()
236 236 return
237 237 except Exception:
238 238 self.log.warn("GUI event loop or pylab initialization failed")
239 239 self.shell.showtraceback()
240 240 return
241 241
242 242 if isinstance(r, tuple):
243 243 gui, backend = r[:2]
244 244 self.log.info("Enabling GUI event loop integration, "
245 245 "eventloop=%s, matplotlib=%s", gui, backend)
246 246 if key == "auto":
247 247 print("Using matplotlib backend: %s" % backend)
248 248 else:
249 249 gui = r
250 250 self.log.info("Enabling GUI event loop integration, "
251 251 "eventloop=%s", gui)
252 252
253 253 def init_extensions(self):
254 254 """Load all IPython extensions in IPythonApp.extensions.
255 255
256 256 This uses the :meth:`ExtensionManager.load_extensions` to load all
257 257 the extensions listed in ``self.extensions``.
258 258 """
259 259 try:
260 260 self.log.debug("Loading IPython extensions...")
261 261 extensions = self.default_extensions + self.extensions
262 262 if self.extra_extension:
263 263 extensions.append(self.extra_extension)
264 264 for ext in extensions:
265 265 try:
266 266 self.log.info("Loading IPython extension: %s" % ext)
267 267 self.shell.extension_manager.load_extension(ext)
268 268 except:
269 269 if self.reraise_ipython_extension_failures:
270 270 raise
271 271 msg = ("Error in loading extension: {ext}\n"
272 272 "Check your config files in {location}".format(
273 273 ext=ext,
274 274 location=self.profile_dir.location
275 275 ))
276 276 self.log.warn(msg, exc_info=True)
277 277 except:
278 278 if self.reraise_ipython_extension_failures:
279 279 raise
280 280 self.log.warn("Unknown error in loading extensions:", exc_info=True)
281 281
282 282 def init_code(self):
283 283 """run the pre-flight code, specified via exec_lines"""
284 284 self._run_startup_files()
285 285 self._run_exec_lines()
286 286 self._run_exec_files()
287 287
288 288 # Hide variables defined here from %who etc.
289 289 if self.hide_initial_ns:
290 290 self.shell.user_ns_hidden.update(self.shell.user_ns)
291 291
292 292 # command-line execution (ipython -i script.py, ipython -m module)
293 293 # should *not* be excluded from %whos
294 294 self._run_cmd_line_code()
295 295 self._run_module()
296 296
297 297 # flush output, so itwon't be attached to the first cell
298 298 sys.stdout.flush()
299 299 sys.stderr.flush()
300 300
301 301 def _run_exec_lines(self):
302 302 """Run lines of code in IPythonApp.exec_lines in the user's namespace."""
303 303 if not self.exec_lines:
304 304 return
305 305 try:
306 306 self.log.debug("Running code from IPythonApp.exec_lines...")
307 307 for line in self.exec_lines:
308 308 try:
309 309 self.log.info("Running code in user namespace: %s" %
310 310 line)
311 311 self.shell.run_cell(line, store_history=False)
312 312 except:
313 313 self.log.warn("Error in executing line in user "
314 314 "namespace: %s" % line)
315 315 self.shell.showtraceback()
316 316 except:
317 317 self.log.warn("Unknown error in handling IPythonApp.exec_lines:")
318 318 self.shell.showtraceback()
319 319
320 320 def _exec_file(self, fname, shell_futures=False):
321 321 try:
322 322 full_filename = filefind(fname, [u'.', self.ipython_dir])
323 323 except IOError as e:
324 324 self.log.warn("File not found: %r"%fname)
325 325 return
326 326 # Make sure that the running script gets a proper sys.argv as if it
327 327 # were run from a system shell.
328 328 save_argv = sys.argv
329 329 sys.argv = [full_filename] + self.extra_args[1:]
330 330 # protect sys.argv from potential unicode strings on Python 2:
331 331 if not py3compat.PY3:
332 332 sys.argv = [ py3compat.cast_bytes(a) for a in sys.argv ]
333 333 try:
334 334 if os.path.isfile(full_filename):
335 335 self.log.info("Running file in user namespace: %s" %
336 336 full_filename)
337 337 # Ensure that __file__ is always defined to match Python
338 338 # behavior.
339 339 with preserve_keys(self.shell.user_ns, '__file__'):
340 340 self.shell.user_ns['__file__'] = fname
341 341 if full_filename.endswith('.ipy'):
342 342 self.shell.safe_execfile_ipy(full_filename,
343 343 shell_futures=shell_futures)
344 344 else:
345 345 # default to python, even without extension
346 346 self.shell.safe_execfile(full_filename,
347 347 self.shell.user_ns,
348 348 shell_futures=shell_futures)
349 349 finally:
350 350 sys.argv = save_argv
351 351
352 352 def _run_startup_files(self):
353 353 """Run files from profile startup directory"""
354 354 startup_dir = self.profile_dir.startup_dir
355 355 startup_files = []
356 356
357 357 if self.exec_PYTHONSTARTUP and os.environ.get('PYTHONSTARTUP', False) and \
358 358 not (self.file_to_run or self.code_to_run or self.module_to_run):
359 359 python_startup = os.environ['PYTHONSTARTUP']
360 360 self.log.debug("Running PYTHONSTARTUP file %s...", python_startup)
361 361 try:
362 362 self._exec_file(python_startup)
363 363 except:
364 364 self.log.warn("Unknown error in handling PYTHONSTARTUP file %s:", python_startup)
365 365 self.shell.showtraceback()
366 366 finally:
367 367 # Many PYTHONSTARTUP files set up the readline completions,
368 368 # but this is often at odds with IPython's own completions.
369 369 # Do not allow PYTHONSTARTUP to set up readline.
370 370 if self.shell.has_readline:
371 371 self.shell.set_readline_completer()
372 372
373 373 startup_files += glob.glob(os.path.join(startup_dir, '*.py'))
374 374 startup_files += glob.glob(os.path.join(startup_dir, '*.ipy'))
375 375 if not startup_files:
376 376 return
377 377
378 378 self.log.debug("Running startup files from %s...", startup_dir)
379 379 try:
380 380 for fname in sorted(startup_files):
381 381 self._exec_file(fname)
382 382 except:
383 383 self.log.warn("Unknown error in handling startup files:")
384 384 self.shell.showtraceback()
385 385
386 386 def _run_exec_files(self):
387 387 """Run files from IPythonApp.exec_files"""
388 388 if not self.exec_files:
389 389 return
390 390
391 391 self.log.debug("Running files in IPythonApp.exec_files...")
392 392 try:
393 393 for fname in self.exec_files:
394 394 self._exec_file(fname)
395 395 except:
396 396 self.log.warn("Unknown error in handling IPythonApp.exec_files:")
397 397 self.shell.showtraceback()
398 398
399 399 def _run_cmd_line_code(self):
400 400 """Run code or file specified at the command-line"""
401 401 if self.code_to_run:
402 402 line = self.code_to_run
403 403 try:
404 404 self.log.info("Running code given at command line (c=): %s" %
405 405 line)
406 406 self.shell.run_cell(line, store_history=False)
407 407 except:
408 408 self.log.warn("Error in executing line in user namespace: %s" %
409 409 line)
410 410 self.shell.showtraceback()
411 411
412 412 # Like Python itself, ignore the second if the first of these is present
413 413 elif self.file_to_run:
414 414 fname = self.file_to_run
415 415 try:
416 416 self._exec_file(fname, shell_futures=True)
417 417 except:
418 418 self.log.warn("Error in executing file in user namespace: %s" %
419 419 fname)
420 420 self.shell.showtraceback()
421 421
422 422 def _run_module(self):
423 423 """Run module specified at the command-line."""
424 424 if self.module_to_run:
425 425 # Make sure that the module gets a proper sys.argv as if it were
426 426 # run using `python -m`.
427 427 save_argv = sys.argv
428 428 sys.argv = [sys.executable] + self.extra_args
429 429 try:
430 430 self.shell.safe_run_module(self.module_to_run,
431 431 self.shell.user_ns)
432 432 finally:
433 433 sys.argv = save_argv
General Comments 0
You need to be logged in to leave comments. Login now