##// END OF EJS Templates
updated documentation on display formatters
Greg Caporaso -
Show More
@@ -1,279 +1,285 b''
1 1 """Various display related classes.
2 2
3 3 Authors : MinRK, gregcaporaso, dannystaple
4 4 """
5 5 import urllib
6 6
7 7 from os.path import exists, isfile, splitext, abspath, join, isdir
8 8 from os import walk
9 9
10 10
11 11 class YouTubeVideo(object):
12 12 """Class for embedding a YouTube Video in an IPython session, based on its video id.
13 13
14 14 e.g. to embed the video on this page:
15 15
16 16 http://www.youtube.com/watch?v=foo
17 17
18 18 you would do:
19 19
20 20 vid = YouTubeVideo("foo")
21 21 display(vid)
22 22
23 23 To start from 30 seconds:
24 24
25 25 vid = YouTubeVideo("abc", start=30)
26 26 display(vid)
27 27
28 28 To calculate seconds from time as hours, minutes, seconds use:
29 29 start=int(timedelta(hours=1, minutes=46, seconds=40).total_seconds())
30 30
31 31 Other parameters can be provided as documented at
32 32 https://developers.google.com/youtube/player_parameters#parameter-subheader
33 33 """
34 34
35 35 def __init__(self, id, width=400, height=300, **kwargs):
36 36 self.id = id
37 37 self.width = width
38 38 self.height = height
39 39 self.params = kwargs
40 40
41 41 def _repr_html_(self):
42 42 """return YouTube embed iframe for this video id"""
43 43 if self.params:
44 44 params = "?" + urllib.urlencode(self.params)
45 45 else:
46 46 params = ""
47 47 return """
48 48 <iframe
49 49 width="%i"
50 50 height="%i"
51 51 src="http://www.youtube.com/embed/%s%s"
52 52 frameborder="0"
53 53 allowfullscreen
54 54 ></iframe>
55 55 """ % (self.width, self.height, self.id, params)
56 56
57 57 class FileLink(object):
58 58 """Class for embedding a local file link in an IPython session, based on path
59 59
60 60 e.g. to embed a link that was generated in the IPython notebook as my/data.txt
61 61
62 62 you would do:
63 63
64 64 local_file = FileLink("my/data.txt")
65 65 display(local_file)
66 66
67 67 or in the HTML notebook, just
68 68
69 69 FileLink("my/data.txt")
70 70 """
71 71
72 72 html_link_str = "<a href='%s' target='_blank'>%s</a>"
73 73
74 74 def __init__(self,
75 75 path,
76 76 url_prefix='files/',
77 77 result_html_prefix='',
78 78 result_html_suffix='<br>'):
79 79 """
80 80 path : path to the file or directory that should be formatted
81 81 directory_prefix : prefix to be prepended to all files to form a
82 82 working link [default: 'files']
83 83 result_html_prefix : text to append to beginning to link
84 84 [default: none]
85 85 result_html_suffix : text to append at the end of link
86 86 [default: '<br>']
87 87 """
88 88 self.path = path
89 89 self.url_prefix = url_prefix
90 90 self.result_html_prefix = result_html_prefix
91 91 self.result_html_suffix = result_html_suffix
92 92
93 93 def _format_path(self):
94 94 fp = ''.join([self.url_prefix,self.path])
95 95 return ''.join([self.result_html_prefix,
96 96 self.html_link_str % (fp, self.path),
97 97 self.result_html_suffix])
98 98
99 99 def _repr_html_(self):
100 100 """return html link to file
101 101 """
102 102 if not exists(self.path):
103 103 return ("Path (<tt>%s</tt>) doesn't exist. "
104 104 "It may still be in the process of "
105 105 "being generated, or you may have the "
106 106 "incorrect path." % self.path)
107 107
108 108 return self._format_path()
109 109
110 110 def __repr__(self):
111 111 """return absolute path to file
112 112 """
113 113 return abspath(self.path)
114 114
115 115 # Create an alias for formatting a single directory name as a link.
116 116 # Right now this is the same as a formatting for a single file, but
117 117 # we'll encourage users to reference these with a different class in
118 118 # case we want to change this in the future.
119 119 DirectoryLink = FileLink
120 120
121 121 class FileLinks(FileLink):
122 122 """Class for embedding local file links in an IPython session, based on path
123 123
124 124 e.g. to embed links to files that were generated in the IPython notebook under my/data
125 125
126 126 you would do:
127 127
128 128 local_files = FileLinks("my/data")
129 129 display(local_files)
130 130
131 131 or in the HTML notebook, just
132 132
133 133 FileLinks("my/data")
134 134
135 135 """
136 136 def __init__(self,
137 137 path,
138 138 url_prefix='files/',
139 139 included_suffixes=None,
140 140 result_html_prefix='',
141 141 result_html_suffix='<br>',
142 142 notebook_display_formatter=None,
143 143 terminal_display_formatter=None):
144 144 """
145 145 included_suffixes : list of filename suffixes to include when
146 146 formatting output [default: include all files]
147 147
148 148 See the FileLink (baseclass of LocalDirectory) docstring for
149 149 information on additional parameters.
150 150
151 notebook_display_formatter : func passed to os.path.walk when
152 formatting links for display in the notebook. This function
153 should be of the form: f(dirname, fnames) where dirname is the
154 name of a directory (a string) and fnames is a list of the
155 files in that directory (not including subdirectories) and
156 returns a list of lines that should be used to print that text
157 in the notebook. This function is iterated over for each
158 directory in self.path. A default formatter is in place, but
159 a function can be passed to support alternative formatting.
151 notebook_display_formatter : func used to format links for display
152 in the notebook. See discussion of formatter function below.
160 153
161 terminal_display_formatter : func passed to os.path.walk when
162 formatting links for display in the terminal. This function
163 should be of the form: f(dirname, fnames) where dirname is the
164 name of a directory (a string) and fnames is a list of the
165 files in that directory (not including subdirectories) and
166 returns a list of lines that should be used to print that text
167 in the terminal. This function is iterated over for each
168 directory in self.path. A default formatter is in place, but
169 a function can be passed to support alternative formatting.
154 terminal_display_formatter : func used to format links for display
155 in the terminal. See discussion of formatter function below.
156
157
158 Passing custom formatter functions
159 ----------------------------------
160 Formatter functions must be of the form:
161 f(dirname, fnames, included_suffixes)
162 dirname : the name of a directory (a string),
163 fnames : a list of the files in that directory
164 included_suffixes : a list of the file suffixes that should be
165 included in the output (passing None means
166 to include all suffixes in the output in
167 the built-in formatters)
168
169 returns a list of lines that should will be print in the
170 notebook (if passing notebook_display_formatter) or the terminal
171 (if passing terminal_display_formatter). This function is iterated
172 over for each directory in self.path. Default formatters are in
173 place, can be passed here to support alternative formatting.
170 174
171 175 """
172 176 self.included_suffixes = included_suffixes
173 177 # remove trailing slashs for more consistent output formatting
174 178 path = path.rstrip('/')
175 179 FileLink.__init__(self,
176 180 path,
177 181 url_prefix,
178 182 result_html_prefix,
179 183 result_html_suffix)
180 184
181 185 self.notebook_display_formatter = \
182 186 notebook_display_formatter or self._get_notebook_display_formatter()
183 187 self.terminal_display_formatter = \
184 188 terminal_display_formatter or self._get_terminal_display_formatter()
185 189
186 190 def _get_display_formatter(self,
187 191 dirname_output_format,
188 192 fname_output_format,
189 193 fp_format):
190 """ generate function to format output- the resulting function will
191 take a list to be populated with the output lines to print,
194 """ generate built-in formatter function
195
196 this is used to define both the notebook and terminal built-in
197 formatters as they only differ by some wrapper text for each entry
192 198
193 199 dirname_output_format: string to use for formatting directory
194 200 names, dirname will be substituted for a single "%s" which
195 201 must appear in this string
196 202 fname_output_format: string to use for formatting file names,
197 203 if a single "%s" appears in the string, fname will be substituted
198 204 if two "%s" appear in the string, the path to fname will be
199 205 substituted for the first and fname will be substituted for the
200 206 second
201 207 fp_format: string to use for formatting filepaths, must contain
202 208 exactly two "%s" and the dirname will be subsituted for the first
203 209 and fname will be substituted for the second
204 210 """
205 211 def f(dirname, fnames, included_suffixes=None):
206 212 result = []
207 213 # begin by figuring out which filenames, if any,
208 214 # are going to be displayed
209 215 display_fnames = []
210 216 for fname in fnames:
211 217 if (isfile(join(dirname,fname)) and
212 218 (included_suffixes == None or
213 219 splitext(fname)[1] in included_suffixes)):
214 220 display_fnames.append(fname)
215 221
216 222 if len(display_fnames) == 0:
217 223 # if there are no filenames to display, don't print anything
218 224 # (not even the directory name)
219 225 pass
220 226 else:
221 227 # otherwise print the formatted directory name followed by
222 228 # the formatted filenames
223 229 dirname_output_line = dirname_output_format % dirname
224 230 result.append(dirname_output_line)
225 231 for fname in display_fnames:
226 232 fp = fp_format % (dirname,fname)
227 233 try:
228 234 # output can include both a filepath and a filename...
229 235 fname_output_line = fname_output_format % (fp, fname)
230 236 except TypeError:
231 237 # ... or just a single filepath
232 238 fname_output_line = fname_output_format % fname
233 239 result.append(fname_output_line)
234 240 return result
235 241 return f
236 242
237 243 def _get_notebook_display_formatter(self,
238 244 spacer="&nbsp;&nbsp;"):
239 245 """ generate function to use for notebook formatting
240 246 """
241 247 dirname_output_format = \
242 248 self.result_html_prefix + "%s/" + self.result_html_suffix
243 249 fname_output_format = \
244 250 self.result_html_prefix + spacer + self.html_link_str + self.result_html_suffix
245 251 fp_format = self.url_prefix + '%s/%s'
246 252
247 253 return self._get_display_formatter(dirname_output_format,
248 254 fname_output_format,
249 255 fp_format)
250 256
251 257 def _get_terminal_display_formatter(self,
252 258 spacer=" "):
253 259 """ generate function to use for terminal formatting
254 260 """
255 261 dirname_output_format = "%s/"
256 262 fname_output_format = spacer + "%s"
257 263 fp_format = '%s/%s'
258 264
259 265 return self._get_display_formatter(dirname_output_format,
260 266 fname_output_format,
261 267 fp_format)
262 268
263 269 def _format_path(self):
264 270 result_lines = []
265 271 walked_dir = list(walk(self.path))
266 272 walked_dir.sort()
267 273 for dirname, subdirs, fnames in walked_dir:
268 274 result_lines += self.notebook_display_formatter(dirname, fnames, self.included_suffixes)
269 275 return '\n'.join(result_lines)
270 276
271 277 def __repr__(self):
272 278 """return newline-separated absolute paths
273 279 """
274 280 result_lines = []
275 281 walked_dir = list(walk(self.path))
276 282 walked_dir.sort()
277 283 for dirname, subdirs, fnames in walked_dir:
278 284 result_lines += self.terminal_display_formatter(dirname, fnames, self.included_suffixes)
279 285 return '\n'.join(result_lines)
General Comments 0
You need to be logged in to leave comments. Login now