blob: 4bd329f2645dcbddb8f69aaa96fe12a8f446ddcc [file] [log] [blame]
Guido van Rossum7c6ebb51994-03-22 12:05:32 +00001# Open an arbitrary URL
2#
Guido van Rossum838cb281997-02-10 17:51:56 +00003# See the following document for more info on URLs:
4# "Names and Addresses, URIs, URLs, URNs, URCs", at
5# http://www.w3.org/pub/WWW/Addressing/Overview.html
6#
7# See also the HTTP spec (from which the error codes are derived):
8# "HTTP - Hypertext Transfer Protocol", at
9# http://www.w3.org/pub/WWW/Protocols/
10#
11# Related standards and specs:
12# - RFC1808: the "relative URL" spec. (authoritative status)
13# - RFC1738 - the "URL standard". (authoritative status)
14# - RFC1630 - the "URI spec". (informational status)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000015#
16# The object returned by URLopener().open(file) will differ per
17# protocol. All you know is that is has methods read(), readline(),
18# readlines(), fileno(), close() and info(). The read*(), fileno()
19# and close() methods work like those of open files.
Guido van Rossum838cb281997-02-10 17:51:56 +000020# The info() method returns a mimetools.Message object which can be
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000021# used to query various info about the object, if available.
Guido van Rossumbbb0a051995-08-04 04:29:05 +000022# (mimetools.Message objects are queried with the getheader() method.)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000023
Guido van Rossum7c395db1994-07-04 22:14:49 +000024import string
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000025import socket
Jack Jansendc3e3f61995-12-15 13:22:13 +000026import os
Guido van Rossum3c8484e1996-11-20 22:02:24 +000027import sys
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000028
29
Guido van Rossum0dee4ee1999-06-09 15:14:50 +000030__version__ = '1.11' # XXX This version is not always updated :-(
Guido van Rossumf668d171997-06-06 21:11:11 +000031
Jeremy Hyltonf90b0021999-02-25 16:12:12 +000032MAXFTPCACHE = 10 # Trim the ftp cache beyond this size
Guido van Rossum6cb15a01995-06-22 19:00:13 +000033
Jack Jansendc3e3f61995-12-15 13:22:13 +000034# Helper for non-unix systems
35if os.name == 'mac':
Jeremy Hyltonf90b0021999-02-25 16:12:12 +000036 from macurl2path import url2pathname, pathname2url
Guido van Rossum7e7ca0b1998-03-26 21:01:39 +000037elif os.name == 'nt':
Jeremy Hyltonf90b0021999-02-25 16:12:12 +000038 from nturl2path import url2pathname, pathname2url
Jack Jansendc3e3f61995-12-15 13:22:13 +000039else:
Jeremy Hyltonf90b0021999-02-25 16:12:12 +000040 def url2pathname(pathname):
Guido van Rossum367ac801999-03-12 14:31:10 +000041 return unquote(pathname)
Jeremy Hyltonf90b0021999-02-25 16:12:12 +000042 def pathname2url(pathname):
Guido van Rossum367ac801999-03-12 14:31:10 +000043 return quote(pathname)
Guido van Rossum33add0a1998-12-18 15:25:22 +000044
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000045# This really consists of two pieces:
46# (1) a class which handles opening of all sorts of URLs
47# (plus assorted utilities etc.)
48# (2) a set of functions for parsing URLs
49# XXX Should these be separated out into different modules?
50
51
52# Shortcut for basic usage
53_urlopener = None
Guido van Rossumbd013741996-12-10 16:00:28 +000054def urlopen(url, data=None):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +000055 global _urlopener
56 if not _urlopener:
57 _urlopener = FancyURLopener()
58 if data is None:
59 return _urlopener.open(url)
60 else:
61 return _urlopener.open(url, data)
Guido van Rossum9ab96d41998-09-28 14:07:00 +000062def urlretrieve(url, filename=None, reporthook=None):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +000063 global _urlopener
64 if not _urlopener:
65 _urlopener = FancyURLopener()
66 return _urlopener.retrieve(url, filename, reporthook)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000067def urlcleanup():
Jeremy Hyltonf90b0021999-02-25 16:12:12 +000068 if _urlopener:
69 _urlopener.cleanup()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000070
71
72# Class to open URLs.
73# This is a class rather than just a subroutine because we may need
74# more than one set of global protocol-specific options.
Guido van Rossumbbb0a051995-08-04 04:29:05 +000075# Note -- this is a base class for those who don't want the
76# automatic handling of errors type 302 (relocated) and 401
77# (authorization needed).
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000078ftpcache = {}
79class URLopener:
80
Jeremy Hyltonf90b0021999-02-25 16:12:12 +000081 __tempfiles = None
Guido van Rossum29e77811996-11-27 19:39:58 +000082
Jeremy Hyltonf90b0021999-02-25 16:12:12 +000083 # Constructor
84 def __init__(self, proxies=None):
85 if proxies is None:
86 proxies = getproxies()
87 assert hasattr(proxies, 'has_key'), "proxies must be a mapping"
88 self.proxies = proxies
89 server_version = "Python-urllib/%s" % __version__
90 self.addheaders = [('User-agent', server_version)]
91 self.__tempfiles = []
92 self.__unlink = os.unlink # See cleanup()
93 self.tempcache = None
94 # Undocumented feature: if you assign {} to tempcache,
95 # it is used to cache files retrieved with
96 # self.retrieve(). This is not enabled by default
97 # since it does not work for changing documents (and I
98 # haven't got the logic to check expiration headers
99 # yet).
100 self.ftpcache = ftpcache
101 # Undocumented feature: you can use a different
102 # ftp cache by assigning to the .ftpcache member;
103 # in case you want logically independent URL openers
104 # XXX This is not threadsafe. Bah.
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000105
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000106 def __del__(self):
107 self.close()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000108
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000109 def close(self):
110 self.cleanup()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000111
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000112 def cleanup(self):
113 # This code sometimes runs when the rest of this module
114 # has already been deleted, so it can't use any globals
115 # or import anything.
116 if self.__tempfiles:
117 for file in self.__tempfiles:
118 try:
119 self.__unlink(file)
120 except:
121 pass
122 del self.__tempfiles[:]
123 if self.tempcache:
124 self.tempcache.clear()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000125
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000126 # Add a header to be used by the HTTP interface only
127 # e.g. u.addheader('Accept', 'sound/basic')
128 def addheader(self, *args):
129 self.addheaders.append(args)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000130
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000131 # External interface
132 # Use URLopener().open(file) instead of open(file, 'r')
133 def open(self, fullurl, data=None):
134 fullurl = unwrap(fullurl)
135 if self.tempcache and self.tempcache.has_key(fullurl):
136 filename, headers = self.tempcache[fullurl]
137 fp = open(filename, 'rb')
138 return addinfourl(fp, headers, fullurl)
139 type, url = splittype(fullurl)
140 if not type: type = 'file'
141 if self.proxies.has_key(type):
142 proxy = self.proxies[type]
143 type, proxy = splittype(proxy)
144 host, selector = splithost(proxy)
145 url = (host, fullurl) # Signal special case to open_*()
146 name = 'open_' + type
147 if '-' in name:
148 # replace - with _
149 name = string.join(string.split(name, '-'), '_')
150 if not hasattr(self, name):
151 if data is None:
152 return self.open_unknown(fullurl)
153 else:
154 return self.open_unknown(fullurl, data)
155 try:
156 if data is None:
157 return getattr(self, name)(url)
158 else:
159 return getattr(self, name)(url, data)
160 except socket.error, msg:
161 raise IOError, ('socket error', msg), sys.exc_info()[2]
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000162
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000163 # Overridable interface to open unknown URL type
164 def open_unknown(self, fullurl, data=None):
165 type, url = splittype(fullurl)
166 raise IOError, ('url error', 'unknown url type', type)
Guido van Rossumca445401995-08-29 19:19:12 +0000167
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000168 # External interface
169 # retrieve(url) returns (filename, None) for a local object
170 # or (tempfilename, headers) for a remote object
171 def retrieve(self, url, filename=None, reporthook=None):
172 url = unwrap(url)
173 if self.tempcache and self.tempcache.has_key(url):
174 return self.tempcache[url]
175 type, url1 = splittype(url)
176 if not filename and (not type or type == 'file'):
177 try:
178 fp = self.open_local_file(url1)
179 hdrs = fp.info()
180 del fp
181 return url2pathname(splithost(url1)[1]), hdrs
182 except IOError, msg:
183 pass
184 fp = self.open(url)
185 headers = fp.info()
186 if not filename:
187 import tempfile
188 garbage, path = splittype(url)
189 garbage, path = splithost(path or "")
190 path, garbage = splitquery(path or "")
191 path, garbage = splitattr(path or "")
192 suffix = os.path.splitext(path)[1]
193 filename = tempfile.mktemp(suffix)
194 self.__tempfiles.append(filename)
195 result = filename, headers
196 if self.tempcache is not None:
197 self.tempcache[url] = result
198 tfp = open(filename, 'wb')
199 bs = 1024*8
200 size = -1
201 blocknum = 1
202 if reporthook:
203 if headers.has_key("content-length"):
204 size = int(headers["Content-Length"])
205 reporthook(0, bs, size)
206 block = fp.read(bs)
207 if reporthook:
208 reporthook(1, bs, size)
209 while block:
210 tfp.write(block)
211 block = fp.read(bs)
212 blocknum = blocknum + 1
213 if reporthook:
214 reporthook(blocknum, bs, size)
215 fp.close()
216 tfp.close()
217 del fp
218 del tfp
219 return result
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000220
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000221 # Each method named open_<type> knows how to open that type of URL
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000222
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000223 # Use HTTP protocol
224 def open_http(self, url, data=None):
225 import httplib
226 user_passwd = None
227 if type(url) is type(""):
228 host, selector = splithost(url)
229 if host:
230 user_passwd, host = splituser(host)
231 host = unquote(host)
232 realhost = host
233 else:
234 host, selector = url
235 urltype, rest = splittype(selector)
236 url = rest
237 user_passwd = None
238 if string.lower(urltype) != 'http':
239 realhost = None
240 else:
241 realhost, rest = splithost(rest)
242 if realhost:
243 user_passwd, realhost = splituser(realhost)
244 if user_passwd:
245 selector = "%s://%s%s" % (urltype, realhost, rest)
246 #print "proxy via http:", host, selector
247 if not host: raise IOError, ('http error', 'no host given')
248 if user_passwd:
249 import base64
250 auth = string.strip(base64.encodestring(user_passwd))
251 else:
252 auth = None
253 h = httplib.HTTP(host)
254 if data is not None:
255 h.putrequest('POST', selector)
256 h.putheader('Content-type', 'application/x-www-form-urlencoded')
257 h.putheader('Content-length', '%d' % len(data))
258 else:
259 h.putrequest('GET', selector)
260 if auth: h.putheader('Authorization', 'Basic %s' % auth)
261 if realhost: h.putheader('Host', realhost)
262 for args in self.addheaders: apply(h.putheader, args)
263 h.endheaders()
264 if data is not None:
265 h.send(data + '\r\n')
266 errcode, errmsg, headers = h.getreply()
267 fp = h.getfile()
268 if errcode == 200:
269 return addinfourl(fp, headers, "http:" + url)
270 else:
271 if data is None:
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000272 return self.http_error(url, fp, errcode, errmsg, headers)
Guido van Rossum29aab751999-03-09 19:31:21 +0000273 else:
274 return self.http_error(url, fp, errcode, errmsg, headers, data)
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000275
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000276 # Handle http errors.
277 # Derived class can override this, or provide specific handlers
278 # named http_error_DDD where DDD is the 3-digit error code
279 def http_error(self, url, fp, errcode, errmsg, headers, data=None):
280 # First check if there's a specific handler for this error
281 name = 'http_error_%d' % errcode
282 if hasattr(self, name):
283 method = getattr(self, name)
284 if data is None:
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000285 result = method(url, fp, errcode, errmsg, headers)
Jeremy Hyltonb30f52a1999-02-25 16:14:58 +0000286 else:
287 result = method(url, fp, errcode, errmsg, headers, data)
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000288 if result: return result
Jeremy Hyltonb30f52a1999-02-25 16:14:58 +0000289 return self.http_error_default(url, fp, errcode, errmsg, headers)
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000290
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000291 # Default http error handler: close the connection and raises IOError
292 def http_error_default(self, url, fp, errcode, errmsg, headers):
293 void = fp.read()
294 fp.close()
295 raise IOError, ('http error', errcode, errmsg, headers)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000296
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000297 # Use Gopher protocol
298 def open_gopher(self, url):
299 import gopherlib
300 host, selector = splithost(url)
301 if not host: raise IOError, ('gopher error', 'no host given')
302 host = unquote(host)
303 type, selector = splitgophertype(selector)
304 selector, query = splitquery(selector)
305 selector = unquote(selector)
306 if query:
307 query = unquote(query)
308 fp = gopherlib.send_query(selector, query, host)
309 else:
310 fp = gopherlib.send_selector(selector, host)
311 return addinfourl(fp, noheaders(), "gopher:" + url)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000312
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000313 # Use local file or FTP depending on form of URL
314 def open_file(self, url):
315 if url[:2] == '//' and url[2:3] != '/':
316 return self.open_ftp(url)
317 else:
318 return self.open_local_file(url)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000319
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000320 # Use local file
321 def open_local_file(self, url):
322 import mimetypes, mimetools, StringIO
323 mtype = mimetypes.guess_type(url)[0]
324 headers = mimetools.Message(StringIO.StringIO(
325 'Content-Type: %s\n' % (mtype or 'text/plain')))
326 host, file = splithost(url)
327 if not host:
Guido van Rossum336a2011999-06-24 15:27:36 +0000328 urlfile = file
329 if file[:1] == '/':
330 urlfile = 'file://' + file
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000331 return addinfourl(open(url2pathname(file), 'rb'),
Guido van Rossum336a2011999-06-24 15:27:36 +0000332 headers, urlfile)
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000333 host, port = splitport(host)
334 if not port \
335 and socket.gethostbyname(host) in (localhost(), thishost()):
Guido van Rossum336a2011999-06-24 15:27:36 +0000336 urlfile = file
337 if file[:1] == '/':
338 urlfile = 'file://' + file
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000339 return addinfourl(open(url2pathname(file), 'rb'),
Guido van Rossum336a2011999-06-24 15:27:36 +0000340 headers, urlfile)
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000341 raise IOError, ('local file error', 'not on local host')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000342
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000343 # Use FTP protocol
344 def open_ftp(self, url):
345 host, path = splithost(url)
346 if not host: raise IOError, ('ftp error', 'no host given')
347 host, port = splitport(host)
348 user, host = splituser(host)
349 if user: user, passwd = splitpasswd(user)
350 else: passwd = None
351 host = unquote(host)
352 user = unquote(user or '')
353 passwd = unquote(passwd or '')
354 host = socket.gethostbyname(host)
355 if not port:
356 import ftplib
357 port = ftplib.FTP_PORT
358 else:
359 port = int(port)
360 path, attrs = splitattr(path)
361 path = unquote(path)
362 dirs = string.splitfields(path, '/')
363 dirs, file = dirs[:-1], dirs[-1]
364 if dirs and not dirs[0]: dirs = dirs[1:]
Guido van Rossum5e006a31999-08-18 17:40:33 +0000365 if dirs and not dirs[0]: dirs[0] = '/'
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000366 key = (user, host, port, string.joinfields(dirs, '/'))
367 # XXX thread unsafe!
368 if len(self.ftpcache) > MAXFTPCACHE:
369 # Prune the cache, rather arbitrarily
370 for k in self.ftpcache.keys():
371 if k != key:
372 v = self.ftpcache[k]
373 del self.ftpcache[k]
374 v.close()
375 try:
376 if not self.ftpcache.has_key(key):
377 self.ftpcache[key] = \
378 ftpwrapper(user, passwd, host, port, dirs)
379 if not file: type = 'D'
380 else: type = 'I'
381 for attr in attrs:
382 attr, value = splitvalue(attr)
383 if string.lower(attr) == 'type' and \
384 value in ('a', 'A', 'i', 'I', 'd', 'D'):
385 type = string.upper(value)
386 (fp, retrlen) = self.ftpcache[key].retrfile(file, type)
387 if retrlen is not None and retrlen >= 0:
388 import mimetools, StringIO
389 headers = mimetools.Message(StringIO.StringIO(
390 'Content-Length: %d\n' % retrlen))
391 else:
392 headers = noheaders()
393 return addinfourl(fp, headers, "ftp:" + url)
394 except ftperrors(), msg:
395 raise IOError, ('ftp error', msg), sys.exc_info()[2]
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000396
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000397 # Use "data" URL
398 def open_data(self, url, data=None):
399 # ignore POSTed data
400 #
401 # syntax of data URLs:
402 # dataurl := "data:" [ mediatype ] [ ";base64" ] "," data
403 # mediatype := [ type "/" subtype ] *( ";" parameter )
404 # data := *urlchar
405 # parameter := attribute "=" value
406 import StringIO, mimetools, time
407 try:
408 [type, data] = string.split(url, ',', 1)
409 except ValueError:
410 raise IOError, ('data error', 'bad data URL')
411 if not type:
412 type = 'text/plain;charset=US-ASCII'
413 semi = string.rfind(type, ';')
414 if semi >= 0 and '=' not in type[semi:]:
415 encoding = type[semi+1:]
416 type = type[:semi]
417 else:
418 encoding = ''
419 msg = []
420 msg.append('Date: %s'%time.strftime('%a, %d %b %Y %T GMT',
421 time.gmtime(time.time())))
422 msg.append('Content-type: %s' % type)
423 if encoding == 'base64':
424 import base64
425 data = base64.decodestring(data)
426 else:
427 data = unquote(data)
428 msg.append('Content-length: %d' % len(data))
429 msg.append('')
430 msg.append(data)
431 msg = string.join(msg, '\n')
432 f = StringIO.StringIO(msg)
433 headers = mimetools.Message(f, 0)
434 f.fileno = None # needed for addinfourl
435 return addinfourl(f, headers, url)
Guido van Rossum6d4d1c21998-03-12 14:32:55 +0000436
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000437
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000438# Derived class with handlers for errors we can handle (perhaps)
439class FancyURLopener(URLopener):
440
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000441 def __init__(self, *args):
442 apply(URLopener.__init__, (self,) + args)
443 self.auth_cache = {}
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000444
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000445 # Default error handling -- don't raise an exception
446 def http_error_default(self, url, fp, errcode, errmsg, headers):
447 return addinfourl(fp, headers, "http:" + url)
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000448
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000449 # Error 302 -- relocated (temporarily)
450 def http_error_302(self, url, fp, errcode, errmsg, headers,
451 data=None):
452 # XXX The server can force infinite recursion here!
453 if headers.has_key('location'):
454 newurl = headers['location']
455 elif headers.has_key('uri'):
456 newurl = headers['uri']
457 else:
458 return
459 void = fp.read()
460 fp.close()
Guido van Rossum3527f591999-03-29 20:23:41 +0000461 # In case the server sent a relative URL, join with original:
462 newurl = basejoin("http:" + url, newurl)
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000463 return self.open(newurl, data)
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000464
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000465 # Error 301 -- also relocated (permanently)
466 http_error_301 = http_error_302
Guido van Rossume6ad8911996-09-10 17:02:56 +0000467
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000468 # Error 401 -- authentication required
469 # See this URL for a description of the basic authentication scheme:
470 # http://www.ics.uci.edu/pub/ietf/http/draft-ietf-http-v10-spec-00.txt
471 def http_error_401(self, url, fp, errcode, errmsg, headers,
472 data=None):
473 if headers.has_key('www-authenticate'):
474 stuff = headers['www-authenticate']
475 import re
476 match = re.match('[ \t]*([^ \t]+)[ \t]+realm="([^"]*)"', stuff)
477 if match:
478 scheme, realm = match.groups()
479 if string.lower(scheme) == 'basic':
480 return self.retry_http_basic_auth(url, realm, data)
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000481
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000482 def retry_http_basic_auth(self, url, realm, data):
483 host, selector = splithost(url)
484 i = string.find(host, '@') + 1
485 host = host[i:]
486 user, passwd = self.get_user_passwd(host, realm, i)
487 if not (user or passwd): return None
488 host = user + ':' + passwd + '@' + host
489 newurl = 'http://' + host + selector
490 return self.open(newurl, data)
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000491
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000492 def get_user_passwd(self, host, realm, clear_cache = 0):
493 key = realm + '@' + string.lower(host)
494 if self.auth_cache.has_key(key):
495 if clear_cache:
496 del self.auth_cache[key]
497 else:
498 return self.auth_cache[key]
499 user, passwd = self.prompt_user_passwd(host, realm)
500 if user or passwd: self.auth_cache[key] = (user, passwd)
501 return user, passwd
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000502
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000503 def prompt_user_passwd(self, host, realm):
504 # Override this in a GUI environment!
505 import getpass
506 try:
507 user = raw_input("Enter username for %s at %s: " % (realm,
508 host))
509 passwd = getpass.getpass("Enter password for %s in %s at %s: " %
510 (user, realm, host))
511 return user, passwd
512 except KeyboardInterrupt:
513 print
514 return None, None
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000515
516
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000517# Utility functions
518
519# Return the IP address of the magic hostname 'localhost'
520_localhost = None
521def localhost():
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000522 global _localhost
523 if not _localhost:
524 _localhost = socket.gethostbyname('localhost')
525 return _localhost
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000526
527# Return the IP address of the current host
528_thishost = None
529def thishost():
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000530 global _thishost
531 if not _thishost:
532 _thishost = socket.gethostbyname(socket.gethostname())
533 return _thishost
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000534
535# Return the set of errors raised by the FTP class
536_ftperrors = None
537def ftperrors():
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000538 global _ftperrors
539 if not _ftperrors:
540 import ftplib
541 _ftperrors = ftplib.all_errors
542 return _ftperrors
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000543
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000544# Return an empty mimetools.Message object
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000545_noheaders = None
546def noheaders():
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000547 global _noheaders
548 if not _noheaders:
549 import mimetools
550 import StringIO
551 _noheaders = mimetools.Message(StringIO.StringIO(), 0)
552 _noheaders.fp.close() # Recycle file descriptor
553 return _noheaders
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000554
555
556# Utility classes
557
558# Class used by open_ftp() for cache of open FTP connections
559class ftpwrapper:
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000560 def __init__(self, user, passwd, host, port, dirs):
561 self.user = user
562 self.passwd = passwd
563 self.host = host
564 self.port = port
565 self.dirs = dirs
566 self.init()
567 def init(self):
568 import ftplib
569 self.busy = 0
570 self.ftp = ftplib.FTP()
571 self.ftp.connect(self.host, self.port)
572 self.ftp.login(self.user, self.passwd)
573 for dir in self.dirs:
574 self.ftp.cwd(dir)
575 def retrfile(self, file, type):
576 import ftplib
577 self.endtransfer()
578 if type in ('d', 'D'): cmd = 'TYPE A'; isdir = 1
579 else: cmd = 'TYPE ' + type; isdir = 0
580 try:
581 self.ftp.voidcmd(cmd)
582 except ftplib.all_errors:
583 self.init()
584 self.ftp.voidcmd(cmd)
585 conn = None
586 if file and not isdir:
587 # Use nlst to see if the file exists at all
588 try:
589 self.ftp.nlst(file)
590 except ftplib.error_perm, reason:
591 raise IOError, ('ftp error', reason), sys.exc_info()[2]
592 # Restore the transfer mode!
593 self.ftp.voidcmd(cmd)
594 # Try to retrieve as a file
595 try:
596 cmd = 'RETR ' + file
597 conn = self.ftp.ntransfercmd(cmd)
598 except ftplib.error_perm, reason:
599 if reason[:3] != '550':
600 raise IOError, ('ftp error', reason), sys.exc_info()[2]
601 if not conn:
602 # Set transfer mode to ASCII!
603 self.ftp.voidcmd('TYPE A')
604 # Try a directory listing
605 if file: cmd = 'LIST ' + file
606 else: cmd = 'LIST'
607 conn = self.ftp.ntransfercmd(cmd)
608 self.busy = 1
609 # Pass back both a suitably decorated object and a retrieval length
610 return (addclosehook(conn[0].makefile('rb'),
611 self.endtransfer), conn[1])
612 def endtransfer(self):
613 if not self.busy:
614 return
615 self.busy = 0
616 try:
617 self.ftp.voidresp()
618 except ftperrors():
619 pass
620 def close(self):
621 self.endtransfer()
622 try:
623 self.ftp.close()
624 except ftperrors():
625 pass
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000626
627# Base class for addinfo and addclosehook
628class addbase:
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000629 def __init__(self, fp):
630 self.fp = fp
631 self.read = self.fp.read
632 self.readline = self.fp.readline
633 self.readlines = self.fp.readlines
634 self.fileno = self.fp.fileno
635 def __repr__(self):
636 return '<%s at %s whose fp = %s>' % (self.__class__.__name__,
637 `id(self)`, `self.fp`)
638 def close(self):
639 self.read = None
640 self.readline = None
641 self.readlines = None
642 self.fileno = None
643 if self.fp: self.fp.close()
644 self.fp = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000645
646# Class to add a close hook to an open file
647class addclosehook(addbase):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000648 def __init__(self, fp, closehook, *hookargs):
649 addbase.__init__(self, fp)
650 self.closehook = closehook
651 self.hookargs = hookargs
652 def close(self):
653 if self.closehook:
654 apply(self.closehook, self.hookargs)
655 self.closehook = None
656 self.hookargs = None
657 addbase.close(self)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000658
659# class to add an info() method to an open file
660class addinfo(addbase):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000661 def __init__(self, fp, headers):
662 addbase.__init__(self, fp)
663 self.headers = headers
664 def info(self):
665 return self.headers
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000666
Guido van Rossume6ad8911996-09-10 17:02:56 +0000667# class to add info() and geturl() methods to an open file
668class addinfourl(addbase):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000669 def __init__(self, fp, headers, url):
670 addbase.__init__(self, fp)
671 self.headers = headers
672 self.url = url
673 def info(self):
674 return self.headers
675 def geturl(self):
676 return self.url
Guido van Rossume6ad8911996-09-10 17:02:56 +0000677
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000678
679# Utility to combine a URL with a base URL to form a new URL
680
681def basejoin(base, url):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000682 type, path = splittype(url)
683 if type:
684 # if url is complete (i.e., it contains a type), return it
685 return url
686 host, path = splithost(path)
687 type, basepath = splittype(base) # inherit type from base
688 if host:
689 # if url contains host, just inherit type
690 if type: return type + '://' + host + path
691 else:
692 # no type inherited, so url must have started with //
693 # just return it
694 return url
695 host, basepath = splithost(basepath) # inherit host
696 basepath, basetag = splittag(basepath) # remove extraneuous cruft
697 basepath, basequery = splitquery(basepath) # idem
698 if path[:1] != '/':
699 # non-absolute path name
700 if path[:1] in ('#', '?'):
701 # path is just a tag or query, attach to basepath
702 i = len(basepath)
703 else:
704 # else replace last component
705 i = string.rfind(basepath, '/')
706 if i < 0:
707 # basepath not absolute
708 if host:
709 # host present, make absolute
710 basepath = '/'
711 else:
712 # else keep non-absolute
713 basepath = ''
714 else:
715 # remove last file component
716 basepath = basepath[:i+1]
717 # Interpret ../ (important because of symlinks)
718 while basepath and path[:3] == '../':
719 path = path[3:]
720 i = string.rfind(basepath[:-1], '/')
721 if i > 0:
722 basepath = basepath[:i+1]
723 elif i == 0:
724 basepath = '/'
725 break
726 else:
727 basepath = ''
728
729 path = basepath + path
730 if type and host: return type + '://' + host + path
731 elif type: return type + ':' + path
732 elif host: return '//' + host + path # don't know what this means
733 else: return path
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000734
735
Guido van Rossum7c395db1994-07-04 22:14:49 +0000736# Utilities to parse URLs (most of these return None for missing parts):
Sjoerd Mullendere0371b81995-11-10 10:36:07 +0000737# unwrap('<URL:type://host/path>') --> 'type://host/path'
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000738# splittype('type:opaquestring') --> 'type', 'opaquestring'
739# splithost('//host[:port]/path') --> 'host[:port]', '/path'
Guido van Rossum7c395db1994-07-04 22:14:49 +0000740# splituser('user[:passwd]@host[:port]') --> 'user[:passwd]', 'host[:port]'
741# splitpasswd('user:passwd') -> 'user', 'passwd'
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000742# splitport('host:port') --> 'host', 'port'
743# splitquery('/path?query') --> '/path', 'query'
744# splittag('/path#tag') --> '/path', 'tag'
Guido van Rossum7c395db1994-07-04 22:14:49 +0000745# splitattr('/path;attr1=value1;attr2=value2;...') ->
746# '/path', ['attr1=value1', 'attr2=value2', ...]
747# splitvalue('attr=value') --> 'attr', 'value'
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000748# splitgophertype('/Xselector') --> 'X', 'selector'
749# unquote('abc%20def') -> 'abc def'
750# quote('abc def') -> 'abc%20def')
751
752def unwrap(url):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000753 url = string.strip(url)
754 if url[:1] == '<' and url[-1:] == '>':
755 url = string.strip(url[1:-1])
756 if url[:4] == 'URL:': url = string.strip(url[4:])
757 return url
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000758
Guido van Rossum332e1441997-09-29 23:23:46 +0000759_typeprog = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000760def splittype(url):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000761 global _typeprog
762 if _typeprog is None:
763 import re
764 _typeprog = re.compile('^([^/:]+):')
Guido van Rossum332e1441997-09-29 23:23:46 +0000765
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000766 match = _typeprog.match(url)
767 if match:
768 scheme = match.group(1)
769 return scheme, url[len(scheme) + 1:]
770 return None, url
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000771
Guido van Rossum332e1441997-09-29 23:23:46 +0000772_hostprog = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000773def splithost(url):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000774 global _hostprog
775 if _hostprog is None:
776 import re
Guido van Rossum3427c1f1999-07-01 23:20:56 +0000777 _hostprog = re.compile('^//([^/]*)(.*)$')
Guido van Rossum332e1441997-09-29 23:23:46 +0000778
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000779 match = _hostprog.match(url)
780 if match: return match.group(1, 2)
781 return None, url
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000782
Guido van Rossum332e1441997-09-29 23:23:46 +0000783_userprog = None
Guido van Rossum7c395db1994-07-04 22:14:49 +0000784def splituser(host):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000785 global _userprog
786 if _userprog is None:
787 import re
788 _userprog = re.compile('^([^@]*)@(.*)$')
Guido van Rossum332e1441997-09-29 23:23:46 +0000789
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000790 match = _userprog.match(host)
791 if match: return match.group(1, 2)
792 return None, host
Guido van Rossum7c395db1994-07-04 22:14:49 +0000793
Guido van Rossum332e1441997-09-29 23:23:46 +0000794_passwdprog = None
Guido van Rossum7c395db1994-07-04 22:14:49 +0000795def splitpasswd(user):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000796 global _passwdprog
797 if _passwdprog is None:
798 import re
799 _passwdprog = re.compile('^([^:]*):(.*)$')
Guido van Rossum332e1441997-09-29 23:23:46 +0000800
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000801 match = _passwdprog.match(user)
802 if match: return match.group(1, 2)
803 return user, None
Guido van Rossum7c395db1994-07-04 22:14:49 +0000804
Guido van Rossum332e1441997-09-29 23:23:46 +0000805_portprog = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000806def splitport(host):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000807 global _portprog
808 if _portprog is None:
809 import re
810 _portprog = re.compile('^(.*):([0-9]+)$')
Guido van Rossum332e1441997-09-29 23:23:46 +0000811
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000812 match = _portprog.match(host)
813 if match: return match.group(1, 2)
814 return host, None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000815
Guido van Rossum53725a21996-06-13 19:12:35 +0000816# Split host and port, returning numeric port.
817# Return given default port if no ':' found; defaults to -1.
Guido van Rossum84a00a81996-06-17 17:11:40 +0000818# Return numerical port if a valid number are found after ':'.
819# Return None if ':' but not a valid number.
Guido van Rossum332e1441997-09-29 23:23:46 +0000820_nportprog = None
Guido van Rossum53725a21996-06-13 19:12:35 +0000821def splitnport(host, defport=-1):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000822 global _nportprog
823 if _nportprog is None:
824 import re
825 _nportprog = re.compile('^(.*):(.*)$')
Guido van Rossum7e7ca0b1998-03-26 21:01:39 +0000826
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000827 match = _nportprog.match(host)
828 if match:
829 host, port = match.group(1, 2)
830 try:
831 if not port: raise string.atoi_error, "no digits"
832 nport = string.atoi(port)
833 except string.atoi_error:
834 nport = None
835 return host, nport
836 return host, defport
Guido van Rossum53725a21996-06-13 19:12:35 +0000837
Guido van Rossum332e1441997-09-29 23:23:46 +0000838_queryprog = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000839def splitquery(url):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000840 global _queryprog
841 if _queryprog is None:
842 import re
843 _queryprog = re.compile('^(.*)\?([^?]*)$')
Guido van Rossum332e1441997-09-29 23:23:46 +0000844
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000845 match = _queryprog.match(url)
846 if match: return match.group(1, 2)
847 return url, None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000848
Guido van Rossum332e1441997-09-29 23:23:46 +0000849_tagprog = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000850def splittag(url):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000851 global _tagprog
852 if _tagprog is None:
853 import re
854 _tagprog = re.compile('^(.*)#([^#]*)$')
Guido van Rossum7e7ca0b1998-03-26 21:01:39 +0000855
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000856 match = _tagprog.match(url)
857 if match: return match.group(1, 2)
858 return url, None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000859
Guido van Rossum7c395db1994-07-04 22:14:49 +0000860def splitattr(url):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000861 words = string.splitfields(url, ';')
862 return words[0], words[1:]
Guido van Rossum7c395db1994-07-04 22:14:49 +0000863
Guido van Rossum332e1441997-09-29 23:23:46 +0000864_valueprog = None
Guido van Rossum7c395db1994-07-04 22:14:49 +0000865def splitvalue(attr):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000866 global _valueprog
867 if _valueprog is None:
868 import re
869 _valueprog = re.compile('^([^=]*)=(.*)$')
Guido van Rossum332e1441997-09-29 23:23:46 +0000870
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000871 match = _valueprog.match(attr)
872 if match: return match.group(1, 2)
873 return attr, None
Guido van Rossum7c395db1994-07-04 22:14:49 +0000874
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000875def splitgophertype(selector):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000876 if selector[:1] == '/' and selector[1:2]:
877 return selector[1], selector[2:]
878 return None, selector
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000879
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000880def unquote(s):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000881 mychr = chr
882 myatoi = string.atoi
883 list = string.split(s, '%')
884 res = [list[0]]
885 myappend = res.append
886 del list[0]
887 for item in list:
888 if item[1:2]:
889 try:
890 myappend(mychr(myatoi(item[:2], 16))
891 + item[2:])
892 except:
893 myappend('%' + item)
894 else:
895 myappend('%' + item)
896 return string.join(res, "")
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000897
Guido van Rossum0564e121996-12-13 14:47:36 +0000898def unquote_plus(s):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000899 if '+' in s:
900 # replace '+' with ' '
901 s = string.join(string.split(s, '+'), ' ')
902 return unquote(s)
Guido van Rossum0564e121996-12-13 14:47:36 +0000903
Guido van Rossum3bb54481994-08-29 10:52:58 +0000904always_safe = string.letters + string.digits + '_,.-'
Guido van Rossum7c395db1994-07-04 22:14:49 +0000905def quote(s, safe = '/'):
Guido van Rossum0dee4ee1999-06-09 15:14:50 +0000906 # XXX Can speed this up an order of magnitude
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000907 safe = always_safe + safe
908 res = list(s)
909 for i in range(len(res)):
910 c = res[i]
911 if c not in safe:
912 res[i] = '%%%02x' % ord(c)
913 return string.joinfields(res, '')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000914
Guido van Rossum0564e121996-12-13 14:47:36 +0000915def quote_plus(s, safe = '/'):
Guido van Rossum0dee4ee1999-06-09 15:14:50 +0000916 # XXX Can speed this up an order of magnitude
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000917 if ' ' in s:
918 # replace ' ' with '+'
919 l = string.split(s, ' ')
920 for i in range(len(l)):
921 l[i] = quote(l[i], safe)
922 return string.join(l, '+')
923 else:
924 return quote(s, safe)
Guido van Rossum0564e121996-12-13 14:47:36 +0000925
Guido van Rossum810a3391998-07-22 21:33:23 +0000926def urlencode(dict):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000927 l = []
928 for k, v in dict.items():
929 k = quote_plus(str(k))
930 v = quote_plus(str(v))
931 l.append(k + '=' + v)
932 return string.join(l, '&')
Guido van Rossum810a3391998-07-22 21:33:23 +0000933
Guido van Rossum442e7201996-03-20 15:33:11 +0000934
935# Proxy handling
Guido van Rossum4163e701998-08-06 13:39:09 +0000936if os.name == 'mac':
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000937 def getproxies():
938 """Return a dictionary of scheme -> proxy server URL mappings.
Guido van Rossum442e7201996-03-20 15:33:11 +0000939
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000940 By convention the mac uses Internet Config to store
941 proxies. An HTTP proxy, for instance, is stored under
942 the HttpProxy key.
Guido van Rossum442e7201996-03-20 15:33:11 +0000943
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000944 """
945 try:
946 import ic
947 except ImportError:
948 return {}
949
950 try:
951 config = ic.IC()
952 except ic.error:
953 return {}
954 proxies = {}
955 # HTTP:
956 if config.has_key('UseHTTPProxy') and config['UseHTTPProxy']:
957 try:
958 value = config['HTTPProxyHost']
959 except ic.error:
960 pass
961 else:
962 proxies['http'] = 'http://%s' % value
963 # FTP: XXXX To be done.
964 # Gopher: XXXX To be done.
965 return proxies
966
Guido van Rossum4163e701998-08-06 13:39:09 +0000967else:
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000968 def getproxies():
969 """Return a dictionary of scheme -> proxy server URL mappings.
970
971 Scan the environment for variables named <scheme>_proxy;
972 this seems to be the standard convention. If you need a
973 different way, you can pass a proxies dictionary to the
974 [Fancy]URLopener constructor.
975
976 """
977 proxies = {}
978 for name, value in os.environ.items():
979 name = string.lower(name)
980 if value and name[-6:] == '_proxy':
981 proxies[name[:-6]] = value
982 return proxies
Guido van Rossum442e7201996-03-20 15:33:11 +0000983
984
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000985# Test and time quote() and unquote()
986def test1():
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000987 import time
988 s = ''
989 for i in range(256): s = s + chr(i)
990 s = s*4
991 t0 = time.time()
992 qs = quote(s)
993 uqs = unquote(qs)
994 t1 = time.time()
995 if uqs != s:
996 print 'Wrong!'
997 print `s`
998 print `qs`
999 print `uqs`
1000 print round(t1 - t0, 3), 'sec'
Guido van Rossum7c6ebb51994-03-22 12:05:32 +00001001
1002
Guido van Rossum9ab96d41998-09-28 14:07:00 +00001003def reporthook(blocknum, blocksize, totalsize):
1004 # Report during remote transfers
1005 print "Block number: %d, Block size: %d, Total size: %d" % (blocknum, blocksize, totalsize)
1006
Guido van Rossum7c6ebb51994-03-22 12:05:32 +00001007# Test program
Guido van Rossum23490151998-06-25 02:39:00 +00001008def test(args=[]):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001009 if not args:
1010 args = [
1011 '/etc/passwd',
1012 'file:/etc/passwd',
1013 'file://localhost/etc/passwd',
1014 'ftp://ftp.python.org/etc/passwd',
1015## 'gopher://gopher.micro.umn.edu/1/',
1016 'http://www.python.org/index.html',
1017 ]
1018 try:
1019 for url in args:
1020 print '-'*10, url, '-'*10
1021 fn, h = urlretrieve(url, None, reporthook)
1022 print fn, h
1023 if h:
1024 print '======'
1025 for k in h.keys(): print k + ':', h[k]
1026 print '======'
1027 fp = open(fn, 'rb')
1028 data = fp.read()
1029 del fp
1030 if '\r' in data:
1031 table = string.maketrans("", "")
1032 data = string.translate(data, table, "\r")
1033 print data
1034 fn, h = None, None
1035 print '-'*40
1036 finally:
1037 urlcleanup()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +00001038
Guido van Rossum23490151998-06-25 02:39:00 +00001039def main():
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001040 import getopt, sys
1041 try:
1042 opts, args = getopt.getopt(sys.argv[1:], "th")
1043 except getopt.error, msg:
1044 print msg
1045 print "Use -h for help"
1046 return
1047 t = 0
1048 for o, a in opts:
1049 if o == '-t':
1050 t = t + 1
1051 if o == '-h':
1052 print "Usage: python urllib.py [-t] [url ...]"
1053 print "-t runs self-test;",
1054 print "otherwise, contents of urls are printed"
1055 return
1056 if t:
1057 if t > 1:
1058 test1()
1059 test(args)
1060 else:
1061 if not args:
1062 print "Use -h for help"
1063 for url in args:
1064 print urlopen(url).read(),
Guido van Rossum23490151998-06-25 02:39:00 +00001065
Guido van Rossum7c6ebb51994-03-22 12:05:32 +00001066# Run test program when run as a script
1067if __name__ == '__main__':
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001068 main()