blob: 5363f3c711101b01423144143f05a73ec33bcbb1 [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 Rossum036309b1997-10-27 18:56:19 +000030__version__ = '1.9'
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 Rossume6ad8911996-09-10 17:02:56 +0000143 self.openedurl = '%s:%s' % (type, url)
Guido van Rossum442e7201996-03-20 15:33:11 +0000144 if self.proxies.has_key(type):
145 proxy = self.proxies[type]
146 type, proxy = splittype(proxy)
147 host, selector = splithost(proxy)
148 url = (host, fullurl) # Signal special case to open_*()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000149 name = 'open_' + type
150 if '-' in name:
Guido van Rossum332e1441997-09-29 23:23:46 +0000151 # replace - with _
152 name = string.join(string.split(name, '-'), '_')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000153 if not hasattr(self, name):
Guido van Rossumbd013741996-12-10 16:00:28 +0000154 if data is None:
155 return self.open_unknown(fullurl)
156 else:
157 return self.open_unknown(fullurl, data)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000158 try:
Guido van Rossumbd013741996-12-10 16:00:28 +0000159 if data is None:
160 return getattr(self, name)(url)
161 else:
162 return getattr(self, name)(url, data)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000163 except socket.error, msg:
Guido van Rossum332e1441997-09-29 23:23:46 +0000164 raise IOError, ('socket error', msg), sys.exc_info()[2]
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000165
Guido van Rossumca445401995-08-29 19:19:12 +0000166 # Overridable interface to open unknown URL type
Guido van Rossumbd013741996-12-10 16:00:28 +0000167 def open_unknown(self, fullurl, data=None):
Guido van Rossumca445401995-08-29 19:19:12 +0000168 type, url = splittype(fullurl)
169 raise IOError, ('url error', 'unknown url type', type)
170
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000171 # External interface
172 # retrieve(url) returns (filename, None) for a local object
173 # or (tempfilename, headers) for a remote object
Guido van Rossuma7e4b281996-06-11 00:16:27 +0000174 def retrieve(self, url, filename=None):
Guido van Rossum03710d21998-02-05 16:22:27 +0000175 url = unwrap(url)
176 self.openedurl = url
Guido van Rossum7aeb4b91994-08-23 13:32:20 +0000177 if self.tempcache and self.tempcache.has_key(url):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000178 return self.tempcache[url]
Guido van Rossum03710d21998-02-05 16:22:27 +0000179 type, url1 = splittype(url)
Guido van Rossuma7e4b281996-06-11 00:16:27 +0000180 if not filename and (not type or type == 'file'):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000181 try:
182 fp = self.open_local_file(url1)
183 del fp
Jack Jansene8ea21b1995-12-21 15:43:53 +0000184 return url2pathname(splithost(url1)[1]), None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000185 except IOError, msg:
186 pass
187 fp = self.open(url)
188 headers = fp.info()
Guido van Rossuma7e4b281996-06-11 00:16:27 +0000189 if not filename:
190 import tempfile
191 filename = tempfile.mktemp()
Guido van Rossum2b3fd761997-09-03 22:36:15 +0000192 self.__tempfiles.append(filename)
Guido van Rossuma7e4b281996-06-11 00:16:27 +0000193 result = filename, headers
Guido van Rossum7aeb4b91994-08-23 13:32:20 +0000194 if self.tempcache is not None:
Guido van Rossumfa59e831994-09-21 11:36:19 +0000195 self.tempcache[url] = result
Guido van Rossumc511aee1997-04-11 19:01:48 +0000196 tfp = open(filename, 'wb')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000197 bs = 1024*8
198 block = fp.read(bs)
199 while block:
200 tfp.write(block)
201 block = fp.read(bs)
Guido van Rossumab0abdc1997-08-26 19:06:40 +0000202 fp.close()
203 tfp.close()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000204 del fp
205 del tfp
206 return result
207
208 # Each method named open_<type> knows how to open that type of URL
209
210 # Use HTTP protocol
Guido van Rossumbd013741996-12-10 16:00:28 +0000211 def open_http(self, url, data=None):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000212 import httplib
Guido van Rossum442e7201996-03-20 15:33:11 +0000213 if type(url) is type(""):
214 host, selector = splithost(url)
Guido van Rossum78c96371996-08-26 18:09:59 +0000215 user_passwd, host = splituser(host)
Guido van Rossumc24751b1997-06-03 14:34:19 +0000216 realhost = host
Guido van Rossum442e7201996-03-20 15:33:11 +0000217 else:
218 host, selector = url
Guido van Rossum78c96371996-08-26 18:09:59 +0000219 urltype, rest = splittype(selector)
Guido van Rossumfd795661997-04-02 05:46:35 +0000220 user_passwd = None
Guido van Rossumc24751b1997-06-03 14:34:19 +0000221 if string.lower(urltype) != 'http':
222 realhost = None
223 else:
Guido van Rossum78c96371996-08-26 18:09:59 +0000224 realhost, rest = splithost(rest)
225 user_passwd, realhost = splituser(realhost)
226 if user_passwd:
227 selector = "%s://%s%s" % (urltype,
228 realhost, rest)
Guido van Rossumfd795661997-04-02 05:46:35 +0000229 #print "proxy via http:", host, selector
Guido van Rossum590b2891994-04-18 09:39:56 +0000230 if not host: raise IOError, ('http error', 'no host given')
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000231 if user_passwd:
232 import base64
233 auth = string.strip(base64.encodestring(user_passwd))
234 else:
235 auth = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000236 h = httplib.HTTP(host)
Guido van Rossumbd013741996-12-10 16:00:28 +0000237 if data is not None:
238 h.putrequest('POST', selector)
239 h.putheader('Content-type',
240 'application/x-www-form-urlencoded')
241 h.putheader('Content-length', '%d' % len(data))
242 else:
243 h.putrequest('GET', selector)
Guido van Rossumc5d7e801996-11-11 19:01:17 +0000244 if auth: h.putheader('Authorization', 'Basic %s' % auth)
Guido van Rossumc24751b1997-06-03 14:34:19 +0000245 if realhost: h.putheader('Host', realhost)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000246 for args in self.addheaders: apply(h.putheader, args)
Guido van Rossum6cb15a01995-06-22 19:00:13 +0000247 h.endheaders()
Guido van Rossumbd013741996-12-10 16:00:28 +0000248 if data is not None:
249 h.send(data + '\r\n')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000250 errcode, errmsg, headers = h.getreply()
Guido van Rossum6cb15a01995-06-22 19:00:13 +0000251 fp = h.getfile()
252 if errcode == 200:
Guido van Rossume6ad8911996-09-10 17:02:56 +0000253 return addinfourl(fp, headers, self.openedurl)
Guido van Rossum6cb15a01995-06-22 19:00:13 +0000254 else:
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000255 return self.http_error(url,
256 fp, errcode, errmsg, headers)
257
258 # Handle http errors.
259 # Derived class can override this, or provide specific handlers
260 # named http_error_DDD where DDD is the 3-digit error code
261 def http_error(self, url, fp, errcode, errmsg, headers):
262 # First check if there's a specific handler for this error
263 name = 'http_error_%d' % errcode
264 if hasattr(self, name):
265 method = getattr(self, name)
266 result = method(url, fp, errcode, errmsg, headers)
267 if result: return result
268 return self.http_error_default(
269 url, fp, errcode, errmsg, headers)
270
271 # Default http error handler: close the connection and raises IOError
272 def http_error_default(self, url, fp, errcode, errmsg, headers):
273 void = fp.read()
274 fp.close()
275 raise IOError, ('http error', errcode, errmsg, headers)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000276
277 # Use Gopher protocol
278 def open_gopher(self, url):
279 import gopherlib
280 host, selector = splithost(url)
Guido van Rossum590b2891994-04-18 09:39:56 +0000281 if not host: raise IOError, ('gopher error', 'no host given')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000282 type, selector = splitgophertype(selector)
283 selector, query = splitquery(selector)
Guido van Rossum7c395db1994-07-04 22:14:49 +0000284 selector = unquote(selector)
285 if query:
286 query = unquote(query)
287 fp = gopherlib.send_query(selector, query, host)
288 else:
289 fp = gopherlib.send_selector(selector, host)
Guido van Rossume6ad8911996-09-10 17:02:56 +0000290 return addinfourl(fp, noheaders(), self.openedurl)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000291
292 # Use local file or FTP depending on form of URL
293 def open_file(self, url):
Guido van Rossumb6784dc1997-08-20 23:34:01 +0000294 if url[:2] == '//' and url[2:3] != '/':
295 return self.open_ftp(url)
296 else:
297 return self.open_local_file(url)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000298
299 # Use local file
300 def open_local_file(self, url):
301 host, file = splithost(url)
Guido van Rossumb030bc01996-10-10 16:01:16 +0000302 if not host:
Guido van Rossum2966b321997-06-06 17:44:07 +0000303 return addinfourl(
304 open(url2pathname(file), 'rb'),
305 noheaders(), 'file:'+file)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000306 host, port = splitport(host)
307 if not port and socket.gethostbyname(host) in (
308 localhost(), thishost()):
Guido van Rossum7c395db1994-07-04 22:14:49 +0000309 file = unquote(file)
Guido van Rossum2966b321997-06-06 17:44:07 +0000310 return addinfourl(
311 open(url2pathname(file), 'rb'),
312 noheaders(), 'file:'+file)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000313 raise IOError, ('local file error', 'not on local host')
314
315 # Use FTP protocol
316 def open_ftp(self, url):
Guido van Rossum7c395db1994-07-04 22:14:49 +0000317 host, path = splithost(url)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000318 if not host: raise IOError, ('ftp error', 'no host given')
319 host, port = splitport(host)
Guido van Rossum7c395db1994-07-04 22:14:49 +0000320 user, host = splituser(host)
321 if user: user, passwd = splitpasswd(user)
322 else: passwd = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000323 host = socket.gethostbyname(host)
324 if not port:
325 import ftplib
326 port = ftplib.FTP_PORT
Guido van Rossumc0f29c21997-12-02 20:26:21 +0000327 else:
328 port = int(port)
Guido van Rossum7c395db1994-07-04 22:14:49 +0000329 path, attrs = splitattr(path)
330 dirs = string.splitfields(path, '/')
331 dirs, file = dirs[:-1], dirs[-1]
332 if dirs and not dirs[0]: dirs = dirs[1:]
333 key = (user, host, port, string.joinfields(dirs, '/'))
Guido van Rossumf668d171997-06-06 21:11:11 +0000334 if len(self.ftpcache) > MAXFTPCACHE:
335 # Prune the cache, rather arbitrarily
336 for k in self.ftpcache.keys():
337 if k != key:
338 v = self.ftpcache[k]
339 del self.ftpcache[k]
340 v.close()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000341 try:
342 if not self.ftpcache.has_key(key):
Guido van Rossum7c395db1994-07-04 22:14:49 +0000343 self.ftpcache[key] = \
344 ftpwrapper(user, passwd,
345 host, port, dirs)
346 if not file: type = 'D'
347 else: type = 'I'
348 for attr in attrs:
349 attr, value = splitvalue(attr)
350 if string.lower(attr) == 'type' and \
351 value in ('a', 'A', 'i', 'I', 'd', 'D'):
352 type = string.upper(value)
Guido van Rossum2966b321997-06-06 17:44:07 +0000353 return addinfourl(
354 self.ftpcache[key].retrfile(file, type),
355 noheaders(), self.openedurl)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000356 except ftperrors(), msg:
Guido van Rossum332e1441997-09-29 23:23:46 +0000357 raise IOError, ('ftp error', msg), sys.exc_info()[2]
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000358
359
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000360# Derived class with handlers for errors we can handle (perhaps)
361class FancyURLopener(URLopener):
362
363 def __init__(self, *args):
364 apply(URLopener.__init__, (self,) + args)
365 self.auth_cache = {}
366
367 # Default error handling -- don't raise an exception
368 def http_error_default(self, url, fp, errcode, errmsg, headers):
Guido van Rossume6ad8911996-09-10 17:02:56 +0000369 return addinfourl(fp, headers, self.openedurl)
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000370
Guido van Rossume6ad8911996-09-10 17:02:56 +0000371 # Error 302 -- relocated (temporarily)
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000372 def http_error_302(self, url, fp, errcode, errmsg, headers):
373 # XXX The server can force infinite recursion here!
374 if headers.has_key('location'):
375 newurl = headers['location']
376 elif headers.has_key('uri'):
377 newurl = headers['uri']
378 else:
379 return
380 void = fp.read()
381 fp.close()
382 return self.open(newurl)
383
Guido van Rossume6ad8911996-09-10 17:02:56 +0000384 # Error 301 -- also relocated (permanently)
385 http_error_301 = http_error_302
386
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000387 # Error 401 -- authentication required
388 # See this URL for a description of the basic authentication scheme:
389 # http://www.ics.uci.edu/pub/ietf/http/draft-ietf-http-v10-spec-00.txt
390 def http_error_401(self, url, fp, errcode, errmsg, headers):
391 if headers.has_key('www-authenticate'):
392 stuff = headers['www-authenticate']
Guido van Rossum332e1441997-09-29 23:23:46 +0000393 import re
394 match = re.match(
395 '[ \t]*([^ \t]+)[ \t]+realm="([^"]*)"', stuff)
396 if match:
Guido van Rossumc5d8fed1998-02-05 16:21:28 +0000397 scheme, realm = match.groups()
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000398 if string.lower(scheme) == 'basic':
399 return self.retry_http_basic_auth(
400 url, realm)
401
402 def retry_http_basic_auth(self, url, realm):
403 host, selector = splithost(url)
404 i = string.find(host, '@') + 1
405 host = host[i:]
406 user, passwd = self.get_user_passwd(host, realm, i)
407 if not (user or passwd): return None
408 host = user + ':' + passwd + '@' + host
409 newurl = '//' + host + selector
410 return self.open_http(newurl)
411
412 def get_user_passwd(self, host, realm, clear_cache = 0):
413 key = realm + '@' + string.lower(host)
414 if self.auth_cache.has_key(key):
415 if clear_cache:
416 del self.auth_cache[key]
417 else:
418 return self.auth_cache[key]
419 user, passwd = self.prompt_user_passwd(host, realm)
420 if user or passwd: self.auth_cache[key] = (user, passwd)
421 return user, passwd
422
423 def prompt_user_passwd(self, host, realm):
424 # Override this in a GUI environment!
425 try:
426 user = raw_input("Enter username for %s at %s: " %
427 (realm, host))
428 self.echo_off()
429 try:
430 passwd = raw_input(
431 "Enter password for %s in %s at %s: " %
432 (user, realm, host))
433 finally:
434 self.echo_on()
435 return user, passwd
436 except KeyboardInterrupt:
437 return None, None
438
439 def echo_off(self):
Guido van Rossumc5d8fed1998-02-05 16:21:28 +0000440 # XXX Is this sufficient???
441 if hasattr(os, "system"):
442 os.system("stty -echo")
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000443
444 def echo_on(self):
Guido van Rossumc5d8fed1998-02-05 16:21:28 +0000445 # XXX Is this sufficient???
446 if hasattr(os, "system"):
447 print
448 os.system("stty echo")
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000449
450
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000451# Utility functions
452
453# Return the IP address of the magic hostname 'localhost'
454_localhost = None
455def localhost():
456 global _localhost
457 if not _localhost:
458 _localhost = socket.gethostbyname('localhost')
459 return _localhost
460
461# Return the IP address of the current host
462_thishost = None
463def thishost():
464 global _thishost
465 if not _thishost:
466 _thishost = socket.gethostbyname(socket.gethostname())
467 return _thishost
468
469# Return the set of errors raised by the FTP class
470_ftperrors = None
471def ftperrors():
472 global _ftperrors
473 if not _ftperrors:
474 import ftplib
Guido van Rossum2966b321997-06-06 17:44:07 +0000475 _ftperrors = ftplib.all_errors
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000476 return _ftperrors
477
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000478# Return an empty mimetools.Message object
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000479_noheaders = None
480def noheaders():
481 global _noheaders
482 if not _noheaders:
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000483 import mimetools
484 import StringIO
485 _noheaders = mimetools.Message(StringIO.StringIO(), 0)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000486 _noheaders.fp.close() # Recycle file descriptor
487 return _noheaders
488
489
490# Utility classes
491
492# Class used by open_ftp() for cache of open FTP connections
493class ftpwrapper:
Guido van Rossum7c395db1994-07-04 22:14:49 +0000494 def __init__(self, user, passwd, host, port, dirs):
495 self.user = unquote(user or '')
496 self.passwd = unquote(passwd or '')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000497 self.host = host
498 self.port = port
Guido van Rossum7c395db1994-07-04 22:14:49 +0000499 self.dirs = []
500 for dir in dirs:
501 self.dirs.append(unquote(dir))
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000502 self.init()
503 def init(self):
504 import ftplib
Guido van Rossumd4990041997-12-28 04:21:20 +0000505 self.busy = 0
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000506 self.ftp = ftplib.FTP()
507 self.ftp.connect(self.host, self.port)
Guido van Rossum7c395db1994-07-04 22:14:49 +0000508 self.ftp.login(self.user, self.passwd)
509 for dir in self.dirs:
510 self.ftp.cwd(dir)
511 def retrfile(self, file, type):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000512 import ftplib
Guido van Rossumd4990041997-12-28 04:21:20 +0000513 self.endtransfer()
Guido van Rossum7c395db1994-07-04 22:14:49 +0000514 if type in ('d', 'D'): cmd = 'TYPE A'; isdir = 1
515 else: cmd = 'TYPE ' + type; isdir = 0
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000516 try:
Guido van Rossum7c395db1994-07-04 22:14:49 +0000517 self.ftp.voidcmd(cmd)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000518 except ftplib.all_errors:
519 self.init()
Guido van Rossum7c395db1994-07-04 22:14:49 +0000520 self.ftp.voidcmd(cmd)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000521 conn = None
Guido van Rossum7c395db1994-07-04 22:14:49 +0000522 if file and not isdir:
Guido van Rossumd4990041997-12-28 04:21:20 +0000523 # Use nlst to see if the file exists at all
524 try:
525 self.ftp.nlst(file)
526 except ftplib.error_perm, reason:
527 raise IOError, ('ftp error', reason), \
528 sys.exc_info()[2]
Guido van Rossume7579621998-01-19 22:26:54 +0000529 # Restore the transfer mode!
530 self.ftp.voidcmd(cmd)
Guido van Rossumd4990041997-12-28 04:21:20 +0000531 # Try to retrieve as a file
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000532 try:
533 cmd = 'RETR ' + file
534 conn = self.ftp.transfercmd(cmd)
535 except ftplib.error_perm, reason:
536 if reason[:3] != '550':
Guido van Rossum3c8484e1996-11-20 22:02:24 +0000537 raise IOError, ('ftp error', reason), \
Guido van Rossum332e1441997-09-29 23:23:46 +0000538 sys.exc_info()[2]
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000539 if not conn:
Guido van Rossume7579621998-01-19 22:26:54 +0000540 # Set transfer mode to ASCII!
541 self.ftp.voidcmd('TYPE A')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000542 # Try a directory listing
543 if file: cmd = 'LIST ' + file
544 else: cmd = 'LIST'
545 conn = self.ftp.transfercmd(cmd)
Guido van Rossumd4990041997-12-28 04:21:20 +0000546 self.busy = 1
Guido van Rossumf668d171997-06-06 21:11:11 +0000547 return addclosehook(conn.makefile('rb'), self.endtransfer)
548 def endtransfer(self):
Guido van Rossumd4990041997-12-28 04:21:20 +0000549 if not self.busy:
550 return
551 self.busy = 0
Guido van Rossumf668d171997-06-06 21:11:11 +0000552 try:
553 self.ftp.voidresp()
554 except ftperrors():
555 pass
556 def close(self):
Guido van Rossumd4990041997-12-28 04:21:20 +0000557 self.endtransfer()
Guido van Rossumf668d171997-06-06 21:11:11 +0000558 try:
559 self.ftp.close()
560 except ftperrors():
561 pass
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000562
563# Base class for addinfo and addclosehook
564class addbase:
565 def __init__(self, fp):
566 self.fp = fp
567 self.read = self.fp.read
568 self.readline = self.fp.readline
569 self.readlines = self.fp.readlines
570 self.fileno = self.fp.fileno
571 def __repr__(self):
572 return '<%s at %s whose fp = %s>' % (
573 self.__class__.__name__, `id(self)`, `self.fp`)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000574 def close(self):
575 self.read = None
576 self.readline = None
577 self.readlines = None
578 self.fileno = None
Guido van Rossum6cb15a01995-06-22 19:00:13 +0000579 if self.fp: self.fp.close()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000580 self.fp = None
581
582# Class to add a close hook to an open file
583class addclosehook(addbase):
584 def __init__(self, fp, closehook, *hookargs):
585 addbase.__init__(self, fp)
586 self.closehook = closehook
587 self.hookargs = hookargs
588 def close(self):
589 if self.closehook:
590 apply(self.closehook, self.hookargs)
591 self.closehook = None
592 self.hookargs = None
593 addbase.close(self)
594
595# class to add an info() method to an open file
596class addinfo(addbase):
597 def __init__(self, fp, headers):
598 addbase.__init__(self, fp)
599 self.headers = headers
600 def info(self):
601 return self.headers
602
Guido van Rossume6ad8911996-09-10 17:02:56 +0000603# class to add info() and geturl() methods to an open file
604class addinfourl(addbase):
605 def __init__(self, fp, headers, url):
606 addbase.__init__(self, fp)
607 self.headers = headers
608 self.url = url
609 def info(self):
610 return self.headers
611 def geturl(self):
612 return self.url
613
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000614
615# Utility to combine a URL with a base URL to form a new URL
616
617def basejoin(base, url):
618 type, path = splittype(url)
Sjoerd Mullendere0371b81995-11-10 10:36:07 +0000619 if type:
620 # if url is complete (i.e., it contains a type), return it
621 return url
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000622 host, path = splithost(path)
Sjoerd Mullendere0371b81995-11-10 10:36:07 +0000623 type, basepath = splittype(base) # inherit type from base
624 if host:
625 # if url contains host, just inherit type
626 if type: return type + '://' + host + path
627 else:
628 # no type inherited, so url must have started with //
629 # just return it
630 return url
631 host, basepath = splithost(basepath) # inherit host
632 basepath, basetag = splittag(basepath) # remove extraneuous cruft
633 basepath, basequery = splitquery(basepath) # idem
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000634 if path[:1] != '/':
Sjoerd Mullendere0371b81995-11-10 10:36:07 +0000635 # non-absolute path name
636 if path[:1] in ('#', '?'):
637 # path is just a tag or query, attach to basepath
638 i = len(basepath)
639 else:
640 # else replace last component
641 i = string.rfind(basepath, '/')
642 if i < 0:
643 # basepath not absolute
644 if host:
645 # host present, make absolute
646 basepath = '/'
647 else:
648 # else keep non-absolute
649 basepath = ''
650 else:
651 # remove last file component
652 basepath = basepath[:i+1]
Guido van Rossum54a1d0b1997-04-11 19:09:51 +0000653 # Interpret ../ (important because of symlinks)
654 while basepath and path[:3] == '../':
655 path = path[3:]
Guido van Rossum2b3fd761997-09-03 22:36:15 +0000656 i = string.rfind(basepath[:-1], '/')
Guido van Rossum54a1d0b1997-04-11 19:09:51 +0000657 if i > 0:
Guido van Rossum2b3fd761997-09-03 22:36:15 +0000658 basepath = basepath[:i+1]
659 elif i == 0:
660 basepath = '/'
661 break
662 else:
663 basepath = ''
Guido van Rossum54a1d0b1997-04-11 19:09:51 +0000664
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000665 path = basepath + path
Sjoerd Mullendere0371b81995-11-10 10:36:07 +0000666 if type and host: return type + '://' + host + path
667 elif type: return type + ':' + path
668 elif host: return '//' + host + path # don't know what this means
669 else: return path
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000670
671
Guido van Rossum7c395db1994-07-04 22:14:49 +0000672# Utilities to parse URLs (most of these return None for missing parts):
Sjoerd Mullendere0371b81995-11-10 10:36:07 +0000673# unwrap('<URL:type://host/path>') --> 'type://host/path'
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000674# splittype('type:opaquestring') --> 'type', 'opaquestring'
675# splithost('//host[:port]/path') --> 'host[:port]', '/path'
Guido van Rossum7c395db1994-07-04 22:14:49 +0000676# splituser('user[:passwd]@host[:port]') --> 'user[:passwd]', 'host[:port]'
677# splitpasswd('user:passwd') -> 'user', 'passwd'
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000678# splitport('host:port') --> 'host', 'port'
679# splitquery('/path?query') --> '/path', 'query'
680# splittag('/path#tag') --> '/path', 'tag'
Guido van Rossum7c395db1994-07-04 22:14:49 +0000681# splitattr('/path;attr1=value1;attr2=value2;...') ->
682# '/path', ['attr1=value1', 'attr2=value2', ...]
683# splitvalue('attr=value') --> 'attr', 'value'
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000684# splitgophertype('/Xselector') --> 'X', 'selector'
685# unquote('abc%20def') -> 'abc def'
686# quote('abc def') -> 'abc%20def')
687
688def unwrap(url):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000689 url = string.strip(url)
690 if url[:1] == '<' and url[-1:] == '>':
691 url = string.strip(url[1:-1])
692 if url[:4] == 'URL:': url = string.strip(url[4:])
693 return url
694
Guido van Rossum332e1441997-09-29 23:23:46 +0000695_typeprog = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000696def splittype(url):
Guido van Rossum332e1441997-09-29 23:23:46 +0000697 global _typeprog
698 if _typeprog is None:
699 import re
700 _typeprog = re.compile('^([^/:]+):')
701
702 match = _typeprog.match(url)
703 if match:
704 scheme = match.group(1)
Guido van Rossumab0d1af1997-04-16 15:17:06 +0000705 return scheme, url[len(scheme) + 1:]
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000706 return None, url
707
Guido van Rossum332e1441997-09-29 23:23:46 +0000708_hostprog = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000709def splithost(url):
Guido van Rossum332e1441997-09-29 23:23:46 +0000710 global _hostprog
711 if _hostprog is None:
712 import re
713 _hostprog = re.compile('^//([^/]+)(.*)$')
714
715 match = _hostprog.match(url)
716 if match: return match.group(1, 2)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000717 return None, url
718
Guido van Rossum332e1441997-09-29 23:23:46 +0000719_userprog = None
Guido van Rossum7c395db1994-07-04 22:14:49 +0000720def splituser(host):
Guido van Rossum332e1441997-09-29 23:23:46 +0000721 global _userprog
722 if _userprog is None:
723 import re
724 _userprog = re.compile('^([^@]*)@(.*)$')
725
726 match = _userprog.match(host)
727 if match: return match.group(1, 2)
Guido van Rossum7c395db1994-07-04 22:14:49 +0000728 return None, host
729
Guido van Rossum332e1441997-09-29 23:23:46 +0000730_passwdprog = None
Guido van Rossum7c395db1994-07-04 22:14:49 +0000731def splitpasswd(user):
Guido van Rossum332e1441997-09-29 23:23:46 +0000732 global _passwdprog
733 if _passwdprog is None:
734 import re
735 _passwdprog = re.compile('^([^:]*):(.*)$')
736
Fred Drake654451d1997-10-14 13:30:57 +0000737 match = _passwdprog.match(user)
Guido van Rossum332e1441997-09-29 23:23:46 +0000738 if match: return match.group(1, 2)
Guido van Rossum7c395db1994-07-04 22:14:49 +0000739 return user, None
740
Guido van Rossum332e1441997-09-29 23:23:46 +0000741_portprog = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000742def splitport(host):
Guido van Rossum332e1441997-09-29 23:23:46 +0000743 global _portprog
744 if _portprog is None:
745 import re
746 _portprog = re.compile('^(.*):([0-9]+)$')
747
748 match = _portprog.match(host)
749 if match: return match.group(1, 2)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000750 return host, None
751
Guido van Rossum53725a21996-06-13 19:12:35 +0000752# Split host and port, returning numeric port.
753# Return given default port if no ':' found; defaults to -1.
Guido van Rossum84a00a81996-06-17 17:11:40 +0000754# Return numerical port if a valid number are found after ':'.
755# Return None if ':' but not a valid number.
Guido van Rossum332e1441997-09-29 23:23:46 +0000756_nportprog = None
Guido van Rossum53725a21996-06-13 19:12:35 +0000757def splitnport(host, defport=-1):
Guido van Rossum332e1441997-09-29 23:23:46 +0000758 global _nportprog
759 if _nportprog is None:
760 import re
761 _nportprog = re.compile('^(.*):(.*)$')
762
763 match = _nportprog.match(host)
764 if match:
765 host, port = match.group(1, 2)
Guido van Rossum84a00a81996-06-17 17:11:40 +0000766 try:
767 if not port: raise string.atoi_error, "no digits"
768 nport = string.atoi(port)
769 except string.atoi_error:
770 nport = None
Guido van Rossum53725a21996-06-13 19:12:35 +0000771 return host, nport
772 return host, defport
773
Guido van Rossum332e1441997-09-29 23:23:46 +0000774_queryprog = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000775def splitquery(url):
Guido van Rossum332e1441997-09-29 23:23:46 +0000776 global _queryprog
777 if _queryprog is None:
778 import re
779 _queryprog = re.compile('^(.*)\?([^?]*)$')
780
781 match = _queryprog.match(url)
782 if match: return match.group(1, 2)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000783 return url, None
784
Guido van Rossum332e1441997-09-29 23:23:46 +0000785_tagprog = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000786def splittag(url):
Guido van Rossum332e1441997-09-29 23:23:46 +0000787 global _tagprog
788 if _tagprog is None:
789 import re
790 _tagprog = re.compile('^(.*)#([^#]*)$')
791
792 match = _tagprog.match(url)
793 if match: return match.group(1, 2)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000794 return url, None
795
Guido van Rossum7c395db1994-07-04 22:14:49 +0000796def splitattr(url):
797 words = string.splitfields(url, ';')
798 return words[0], words[1:]
799
Guido van Rossum332e1441997-09-29 23:23:46 +0000800_valueprog = None
Guido van Rossum7c395db1994-07-04 22:14:49 +0000801def splitvalue(attr):
Guido van Rossum332e1441997-09-29 23:23:46 +0000802 global _valueprog
803 if _valueprog is None:
804 import re
805 _valueprog = re.compile('^([^=]*)=(.*)$')
806
807 match = _valueprog.match(attr)
808 if match: return match.group(1, 2)
Guido van Rossum7c395db1994-07-04 22:14:49 +0000809 return attr, None
810
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000811def splitgophertype(selector):
812 if selector[:1] == '/' and selector[1:2]:
813 return selector[1], selector[2:]
814 return None, selector
815
Guido van Rossum332e1441997-09-29 23:23:46 +0000816_quoteprog = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000817def unquote(s):
Guido van Rossum332e1441997-09-29 23:23:46 +0000818 global _quoteprog
819 if _quoteprog is None:
820 import re
821 _quoteprog = re.compile('%[0-9a-fA-F][0-9a-fA-F]')
822
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000823 i = 0
824 n = len(s)
Guido van Rossumf8abb381996-08-26 15:56:12 +0000825 res = []
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000826 while 0 <= i < n:
Guido van Rossum332e1441997-09-29 23:23:46 +0000827 match = _quoteprog.search(s, i)
828 if not match:
Guido van Rossumf8abb381996-08-26 15:56:12 +0000829 res.append(s[i:])
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000830 break
Guido van Rossum332e1441997-09-29 23:23:46 +0000831 j = match.start(0)
Guido van Rossumf8abb381996-08-26 15:56:12 +0000832 res.append(s[i:j] + chr(string.atoi(s[j+1:j+3], 16)))
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000833 i = j+3
Guido van Rossumf8abb381996-08-26 15:56:12 +0000834 return string.joinfields(res, '')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000835
Guido van Rossum0564e121996-12-13 14:47:36 +0000836def unquote_plus(s):
837 if '+' in s:
Guido van Rossum332e1441997-09-29 23:23:46 +0000838 # replace '+' with ' '
839 s = string.join(string.split(s, '+'), ' ')
Guido van Rossum0564e121996-12-13 14:47:36 +0000840 return unquote(s)
841
Guido van Rossum3bb54481994-08-29 10:52:58 +0000842always_safe = string.letters + string.digits + '_,.-'
Guido van Rossum7c395db1994-07-04 22:14:49 +0000843def quote(s, safe = '/'):
844 safe = always_safe + safe
Guido van Rossumf8abb381996-08-26 15:56:12 +0000845 res = []
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000846 for c in s:
Guido van Rossum7c395db1994-07-04 22:14:49 +0000847 if c in safe:
Guido van Rossumf8abb381996-08-26 15:56:12 +0000848 res.append(c)
Guido van Rossum7c395db1994-07-04 22:14:49 +0000849 else:
Guido van Rossumf8abb381996-08-26 15:56:12 +0000850 res.append('%%%02x' % ord(c))
851 return string.joinfields(res, '')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000852
Guido van Rossum0564e121996-12-13 14:47:36 +0000853def quote_plus(s, safe = '/'):
854 if ' ' in s:
Guido van Rossum332e1441997-09-29 23:23:46 +0000855 # replace ' ' with '+'
856 s = string.join(string.split(s, ' '), '+')
Guido van Rossum0564e121996-12-13 14:47:36 +0000857 return quote(s, safe + '+')
858 else:
859 return quote(s, safe)
860
Guido van Rossum442e7201996-03-20 15:33:11 +0000861
862# Proxy handling
863def getproxies():
864 """Return a dictionary of protocol scheme -> proxy server URL mappings.
865
866 Scan the environment for variables named <scheme>_proxy;
867 this seems to be the standard convention. If you need a
868 different way, you can pass a proxies dictionary to the
869 [Fancy]URLopener constructor.
870
871 """
872 proxies = {}
873 for name, value in os.environ.items():
Guido van Rossum1aec3f01997-05-28 15:37:19 +0000874 name = string.lower(name)
Guido van Rossum442e7201996-03-20 15:33:11 +0000875 if value and name[-6:] == '_proxy':
876 proxies[name[:-6]] = value
877 return proxies
878
879
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000880# Test and time quote() and unquote()
881def test1():
882 import time
883 s = ''
884 for i in range(256): s = s + chr(i)
885 s = s*4
886 t0 = time.time()
887 qs = quote(s)
888 uqs = unquote(qs)
889 t1 = time.time()
890 if uqs != s:
891 print 'Wrong!'
892 print `s`
893 print `qs`
894 print `uqs`
895 print round(t1 - t0, 3), 'sec'
896
897
898# Test program
899def test():
900 import sys
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000901 args = sys.argv[1:]
902 if not args:
903 args = [
904 '/etc/passwd',
905 'file:/etc/passwd',
906 'file://localhost/etc/passwd',
Guido van Rossum332e1441997-09-29 23:23:46 +0000907 'ftp://ftp.python.org/etc/passwd',
908 'gopher://gopher.micro.umn.edu/1/',
909 'http://www.python.org/index.html',
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000910 ]
911 try:
912 for url in args:
913 print '-'*10, url, '-'*10
914 fn, h = urlretrieve(url)
915 print fn, h
916 if h:
917 print '======'
918 for k in h.keys(): print k + ':', h[k]
919 print '======'
Guido van Rossumc511aee1997-04-11 19:01:48 +0000920 fp = open(fn, 'rb')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000921 data = fp.read()
922 del fp
Guido van Rossum332e1441997-09-29 23:23:46 +0000923 if '\r' in data:
924 table = string.maketrans("", "")
925 data = string.translate(data, table, "\r")
926 print data
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000927 fn, h = None, None
928 print '-'*40
929 finally:
930 urlcleanup()
931
932# Run test program when run as a script
933if __name__ == '__main__':
Guido van Rossum332e1441997-09-29 23:23:46 +0000934 test1()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000935 test()