blob: 79ee82be4b32b1c5fc893bdfe73f1593cc68ecc9 [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 Rossum8a666e71998-02-13 01:39:16 +000030__version__ = '1.10'
Guido van Rossumf668d171997-06-06 21:11:11 +000031
32MAXFTPCACHE = 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':
Guido van Rossum71ac9451996-03-21 16:31:41 +000036 from macurl2path import url2pathname, pathname2url
Guido van Rossum2281d351996-06-26 19:47:37 +000037elif os.name == 'nt':
38 from nturl2path import url2pathname, pathname2url
Jack Jansendc3e3f61995-12-15 13:22:13 +000039else:
Jack Jansene8ea21b1995-12-21 15:43:53 +000040 def url2pathname(pathname):
Jack Jansendc3e3f61995-12-15 13:22:13 +000041 return pathname
Jack Jansene8ea21b1995-12-21 15:43:53 +000042 def pathname2url(pathname):
43 return pathname
Guido van Rossum6cb15a01995-06-22 19:00:13 +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):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000055 global _urlopener
56 if not _urlopener:
Guido van Rossumbbb0a051995-08-04 04:29:05 +000057 _urlopener = FancyURLopener()
Guido van Rossumbd013741996-12-10 16:00:28 +000058 if data is None:
59 return _urlopener.open(url)
60 else:
61 return _urlopener.open(url, data)
Guido van Rossuma7e4b281996-06-11 00:16:27 +000062def urlretrieve(url, filename=None):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000063 global _urlopener
64 if not _urlopener:
Guido van Rossumbbb0a051995-08-04 04:29:05 +000065 _urlopener = FancyURLopener()
Guido van Rossuma7e4b281996-06-11 00:16:27 +000066 if filename:
67 return _urlopener.retrieve(url, filename)
68 else:
69 return _urlopener.retrieve(url)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000070def urlcleanup():
71 if _urlopener:
72 _urlopener.cleanup()
73
74
75# Class to open URLs.
76# This is a class rather than just a subroutine because we may need
77# more than one set of global protocol-specific options.
Guido van Rossumbbb0a051995-08-04 04:29:05 +000078# Note -- this is a base class for those who don't want the
79# automatic handling of errors type 302 (relocated) and 401
80# (authorization needed).
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000081ftpcache = {}
82class URLopener:
83
Guido van Rossum036309b1997-10-27 18:56:19 +000084 __tempfiles = None
Guido van Rossum29e77811996-11-27 19:39:58 +000085
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000086 # Constructor
Guido van Rossum442e7201996-03-20 15:33:11 +000087 def __init__(self, proxies=None):
88 if proxies is None:
89 proxies = getproxies()
Guido van Rossum83600051997-11-18 15:50:39 +000090 assert hasattr(proxies, 'has_key'), "proxies must be a mapping"
Guido van Rossum442e7201996-03-20 15:33:11 +000091 self.proxies = proxies
Guido van Rossum6cb15a01995-06-22 19:00:13 +000092 server_version = "Python-urllib/%s" % __version__
93 self.addheaders = [('User-agent', server_version)]
Guido van Rossum10499321997-09-08 02:16:33 +000094 self.__tempfiles = []
Guido van Rossum036309b1997-10-27 18:56:19 +000095 self.__unlink = os.unlink # See cleanup()
Guido van Rossum7aeb4b91994-08-23 13:32:20 +000096 self.tempcache = None
97 # Undocumented feature: if you assign {} to tempcache,
98 # it is used to cache files retrieved with
99 # self.retrieve(). This is not enabled by default
100 # since it does not work for changing documents (and I
101 # haven't got the logic to check expiration headers
102 # yet).
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000103 self.ftpcache = ftpcache
104 # Undocumented feature: you can use a different
105 # ftp cache by assigning to the .ftpcache member;
106 # in case you want logically independent URL openers
107
108 def __del__(self):
109 self.close()
110
111 def close(self):
112 self.cleanup()
113
114 def cleanup(self):
Guido van Rossum036309b1997-10-27 18:56:19 +0000115 # This code sometimes runs when the rest of this module
116 # has already been deleted, so it can't use any globals
117 # or import anything.
Guido van Rossum2b3fd761997-09-03 22:36:15 +0000118 if self.__tempfiles:
Guido van Rossum2b3fd761997-09-03 22:36:15 +0000119 for file in self.__tempfiles:
Guido van Rossum7aeb4b91994-08-23 13:32:20 +0000120 try:
Guido van Rossum036309b1997-10-27 18:56:19 +0000121 self.__unlink(file)
122 except:
Guido van Rossum7aeb4b91994-08-23 13:32:20 +0000123 pass
Guido van Rossum036309b1997-10-27 18:56:19 +0000124 del self.__tempfiles[:]
125 if self.tempcache:
126 self.tempcache.clear()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000127
128 # Add a header to be used by the HTTP interface only
129 # e.g. u.addheader('Accept', 'sound/basic')
130 def addheader(self, *args):
131 self.addheaders.append(args)
132
133 # External interface
134 # Use URLopener().open(file) instead of open(file, 'r')
Guido van Rossumbd013741996-12-10 16:00:28 +0000135 def open(self, fullurl, data=None):
Guido van Rossumca445401995-08-29 19:19:12 +0000136 fullurl = unwrap(fullurl)
Guido van Rossum03710d21998-02-05 16:22:27 +0000137 if self.tempcache and self.tempcache.has_key(fullurl):
138 filename, headers = self.tempcache[fullurl]
139 fp = open(filename, 'rb')
140 return addinfourl(fp, headers, fullurl)
Guido van Rossumca445401995-08-29 19:19:12 +0000141 type, url = splittype(fullurl)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000142 if not type: type = 'file'
Guido van Rossum442e7201996-03-20 15:33:11 +0000143 if self.proxies.has_key(type):
144 proxy = self.proxies[type]
145 type, proxy = splittype(proxy)
146 host, selector = splithost(proxy)
147 url = (host, fullurl) # Signal special case to open_*()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000148 name = 'open_' + type
149 if '-' in name:
Guido van Rossum332e1441997-09-29 23:23:46 +0000150 # replace - with _
151 name = string.join(string.split(name, '-'), '_')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000152 if not hasattr(self, name):
Guido van Rossumbd013741996-12-10 16:00:28 +0000153 if data is None:
154 return self.open_unknown(fullurl)
155 else:
156 return self.open_unknown(fullurl, data)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000157 try:
Guido van Rossumbd013741996-12-10 16:00:28 +0000158 if data is None:
159 return getattr(self, name)(url)
160 else:
161 return getattr(self, name)(url, data)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000162 except socket.error, msg:
Guido van Rossum332e1441997-09-29 23:23:46 +0000163 raise IOError, ('socket error', msg), sys.exc_info()[2]
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000164
Guido van Rossumca445401995-08-29 19:19:12 +0000165 # Overridable interface to open unknown URL type
Guido van Rossumbd013741996-12-10 16:00:28 +0000166 def open_unknown(self, fullurl, data=None):
Guido van Rossumca445401995-08-29 19:19:12 +0000167 type, url = splittype(fullurl)
168 raise IOError, ('url error', 'unknown url type', type)
169
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000170 # External interface
171 # retrieve(url) returns (filename, None) for a local object
172 # or (tempfilename, headers) for a remote object
Guido van Rossuma7e4b281996-06-11 00:16:27 +0000173 def retrieve(self, url, filename=None):
Guido van Rossum03710d21998-02-05 16:22:27 +0000174 url = unwrap(url)
Guido van Rossum7aeb4b91994-08-23 13:32:20 +0000175 if self.tempcache and self.tempcache.has_key(url):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000176 return self.tempcache[url]
Guido van Rossum03710d21998-02-05 16:22:27 +0000177 type, url1 = splittype(url)
Guido van Rossuma7e4b281996-06-11 00:16:27 +0000178 if not filename and (not type or type == 'file'):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000179 try:
180 fp = self.open_local_file(url1)
181 del fp
Jack Jansene8ea21b1995-12-21 15:43:53 +0000182 return url2pathname(splithost(url1)[1]), None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000183 except IOError, msg:
184 pass
185 fp = self.open(url)
186 headers = fp.info()
Guido van Rossuma7e4b281996-06-11 00:16:27 +0000187 if not filename:
188 import tempfile
189 filename = tempfile.mktemp()
Guido van Rossum2b3fd761997-09-03 22:36:15 +0000190 self.__tempfiles.append(filename)
Guido van Rossuma7e4b281996-06-11 00:16:27 +0000191 result = filename, headers
Guido van Rossum7aeb4b91994-08-23 13:32:20 +0000192 if self.tempcache is not None:
Guido van Rossumfa59e831994-09-21 11:36:19 +0000193 self.tempcache[url] = result
Guido van Rossumc511aee1997-04-11 19:01:48 +0000194 tfp = open(filename, 'wb')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000195 bs = 1024*8
196 block = fp.read(bs)
197 while block:
198 tfp.write(block)
199 block = fp.read(bs)
Guido van Rossumab0abdc1997-08-26 19:06:40 +0000200 fp.close()
201 tfp.close()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000202 del fp
203 del tfp
204 return result
205
206 # Each method named open_<type> knows how to open that type of URL
207
208 # Use HTTP protocol
Guido van Rossumbd013741996-12-10 16:00:28 +0000209 def open_http(self, url, data=None):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000210 import httplib
Guido van Rossum442e7201996-03-20 15:33:11 +0000211 if type(url) is type(""):
212 host, selector = splithost(url)
Guido van Rossum78c96371996-08-26 18:09:59 +0000213 user_passwd, host = splituser(host)
Guido van Rossumc24751b1997-06-03 14:34:19 +0000214 realhost = host
Guido van Rossum442e7201996-03-20 15:33:11 +0000215 else:
216 host, selector = url
Guido van Rossum78c96371996-08-26 18:09:59 +0000217 urltype, rest = splittype(selector)
Guido van Rossumfd795661997-04-02 05:46:35 +0000218 user_passwd = None
Guido van Rossumc24751b1997-06-03 14:34:19 +0000219 if string.lower(urltype) != 'http':
220 realhost = None
221 else:
Guido van Rossum78c96371996-08-26 18:09:59 +0000222 realhost, rest = splithost(rest)
223 user_passwd, realhost = splituser(realhost)
224 if user_passwd:
225 selector = "%s://%s%s" % (urltype,
226 realhost, rest)
Guido van Rossumfd795661997-04-02 05:46:35 +0000227 #print "proxy via http:", host, selector
Guido van Rossum590b2891994-04-18 09:39:56 +0000228 if not host: raise IOError, ('http error', 'no host given')
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000229 if user_passwd:
230 import base64
231 auth = string.strip(base64.encodestring(user_passwd))
232 else:
233 auth = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000234 h = httplib.HTTP(host)
Guido van Rossumbd013741996-12-10 16:00:28 +0000235 if data is not None:
236 h.putrequest('POST', selector)
237 h.putheader('Content-type',
238 'application/x-www-form-urlencoded')
239 h.putheader('Content-length', '%d' % len(data))
240 else:
241 h.putrequest('GET', selector)
Guido van Rossumc5d7e801996-11-11 19:01:17 +0000242 if auth: h.putheader('Authorization', 'Basic %s' % auth)
Guido van Rossumc24751b1997-06-03 14:34:19 +0000243 if realhost: h.putheader('Host', realhost)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000244 for args in self.addheaders: apply(h.putheader, args)
Guido van Rossum6cb15a01995-06-22 19:00:13 +0000245 h.endheaders()
Guido van Rossumbd013741996-12-10 16:00:28 +0000246 if data is not None:
247 h.send(data + '\r\n')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000248 errcode, errmsg, headers = h.getreply()
Guido van Rossum6cb15a01995-06-22 19:00:13 +0000249 fp = h.getfile()
250 if errcode == 200:
Guido van Rossum8a666e71998-02-13 01:39:16 +0000251 return addinfourl(fp, headers, "http:" + url)
Guido van Rossum6cb15a01995-06-22 19:00:13 +0000252 else:
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000253 return self.http_error(url,
254 fp, errcode, errmsg, headers)
255
256 # Handle http errors.
257 # Derived class can override this, or provide specific handlers
258 # named http_error_DDD where DDD is the 3-digit error code
259 def http_error(self, url, fp, errcode, errmsg, headers):
260 # First check if there's a specific handler for this error
261 name = 'http_error_%d' % errcode
262 if hasattr(self, name):
263 method = getattr(self, name)
264 result = method(url, fp, errcode, errmsg, headers)
265 if result: return result
266 return self.http_error_default(
267 url, fp, errcode, errmsg, headers)
268
269 # Default http error handler: close the connection and raises IOError
270 def http_error_default(self, url, fp, errcode, errmsg, headers):
271 void = fp.read()
272 fp.close()
273 raise IOError, ('http error', errcode, errmsg, headers)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000274
275 # Use Gopher protocol
276 def open_gopher(self, url):
277 import gopherlib
278 host, selector = splithost(url)
Guido van Rossum590b2891994-04-18 09:39:56 +0000279 if not host: raise IOError, ('gopher error', 'no host given')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000280 type, selector = splitgophertype(selector)
281 selector, query = splitquery(selector)
Guido van Rossum7c395db1994-07-04 22:14:49 +0000282 selector = unquote(selector)
283 if query:
284 query = unquote(query)
285 fp = gopherlib.send_query(selector, query, host)
286 else:
287 fp = gopherlib.send_selector(selector, host)
Guido van Rossum8a666e71998-02-13 01:39:16 +0000288 return addinfourl(fp, noheaders(), "gopher:" + url)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000289
290 # Use local file or FTP depending on form of URL
291 def open_file(self, url):
Guido van Rossumb6784dc1997-08-20 23:34:01 +0000292 if url[:2] == '//' and url[2:3] != '/':
293 return self.open_ftp(url)
294 else:
295 return self.open_local_file(url)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000296
297 # Use local file
298 def open_local_file(self, url):
299 host, file = splithost(url)
Guido van Rossumb030bc01996-10-10 16:01:16 +0000300 if not host:
Guido van Rossum2966b321997-06-06 17:44:07 +0000301 return addinfourl(
302 open(url2pathname(file), 'rb'),
303 noheaders(), 'file:'+file)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000304 host, port = splitport(host)
305 if not port and socket.gethostbyname(host) in (
306 localhost(), thishost()):
Guido van Rossum7c395db1994-07-04 22:14:49 +0000307 file = unquote(file)
Guido van Rossum2966b321997-06-06 17:44:07 +0000308 return addinfourl(
309 open(url2pathname(file), 'rb'),
310 noheaders(), 'file:'+file)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000311 raise IOError, ('local file error', 'not on local host')
312
313 # Use FTP protocol
314 def open_ftp(self, url):
Guido van Rossum7c395db1994-07-04 22:14:49 +0000315 host, path = splithost(url)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000316 if not host: raise IOError, ('ftp error', 'no host given')
317 host, port = splitport(host)
Guido van Rossum7c395db1994-07-04 22:14:49 +0000318 user, host = splituser(host)
319 if user: user, passwd = splitpasswd(user)
320 else: passwd = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000321 host = socket.gethostbyname(host)
322 if not port:
323 import ftplib
324 port = ftplib.FTP_PORT
Guido van Rossumc0f29c21997-12-02 20:26:21 +0000325 else:
326 port = int(port)
Guido van Rossum7c395db1994-07-04 22:14:49 +0000327 path, attrs = splitattr(path)
328 dirs = string.splitfields(path, '/')
329 dirs, file = dirs[:-1], dirs[-1]
330 if dirs and not dirs[0]: dirs = dirs[1:]
331 key = (user, host, port, string.joinfields(dirs, '/'))
Guido van Rossumf668d171997-06-06 21:11:11 +0000332 if len(self.ftpcache) > MAXFTPCACHE:
333 # Prune the cache, rather arbitrarily
334 for k in self.ftpcache.keys():
335 if k != key:
336 v = self.ftpcache[k]
337 del self.ftpcache[k]
338 v.close()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000339 try:
340 if not self.ftpcache.has_key(key):
Guido van Rossum7c395db1994-07-04 22:14:49 +0000341 self.ftpcache[key] = \
Guido van Rossum8a666e71998-02-13 01:39:16 +0000342 ftpwrapper(user, passwd,
343 host, port, dirs)
Guido van Rossum7c395db1994-07-04 22:14:49 +0000344 if not file: type = 'D'
345 else: type = 'I'
346 for attr in attrs:
347 attr, value = splitvalue(attr)
348 if string.lower(attr) == 'type' and \
349 value in ('a', 'A', 'i', 'I', 'd', 'D'):
350 type = string.upper(value)
Guido van Rossum2966b321997-06-06 17:44:07 +0000351 return addinfourl(
352 self.ftpcache[key].retrfile(file, type),
Guido van Rossum8a666e71998-02-13 01:39:16 +0000353 noheaders(), "ftp:" + url)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000354 except ftperrors(), msg:
Guido van Rossum332e1441997-09-29 23:23:46 +0000355 raise IOError, ('ftp error', msg), sys.exc_info()[2]
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000356
357
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000358# Derived class with handlers for errors we can handle (perhaps)
359class FancyURLopener(URLopener):
360
361 def __init__(self, *args):
362 apply(URLopener.__init__, (self,) + args)
363 self.auth_cache = {}
364
365 # Default error handling -- don't raise an exception
366 def http_error_default(self, url, fp, errcode, errmsg, headers):
Guido van Rossum8a666e71998-02-13 01:39:16 +0000367 return addinfourl(fp, headers, "http:" + url)
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000368
Guido van Rossume6ad8911996-09-10 17:02:56 +0000369 # Error 302 -- relocated (temporarily)
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000370 def http_error_302(self, url, fp, errcode, errmsg, headers):
371 # XXX The server can force infinite recursion here!
372 if headers.has_key('location'):
373 newurl = headers['location']
374 elif headers.has_key('uri'):
375 newurl = headers['uri']
376 else:
377 return
378 void = fp.read()
379 fp.close()
380 return self.open(newurl)
381
Guido van Rossume6ad8911996-09-10 17:02:56 +0000382 # Error 301 -- also relocated (permanently)
383 http_error_301 = http_error_302
384
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000385 # Error 401 -- authentication required
386 # See this URL for a description of the basic authentication scheme:
387 # http://www.ics.uci.edu/pub/ietf/http/draft-ietf-http-v10-spec-00.txt
388 def http_error_401(self, url, fp, errcode, errmsg, headers):
389 if headers.has_key('www-authenticate'):
390 stuff = headers['www-authenticate']
Guido van Rossum332e1441997-09-29 23:23:46 +0000391 import re
392 match = re.match(
393 '[ \t]*([^ \t]+)[ \t]+realm="([^"]*)"', stuff)
394 if match:
Guido van Rossumc5d8fed1998-02-05 16:21:28 +0000395 scheme, realm = match.groups()
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000396 if string.lower(scheme) == 'basic':
397 return self.retry_http_basic_auth(
398 url, realm)
399
400 def retry_http_basic_auth(self, url, realm):
401 host, selector = splithost(url)
402 i = string.find(host, '@') + 1
403 host = host[i:]
404 user, passwd = self.get_user_passwd(host, realm, i)
405 if not (user or passwd): return None
406 host = user + ':' + passwd + '@' + host
407 newurl = '//' + host + selector
408 return self.open_http(newurl)
409
410 def get_user_passwd(self, host, realm, clear_cache = 0):
411 key = realm + '@' + string.lower(host)
412 if self.auth_cache.has_key(key):
413 if clear_cache:
414 del self.auth_cache[key]
415 else:
416 return self.auth_cache[key]
417 user, passwd = self.prompt_user_passwd(host, realm)
418 if user or passwd: self.auth_cache[key] = (user, passwd)
419 return user, passwd
420
421 def prompt_user_passwd(self, host, realm):
422 # Override this in a GUI environment!
423 try:
424 user = raw_input("Enter username for %s at %s: " %
425 (realm, host))
426 self.echo_off()
427 try:
428 passwd = raw_input(
429 "Enter password for %s in %s at %s: " %
430 (user, realm, host))
431 finally:
432 self.echo_on()
433 return user, passwd
434 except KeyboardInterrupt:
435 return None, None
436
437 def echo_off(self):
Guido van Rossumc5d8fed1998-02-05 16:21:28 +0000438 # XXX Is this sufficient???
439 if hasattr(os, "system"):
440 os.system("stty -echo")
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000441
442 def echo_on(self):
Guido van Rossumc5d8fed1998-02-05 16:21:28 +0000443 # XXX Is this sufficient???
444 if hasattr(os, "system"):
445 print
446 os.system("stty echo")
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000447
448
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000449# Utility functions
450
451# Return the IP address of the magic hostname 'localhost'
452_localhost = None
453def localhost():
454 global _localhost
455 if not _localhost:
456 _localhost = socket.gethostbyname('localhost')
457 return _localhost
458
459# Return the IP address of the current host
460_thishost = None
461def thishost():
462 global _thishost
463 if not _thishost:
464 _thishost = socket.gethostbyname(socket.gethostname())
465 return _thishost
466
467# Return the set of errors raised by the FTP class
468_ftperrors = None
469def ftperrors():
470 global _ftperrors
471 if not _ftperrors:
472 import ftplib
Guido van Rossum2966b321997-06-06 17:44:07 +0000473 _ftperrors = ftplib.all_errors
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000474 return _ftperrors
475
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000476# Return an empty mimetools.Message object
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000477_noheaders = None
478def noheaders():
479 global _noheaders
480 if not _noheaders:
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000481 import mimetools
482 import StringIO
483 _noheaders = mimetools.Message(StringIO.StringIO(), 0)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000484 _noheaders.fp.close() # Recycle file descriptor
485 return _noheaders
486
487
488# Utility classes
489
490# Class used by open_ftp() for cache of open FTP connections
491class ftpwrapper:
Guido van Rossum7c395db1994-07-04 22:14:49 +0000492 def __init__(self, user, passwd, host, port, dirs):
493 self.user = unquote(user or '')
494 self.passwd = unquote(passwd or '')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000495 self.host = host
496 self.port = port
Guido van Rossum7c395db1994-07-04 22:14:49 +0000497 self.dirs = []
498 for dir in dirs:
499 self.dirs.append(unquote(dir))
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000500 self.init()
501 def init(self):
502 import ftplib
Guido van Rossumd4990041997-12-28 04:21:20 +0000503 self.busy = 0
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000504 self.ftp = ftplib.FTP()
505 self.ftp.connect(self.host, self.port)
Guido van Rossum7c395db1994-07-04 22:14:49 +0000506 self.ftp.login(self.user, self.passwd)
507 for dir in self.dirs:
508 self.ftp.cwd(dir)
509 def retrfile(self, file, type):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000510 import ftplib
Guido van Rossumd4990041997-12-28 04:21:20 +0000511 self.endtransfer()
Guido van Rossum7c395db1994-07-04 22:14:49 +0000512 if type in ('d', 'D'): cmd = 'TYPE A'; isdir = 1
513 else: cmd = 'TYPE ' + type; isdir = 0
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000514 try:
Guido van Rossum7c395db1994-07-04 22:14:49 +0000515 self.ftp.voidcmd(cmd)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000516 except ftplib.all_errors:
517 self.init()
Guido van Rossum7c395db1994-07-04 22:14:49 +0000518 self.ftp.voidcmd(cmd)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000519 conn = None
Guido van Rossum7c395db1994-07-04 22:14:49 +0000520 if file and not isdir:
Guido van Rossumd4990041997-12-28 04:21:20 +0000521 # Use nlst to see if the file exists at all
522 try:
523 self.ftp.nlst(file)
524 except ftplib.error_perm, reason:
525 raise IOError, ('ftp error', reason), \
526 sys.exc_info()[2]
Guido van Rossume7579621998-01-19 22:26:54 +0000527 # Restore the transfer mode!
528 self.ftp.voidcmd(cmd)
Guido van Rossumd4990041997-12-28 04:21:20 +0000529 # Try to retrieve as a file
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000530 try:
531 cmd = 'RETR ' + file
532 conn = self.ftp.transfercmd(cmd)
533 except ftplib.error_perm, reason:
534 if reason[:3] != '550':
Guido van Rossum3c8484e1996-11-20 22:02:24 +0000535 raise IOError, ('ftp error', reason), \
Guido van Rossum332e1441997-09-29 23:23:46 +0000536 sys.exc_info()[2]
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000537 if not conn:
Guido van Rossume7579621998-01-19 22:26:54 +0000538 # Set transfer mode to ASCII!
539 self.ftp.voidcmd('TYPE A')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000540 # Try a directory listing
541 if file: cmd = 'LIST ' + file
542 else: cmd = 'LIST'
543 conn = self.ftp.transfercmd(cmd)
Guido van Rossumd4990041997-12-28 04:21:20 +0000544 self.busy = 1
Guido van Rossumf668d171997-06-06 21:11:11 +0000545 return addclosehook(conn.makefile('rb'), self.endtransfer)
546 def endtransfer(self):
Guido van Rossumd4990041997-12-28 04:21:20 +0000547 if not self.busy:
548 return
549 self.busy = 0
Guido van Rossumf668d171997-06-06 21:11:11 +0000550 try:
551 self.ftp.voidresp()
552 except ftperrors():
553 pass
554 def close(self):
Guido van Rossumd4990041997-12-28 04:21:20 +0000555 self.endtransfer()
Guido van Rossumf668d171997-06-06 21:11:11 +0000556 try:
557 self.ftp.close()
558 except ftperrors():
559 pass
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000560
561# Base class for addinfo and addclosehook
562class addbase:
563 def __init__(self, fp):
564 self.fp = fp
565 self.read = self.fp.read
566 self.readline = self.fp.readline
567 self.readlines = self.fp.readlines
568 self.fileno = self.fp.fileno
569 def __repr__(self):
570 return '<%s at %s whose fp = %s>' % (
571 self.__class__.__name__, `id(self)`, `self.fp`)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000572 def close(self):
573 self.read = None
574 self.readline = None
575 self.readlines = None
576 self.fileno = None
Guido van Rossum6cb15a01995-06-22 19:00:13 +0000577 if self.fp: self.fp.close()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000578 self.fp = None
579
580# Class to add a close hook to an open file
581class addclosehook(addbase):
582 def __init__(self, fp, closehook, *hookargs):
583 addbase.__init__(self, fp)
584 self.closehook = closehook
585 self.hookargs = hookargs
586 def close(self):
587 if self.closehook:
588 apply(self.closehook, self.hookargs)
589 self.closehook = None
590 self.hookargs = None
591 addbase.close(self)
592
593# class to add an info() method to an open file
594class addinfo(addbase):
595 def __init__(self, fp, headers):
596 addbase.__init__(self, fp)
597 self.headers = headers
598 def info(self):
599 return self.headers
600
Guido van Rossume6ad8911996-09-10 17:02:56 +0000601# class to add info() and geturl() methods to an open file
602class addinfourl(addbase):
603 def __init__(self, fp, headers, url):
604 addbase.__init__(self, fp)
605 self.headers = headers
606 self.url = url
607 def info(self):
608 return self.headers
609 def geturl(self):
610 return self.url
611
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000612
613# Utility to combine a URL with a base URL to form a new URL
614
615def basejoin(base, url):
616 type, path = splittype(url)
Sjoerd Mullendere0371b81995-11-10 10:36:07 +0000617 if type:
618 # if url is complete (i.e., it contains a type), return it
619 return url
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000620 host, path = splithost(path)
Sjoerd Mullendere0371b81995-11-10 10:36:07 +0000621 type, basepath = splittype(base) # inherit type from base
622 if host:
623 # if url contains host, just inherit type
624 if type: return type + '://' + host + path
625 else:
626 # no type inherited, so url must have started with //
627 # just return it
628 return url
629 host, basepath = splithost(basepath) # inherit host
630 basepath, basetag = splittag(basepath) # remove extraneuous cruft
631 basepath, basequery = splitquery(basepath) # idem
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000632 if path[:1] != '/':
Sjoerd Mullendere0371b81995-11-10 10:36:07 +0000633 # non-absolute path name
634 if path[:1] in ('#', '?'):
635 # path is just a tag or query, attach to basepath
636 i = len(basepath)
637 else:
638 # else replace last component
639 i = string.rfind(basepath, '/')
640 if i < 0:
641 # basepath not absolute
642 if host:
643 # host present, make absolute
644 basepath = '/'
645 else:
646 # else keep non-absolute
647 basepath = ''
648 else:
649 # remove last file component
650 basepath = basepath[:i+1]
Guido van Rossum54a1d0b1997-04-11 19:09:51 +0000651 # Interpret ../ (important because of symlinks)
652 while basepath and path[:3] == '../':
653 path = path[3:]
Guido van Rossum2b3fd761997-09-03 22:36:15 +0000654 i = string.rfind(basepath[:-1], '/')
Guido van Rossum54a1d0b1997-04-11 19:09:51 +0000655 if i > 0:
Guido van Rossum2b3fd761997-09-03 22:36:15 +0000656 basepath = basepath[:i+1]
657 elif i == 0:
658 basepath = '/'
659 break
660 else:
661 basepath = ''
Guido van Rossum54a1d0b1997-04-11 19:09:51 +0000662
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000663 path = basepath + path
Sjoerd Mullendere0371b81995-11-10 10:36:07 +0000664 if type and host: return type + '://' + host + path
665 elif type: return type + ':' + path
666 elif host: return '//' + host + path # don't know what this means
667 else: return path
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000668
669
Guido van Rossum7c395db1994-07-04 22:14:49 +0000670# Utilities to parse URLs (most of these return None for missing parts):
Sjoerd Mullendere0371b81995-11-10 10:36:07 +0000671# unwrap('<URL:type://host/path>') --> 'type://host/path'
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000672# splittype('type:opaquestring') --> 'type', 'opaquestring'
673# splithost('//host[:port]/path') --> 'host[:port]', '/path'
Guido van Rossum7c395db1994-07-04 22:14:49 +0000674# splituser('user[:passwd]@host[:port]') --> 'user[:passwd]', 'host[:port]'
675# splitpasswd('user:passwd') -> 'user', 'passwd'
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000676# splitport('host:port') --> 'host', 'port'
677# splitquery('/path?query') --> '/path', 'query'
678# splittag('/path#tag') --> '/path', 'tag'
Guido van Rossum7c395db1994-07-04 22:14:49 +0000679# splitattr('/path;attr1=value1;attr2=value2;...') ->
680# '/path', ['attr1=value1', 'attr2=value2', ...]
681# splitvalue('attr=value') --> 'attr', 'value'
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000682# splitgophertype('/Xselector') --> 'X', 'selector'
683# unquote('abc%20def') -> 'abc def'
684# quote('abc def') -> 'abc%20def')
685
686def unwrap(url):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000687 url = string.strip(url)
688 if url[:1] == '<' and url[-1:] == '>':
689 url = string.strip(url[1:-1])
690 if url[:4] == 'URL:': url = string.strip(url[4:])
691 return url
692
Guido van Rossum332e1441997-09-29 23:23:46 +0000693_typeprog = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000694def splittype(url):
Guido van Rossum332e1441997-09-29 23:23:46 +0000695 global _typeprog
696 if _typeprog is None:
697 import re
698 _typeprog = re.compile('^([^/:]+):')
699
700 match = _typeprog.match(url)
701 if match:
702 scheme = match.group(1)
Guido van Rossumab0d1af1997-04-16 15:17:06 +0000703 return scheme, url[len(scheme) + 1:]
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000704 return None, url
705
Guido van Rossum332e1441997-09-29 23:23:46 +0000706_hostprog = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000707def splithost(url):
Guido van Rossum332e1441997-09-29 23:23:46 +0000708 global _hostprog
709 if _hostprog is None:
710 import re
711 _hostprog = re.compile('^//([^/]+)(.*)$')
712
713 match = _hostprog.match(url)
714 if match: return match.group(1, 2)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000715 return None, url
716
Guido van Rossum332e1441997-09-29 23:23:46 +0000717_userprog = None
Guido van Rossum7c395db1994-07-04 22:14:49 +0000718def splituser(host):
Guido van Rossum332e1441997-09-29 23:23:46 +0000719 global _userprog
720 if _userprog is None:
721 import re
722 _userprog = re.compile('^([^@]*)@(.*)$')
723
724 match = _userprog.match(host)
725 if match: return match.group(1, 2)
Guido van Rossum7c395db1994-07-04 22:14:49 +0000726 return None, host
727
Guido van Rossum332e1441997-09-29 23:23:46 +0000728_passwdprog = None
Guido van Rossum7c395db1994-07-04 22:14:49 +0000729def splitpasswd(user):
Guido van Rossum332e1441997-09-29 23:23:46 +0000730 global _passwdprog
731 if _passwdprog is None:
732 import re
733 _passwdprog = re.compile('^([^:]*):(.*)$')
734
Fred Drake654451d1997-10-14 13:30:57 +0000735 match = _passwdprog.match(user)
Guido van Rossum332e1441997-09-29 23:23:46 +0000736 if match: return match.group(1, 2)
Guido van Rossum7c395db1994-07-04 22:14:49 +0000737 return user, None
738
Guido van Rossum332e1441997-09-29 23:23:46 +0000739_portprog = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000740def splitport(host):
Guido van Rossum332e1441997-09-29 23:23:46 +0000741 global _portprog
742 if _portprog is None:
743 import re
744 _portprog = re.compile('^(.*):([0-9]+)$')
745
746 match = _portprog.match(host)
747 if match: return match.group(1, 2)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000748 return host, None
749
Guido van Rossum53725a21996-06-13 19:12:35 +0000750# Split host and port, returning numeric port.
751# Return given default port if no ':' found; defaults to -1.
Guido van Rossum84a00a81996-06-17 17:11:40 +0000752# Return numerical port if a valid number are found after ':'.
753# Return None if ':' but not a valid number.
Guido van Rossum332e1441997-09-29 23:23:46 +0000754_nportprog = None
Guido van Rossum53725a21996-06-13 19:12:35 +0000755def splitnport(host, defport=-1):
Guido van Rossum332e1441997-09-29 23:23:46 +0000756 global _nportprog
757 if _nportprog is None:
758 import re
759 _nportprog = re.compile('^(.*):(.*)$')
760
761 match = _nportprog.match(host)
762 if match:
763 host, port = match.group(1, 2)
Guido van Rossum84a00a81996-06-17 17:11:40 +0000764 try:
765 if not port: raise string.atoi_error, "no digits"
766 nport = string.atoi(port)
767 except string.atoi_error:
768 nport = None
Guido van Rossum53725a21996-06-13 19:12:35 +0000769 return host, nport
770 return host, defport
771
Guido van Rossum332e1441997-09-29 23:23:46 +0000772_queryprog = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000773def splitquery(url):
Guido van Rossum332e1441997-09-29 23:23:46 +0000774 global _queryprog
775 if _queryprog is None:
776 import re
777 _queryprog = re.compile('^(.*)\?([^?]*)$')
778
779 match = _queryprog.match(url)
780 if match: return match.group(1, 2)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000781 return url, None
782
Guido van Rossum332e1441997-09-29 23:23:46 +0000783_tagprog = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000784def splittag(url):
Guido van Rossum332e1441997-09-29 23:23:46 +0000785 global _tagprog
786 if _tagprog is None:
787 import re
788 _tagprog = re.compile('^(.*)#([^#]*)$')
789
790 match = _tagprog.match(url)
791 if match: return match.group(1, 2)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000792 return url, None
793
Guido van Rossum7c395db1994-07-04 22:14:49 +0000794def splitattr(url):
795 words = string.splitfields(url, ';')
796 return words[0], words[1:]
797
Guido van Rossum332e1441997-09-29 23:23:46 +0000798_valueprog = None
Guido van Rossum7c395db1994-07-04 22:14:49 +0000799def splitvalue(attr):
Guido van Rossum332e1441997-09-29 23:23:46 +0000800 global _valueprog
801 if _valueprog is None:
802 import re
803 _valueprog = re.compile('^([^=]*)=(.*)$')
804
805 match = _valueprog.match(attr)
806 if match: return match.group(1, 2)
Guido van Rossum7c395db1994-07-04 22:14:49 +0000807 return attr, None
808
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000809def splitgophertype(selector):
810 if selector[:1] == '/' and selector[1:2]:
811 return selector[1], selector[2:]
812 return None, selector
813
Guido van Rossum332e1441997-09-29 23:23:46 +0000814_quoteprog = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000815def unquote(s):
Guido van Rossum332e1441997-09-29 23:23:46 +0000816 global _quoteprog
817 if _quoteprog is None:
818 import re
819 _quoteprog = re.compile('%[0-9a-fA-F][0-9a-fA-F]')
820
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000821 i = 0
822 n = len(s)
Guido van Rossumf8abb381996-08-26 15:56:12 +0000823 res = []
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000824 while 0 <= i < n:
Guido van Rossum332e1441997-09-29 23:23:46 +0000825 match = _quoteprog.search(s, i)
826 if not match:
Guido van Rossumf8abb381996-08-26 15:56:12 +0000827 res.append(s[i:])
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000828 break
Guido van Rossum332e1441997-09-29 23:23:46 +0000829 j = match.start(0)
Guido van Rossumf8abb381996-08-26 15:56:12 +0000830 res.append(s[i:j] + chr(string.atoi(s[j+1:j+3], 16)))
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000831 i = j+3
Guido van Rossumf8abb381996-08-26 15:56:12 +0000832 return string.joinfields(res, '')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000833
Guido van Rossum0564e121996-12-13 14:47:36 +0000834def unquote_plus(s):
835 if '+' in s:
Guido van Rossum332e1441997-09-29 23:23:46 +0000836 # replace '+' with ' '
837 s = string.join(string.split(s, '+'), ' ')
Guido van Rossum0564e121996-12-13 14:47:36 +0000838 return unquote(s)
839
Guido van Rossum3bb54481994-08-29 10:52:58 +0000840always_safe = string.letters + string.digits + '_,.-'
Guido van Rossum7c395db1994-07-04 22:14:49 +0000841def quote(s, safe = '/'):
842 safe = always_safe + safe
Guido van Rossumf8abb381996-08-26 15:56:12 +0000843 res = []
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000844 for c in s:
Guido van Rossum7c395db1994-07-04 22:14:49 +0000845 if c in safe:
Guido van Rossumf8abb381996-08-26 15:56:12 +0000846 res.append(c)
Guido van Rossum7c395db1994-07-04 22:14:49 +0000847 else:
Guido van Rossumf8abb381996-08-26 15:56:12 +0000848 res.append('%%%02x' % ord(c))
849 return string.joinfields(res, '')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000850
Guido van Rossum0564e121996-12-13 14:47:36 +0000851def quote_plus(s, safe = '/'):
852 if ' ' in s:
Guido van Rossum332e1441997-09-29 23:23:46 +0000853 # replace ' ' with '+'
854 s = string.join(string.split(s, ' '), '+')
Guido van Rossum0564e121996-12-13 14:47:36 +0000855 return quote(s, safe + '+')
856 else:
857 return quote(s, safe)
858
Guido van Rossum442e7201996-03-20 15:33:11 +0000859
860# Proxy handling
861def getproxies():
862 """Return a dictionary of protocol scheme -> proxy server URL mappings.
863
864 Scan the environment for variables named <scheme>_proxy;
865 this seems to be the standard convention. If you need a
866 different way, you can pass a proxies dictionary to the
867 [Fancy]URLopener constructor.
868
869 """
870 proxies = {}
871 for name, value in os.environ.items():
Guido van Rossum1aec3f01997-05-28 15:37:19 +0000872 name = string.lower(name)
Guido van Rossum442e7201996-03-20 15:33:11 +0000873 if value and name[-6:] == '_proxy':
874 proxies[name[:-6]] = value
875 return proxies
876
877
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000878# Test and time quote() and unquote()
879def test1():
880 import time
881 s = ''
882 for i in range(256): s = s + chr(i)
883 s = s*4
884 t0 = time.time()
885 qs = quote(s)
886 uqs = unquote(qs)
887 t1 = time.time()
888 if uqs != s:
889 print 'Wrong!'
890 print `s`
891 print `qs`
892 print `uqs`
893 print round(t1 - t0, 3), 'sec'
894
895
896# Test program
897def test():
898 import sys
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000899 args = sys.argv[1:]
900 if not args:
901 args = [
902 '/etc/passwd',
903 'file:/etc/passwd',
904 'file://localhost/etc/passwd',
Guido van Rossum332e1441997-09-29 23:23:46 +0000905 'ftp://ftp.python.org/etc/passwd',
906 'gopher://gopher.micro.umn.edu/1/',
907 'http://www.python.org/index.html',
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000908 ]
909 try:
910 for url in args:
911 print '-'*10, url, '-'*10
912 fn, h = urlretrieve(url)
913 print fn, h
914 if h:
915 print '======'
916 for k in h.keys(): print k + ':', h[k]
917 print '======'
Guido van Rossumc511aee1997-04-11 19:01:48 +0000918 fp = open(fn, 'rb')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000919 data = fp.read()
920 del fp
Guido van Rossum332e1441997-09-29 23:23:46 +0000921 if '\r' in data:
922 table = string.maketrans("", "")
923 data = string.translate(data, table, "\r")
924 print data
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000925 fn, h = None, None
926 print '-'*40
927 finally:
928 urlcleanup()
929
930# Run test program when run as a script
931if __name__ == '__main__':
Guido van Rossum332e1441997-09-29 23:23:46 +0000932 test1()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000933 test()