##// END OF EJS Templates
Update irunner - needs work on pexpect to work in Python 3.
Update irunner - needs work on pexpect to work in Python 3.

File last commit:

r4872:34c10438
r4893:d5ec58fa
Show More
display.py
383 lines | 11.6 KiB | text/x-python | PythonLexer
Brian Granger
Display system is fully working now....
r3278 # -*- coding: utf-8 -*-
"""Top-level display functions for displaying object in different formats.
Authors:
* Brian Granger
"""
#-----------------------------------------------------------------------------
# Copyright (C) 2008-2010 The IPython Development Team
#
# Distributed under the terms of the BSD License. The full license is in
# the file COPYING, distributed as part of this software.
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
Brian E. Granger
Updates to the display system....
r4526 from .displaypub import (
publish_pretty, publish_html,
publish_latex, publish_svg,
publish_png, publish_json,
Brian E. Granger
Finishing display system work....
r4528 publish_javascript, publish_jpeg
Brian E. Granger
Updates to the display system....
r4526 )
Brian Granger
Display system is fully working now....
r3278 #-----------------------------------------------------------------------------
# Main functions
#-----------------------------------------------------------------------------
Brian Granger
Final work on display system....
r3288 def display(*objs, **kwargs):
Brian Granger
Display system is fully working now....
r3278 """Display a Python object in all frontends.
By default all representations will be computed and sent to the frontends.
Frontends can decide which representation is used and how.
Parameters
----------
Brian Granger
Final work on display system....
r3288 objs : tuple of objects
The Python objects to display.
Brian Granger
Display system is fully working now....
r3278 include : list or tuple, optional
A list of format type strings (MIME types) to include in the
format data dict. If this is set *only* the format types included
in this list will be computed.
exclude : list or tuple, optional
A list of format type string (MIME types) to exclue in the format
data dict. If this is set all format types will be computed,
except for those included in this argument.
"""
Brian Granger
Final work on display system....
r3288 include = kwargs.get('include')
exclude = kwargs.get('exclude')
Bernardo B. Marques
remove all trailling spaces
r4872
Brian Granger
Display system is fully working now....
r3278 from IPython.core.interactiveshell import InteractiveShell
Brian Granger
Addressing review comments....
r3286 inst = InteractiveShell.instance()
format = inst.display_formatter.format
publish = inst.display_pub.publish
Brian Granger
Display system is fully working now....
r3278
Brian Granger
Final work on display system....
r3288 for obj in objs:
format_dict = format(obj, include=include, exclude=exclude)
publish('IPython.core.display.display', format_dict)
Brian Granger
Display system is fully working now....
r3278
Brian E. Granger
Updates to the display system....
r4526 def display_pretty(*objs, **kwargs):
Brian Granger
More improvements to the display system....
r3279 """Display the pretty (default) representation of an object.
Parameters
----------
Brian Granger
Final work on display system....
r3288 objs : tuple of objects
Brian E. Granger
Updates to the display system....
r4526 The Python objects to display, or if raw=True raw text data to
display.
raw : bool
Are the data objects raw data or Python objects that need to be
formatted before display? [default: False]
Brian Granger
More improvements to the display system....
r3279 """
Brian E. Granger
Updates to the display system....
r4526 raw = kwargs.pop('raw',False)
if raw:
for obj in objs:
publish_pretty(obj)
else:
display(*objs, include=['text/plain'])
Brian Granger
More improvements to the display system....
r3279
Brian E. Granger
Updates to the display system....
r4526 def display_html(*objs, **kwargs):
Brian Granger
Display system is fully working now....
r3278 """Display the HTML representation of an object.
Parameters
----------
Brian Granger
Final work on display system....
r3288 objs : tuple of objects
Brian E. Granger
Finishing display system work....
r4528 The Python objects to display, or if raw=True raw HTML data to
Brian E. Granger
Updates to the display system....
r4526 display.
raw : bool
Are the data objects raw data or Python objects that need to be
formatted before display? [default: False]
"""
raw = kwargs.pop('raw',False)
if raw:
for obj in objs:
publish_html(obj)
else:
display(*objs, include=['text/plain','text/html'])
Brian Granger
Display system is fully working now....
r3278
Brian E. Granger
Updates to the display system....
r4526 def display_svg(*objs, **kwargs):
Brian Granger
Display system is fully working now....
r3278 """Display the SVG representation of an object.
Parameters
----------
Brian Granger
Final work on display system....
r3288 objs : tuple of objects
Brian E. Granger
Updates to the display system....
r4526 The Python objects to display, or if raw=True raw svg data to
display.
raw : bool
Are the data objects raw data or Python objects that need to be
formatted before display? [default: False]
Brian Granger
Display system is fully working now....
r3278 """
Brian E. Granger
Updates to the display system....
r4526 raw = kwargs.pop('raw',False)
if raw:
for obj in objs:
publish_svg(obj)
else:
display(*objs, include=['text/plain','image/svg+xml'])
Brian Granger
Display system is fully working now....
r3278
Brian E. Granger
Updates to the display system....
r4526 def display_png(*objs, **kwargs):
Brian Granger
Display system is fully working now....
r3278 """Display the PNG representation of an object.
Parameters
----------
Brian Granger
Final work on display system....
r3288 objs : tuple of objects
Brian E. Granger
Updates to the display system....
r4526 The Python objects to display, or if raw=True raw png data to
display.
raw : bool
Are the data objects raw data or Python objects that need to be
formatted before display? [default: False]
Brian Granger
Display system is fully working now....
r3278 """
Brian E. Granger
Updates to the display system....
r4526 raw = kwargs.pop('raw',False)
if raw:
for obj in objs:
publish_png(obj)
else:
display(*objs, include=['text/plain','image/png'])
Brian Granger
Display system is fully working now....
r3278
Brian E. Granger
Finishing display system work....
r4528 def display_jpeg(*objs, **kwargs):
"""Display the JPEG representation of an object.
Parameters
----------
objs : tuple of objects
The Python objects to display, or if raw=True raw JPEG data to
display.
raw : bool
Are the data objects raw data or Python objects that need to be
formatted before display? [default: False]
"""
raw = kwargs.pop('raw',False)
if raw:
for obj in objs:
Brian E. Granger
Fixing two minor things for review....
r4577 publish_jpeg(obj)
Brian E. Granger
Finishing display system work....
r4528 else:
display(*objs, include=['text/plain','image/jpeg'])
Brian E. Granger
Updates to the display system....
r4526 def display_latex(*objs, **kwargs):
Brian Granger
Display system is fully working now....
r3278 """Display the LaTeX representation of an object.
Parameters
----------
Brian Granger
Final work on display system....
r3288 objs : tuple of objects
Brian E. Granger
Updates to the display system....
r4526 The Python objects to display, or if raw=True raw latex data to
display.
raw : bool
Are the data objects raw data or Python objects that need to be
formatted before display? [default: False]
Brian Granger
Display system is fully working now....
r3278 """
Brian E. Granger
Updates to the display system....
r4526 raw = kwargs.pop('raw',False)
if raw:
for obj in objs:
publish_latex(obj)
else:
display(*objs, include=['text/plain','text/latex'])
Brian Granger
Display system is fully working now....
r3278
Brian E. Granger
Updates to the display system....
r4526 def display_json(*objs, **kwargs):
Brian Granger
Display system is fully working now....
r3278 """Display the JSON representation of an object.
Parameters
----------
Brian Granger
Final work on display system....
r3288 objs : tuple of objects
Brian E. Granger
Updates to the display system....
r4526 The Python objects to display, or if raw=True raw json data to
display.
raw : bool
Are the data objects raw data or Python objects that need to be
formatted before display? [default: False]
Brian Granger
Display system is fully working now....
r3278 """
Brian E. Granger
Updates to the display system....
r4526 raw = kwargs.pop('raw',False)
if raw:
for obj in objs:
publish_json(obj)
else:
display(*objs, include=['text/plain','application/json'])
Brian Granger
Display system is fully working now....
r3278
Brian E. Granger
Updates to the display system....
r4526 def display_javascript(*objs, **kwargs):
Brian Granger
Renaming the special methods of the formatters....
r3878 """Display the Javascript representation of an object.
Brian Granger
Display system is fully working now....
r3278
Brian Granger
Renaming the special methods of the formatters....
r3878 Parameters
----------
objs : tuple of objects
Brian E. Granger
Updates to the display system....
r4526 The Python objects to display, or if raw=True raw javascript data to
display.
raw : bool
Are the data objects raw data or Python objects that need to be
formatted before display? [default: False]
Brian Granger
Renaming the special methods of the formatters....
r3878 """
Brian E. Granger
Updates to the display system....
r4526 raw = kwargs.pop('raw',False)
if raw:
for obj in objs:
publish_javascript(obj)
else:
display(*objs, include=['text/plain','application/javascript'])
#-----------------------------------------------------------------------------
# Smart classes
#-----------------------------------------------------------------------------
class DisplayObject(object):
"""An object that wraps data to be displayed."""
Brian E. Granger
Finishing display system work....
r4528 _read_flags = 'r'
def __init__(self, data=None, url=None, filename=None):
"""Create a display object given raw data.
Brian E. Granger
Updates to the display system....
r4526
When this object is returned by an expression or passed to the
display function, it will result in the data being displayed
in the frontend. The MIME type of the data should match the
subclasses used, so the Png subclass should be used for 'image/png'
data. If the data is a URL, the data will first be downloaded
Bernardo B. Marques
remove all trailling spaces
r4872 and then displayed. If
Brian E. Granger
Updates to the display system....
r4526
Parameters
----------
data : unicode, str or bytes
The raw data or a URL to download the data from.
Brian E. Granger
Finishing display system work....
r4528 url : unicode
A URL to download the data from.
filename : unicode
Path to a local file to load the data from.
Brian E. Granger
Updates to the display system....
r4526 """
Brian E. Granger
Finishing display system work....
r4528 if data is not None and data.startswith('http'):
self.url = data
self.filename = None
self.data = None
Brian E. Granger
Updates to the display system....
r4526 else:
self.data = data
Brian E. Granger
Finishing display system work....
r4528 self.url = url
self.filename = None if filename is None else unicode(filename)
self.reload()
def reload(self):
"""Reload the raw data from file or URL."""
if self.filename is not None:
with open(self.filename, self._read_flags) as f:
self.data = f.read()
elif self.url is not None:
try:
import urllib2
response = urllib2.urlopen(self.url)
self.data = response.read()
MinRK
respect encoding of display data from urls
r4684 # extract encoding from header, if there is one:
encoding = None
for sub in response.headers['content-type'].split(';'):
sub = sub.strip()
if sub.startswith('charset'):
encoding = sub.split('=')[-1].strip()
break
# decode data, if an encoding was specified
if encoding:
self.data = self.data.decode(encoding, 'replace')
Brian E. Granger
Finishing display system work....
r4528 except:
self.data = None
Brian E. Granger
Updates to the display system....
r4526
class Pretty(DisplayObject):
def _repr_pretty_(self):
return self.data
Brian E. Granger
Finishing display system work....
r4528 class HTML(DisplayObject):
Brian E. Granger
Updates to the display system....
r4526
def _repr_html_(self):
return self.data
Brian E. Granger
Finishing display system work....
r4528 class Math(DisplayObject):
Brian E. Granger
Updates to the display system....
r4526
def _repr_latex_(self):
return self.data
Brian E. Granger
Finishing display system work....
r4528 class SVG(DisplayObject):
Brian E. Granger
Updates to the display system....
r4526
def _repr_svg_(self):
return self.data
Brian E. Granger
Finishing display system work....
r4528 class JSON(DisplayObject):
Brian E. Granger
Updates to the display system....
r4526
def _repr_json_(self):
return self.data
Brian E. Granger
Finishing display system work....
r4528 class Javascript(DisplayObject):
Brian E. Granger
Updates to the display system....
r4526
def _repr_javascript_(self):
return self.data
Brian E. Granger
Finishing display system work....
r4528 class Image(DisplayObject):
_read_flags = 'rb'
def __init__(self, data=None, url=None, filename=None, format=u'png', embed=False):
"""Create a display an PNG/JPEG image given raw data.
When this object is returned by an expression or passed to the
display function, it will result in the image being displayed
in the frontend.
Parameters
----------
data : unicode, str or bytes
The raw data or a URL to download the data from.
url : unicode
A URL to download the data from.
filename : unicode
Path to a local file to load the data from.
format : unicode
The format of the image data (png/jpeg/jpg). If a filename or URL is given
for format will be inferred from the filename extension.
embed : bool
Should the image data be embedded in the notebook using a data URI (True)
or be loaded using an <img> tag. Set this to True if you want the image
to be viewable later with no internet connection. If a filename is given
embed is always set to True.
"""
if filename is not None:
ext = self._find_ext(filename)
elif url is not None:
ext = self._find_ext(url)
elif data.startswith('http'):
ext = self._find_ext(data)
else:
ext = None
if ext is not None:
if ext == u'jpg' or ext == u'jpeg':
format = u'jpeg'
if ext == u'png':
format = u'png'
self.format = unicode(format).lower()
self.embed = True if filename is not None else embed
super(Image, self).__init__(data=data, url=url, filename=filename)
def reload(self):
"""Reload the raw data from file or URL."""
if self.embed:
super(Image,self).reload()
def _repr_html_(self):
if not self.embed:
return u'<img src="%s" />' % self.url
def _repr_png_(self):
if self.embed and self.format == u'png':
return self.data
def _repr_jpeg_(self):
if self.embed and (self.format == u'jpeg' or self.format == u'jpg'):
return self.data
def _find_ext(self, s):
return unicode(s.split('.')[-1].lower())