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