blob: ad1e791386ccfdbc740d2db24600c089e20306f6 [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:]
365 key = (user, host, port, string.joinfields(dirs, '/'))
366 # XXX thread unsafe!
367 if len(self.ftpcache) > MAXFTPCACHE:
368 # Prune the cache, rather arbitrarily
369 for k in self.ftpcache.keys():
370 if k != key:
371 v = self.ftpcache[k]
372 del self.ftpcache[k]
373 v.close()
374 try:
375 if not self.ftpcache.has_key(key):
376 self.ftpcache[key] = \
377 ftpwrapper(user, passwd, host, port, dirs)
378 if not file: type = 'D'
379 else: type = 'I'
380 for attr in attrs:
381 attr, value = splitvalue(attr)
382 if string.lower(attr) == 'type' and \
383 value in ('a', 'A', 'i', 'I', 'd', 'D'):
384 type = string.upper(value)
385 (fp, retrlen) = self.ftpcache[key].retrfile(file, type)
386 if retrlen is not None and retrlen >= 0:
387 import mimetools, StringIO
388 headers = mimetools.Message(StringIO.StringIO(
389 'Content-Length: %d\n' % retrlen))
390 else:
391 headers = noheaders()
392 return addinfourl(fp, headers, "ftp:" + url)
393 except ftperrors(), msg:
394 raise IOError, ('ftp error', msg), sys.exc_info()[2]
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000395
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000396 # Use "data" URL
397 def open_data(self, url, data=None):
398 # ignore POSTed data
399 #
400 # syntax of data URLs:
401 # dataurl := "data:" [ mediatype ] [ ";base64" ] "," data
402 # mediatype := [ type "/" subtype ] *( ";" parameter )
403 # data := *urlchar
404 # parameter := attribute "=" value
405 import StringIO, mimetools, time
406 try:
407 [type, data] = string.split(url, ',', 1)
408 except ValueError:
409 raise IOError, ('data error', 'bad data URL')
410 if not type:
411 type = 'text/plain;charset=US-ASCII'
412 semi = string.rfind(type, ';')
413 if semi >= 0 and '=' not in type[semi:]:
414 encoding = type[semi+1:]
415 type = type[:semi]
416 else:
417 encoding = ''
418 msg = []
419 msg.append('Date: %s'%time.strftime('%a, %d %b %Y %T GMT',
420 time.gmtime(time.time())))
421 msg.append('Content-type: %s' % type)
422 if encoding == 'base64':
423 import base64
424 data = base64.decodestring(data)
425 else:
426 data = unquote(data)
427 msg.append('Content-length: %d' % len(data))
428 msg.append('')
429 msg.append(data)
430 msg = string.join(msg, '\n')
431 f = StringIO.StringIO(msg)
432 headers = mimetools.Message(f, 0)
433 f.fileno = None # needed for addinfourl
434 return addinfourl(f, headers, url)
Guido van Rossum6d4d1c21998-03-12 14:32:55 +0000435
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000436
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000437# Derived class with handlers for errors we can handle (perhaps)
438class FancyURLopener(URLopener):
439
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000440 def __init__(self, *args):
441 apply(URLopener.__init__, (self,) + args)
442 self.auth_cache = {}
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000443
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000444 # Default error handling -- don't raise an exception
445 def http_error_default(self, url, fp, errcode, errmsg, headers):
446 return addinfourl(fp, headers, "http:" + url)
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000447
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000448 # Error 302 -- relocated (temporarily)
449 def http_error_302(self, url, fp, errcode, errmsg, headers,
450 data=None):
451 # XXX The server can force infinite recursion here!
452 if headers.has_key('location'):
453 newurl = headers['location']
454 elif headers.has_key('uri'):
455 newurl = headers['uri']
456 else:
457 return
458 void = fp.read()
459 fp.close()
Guido van Rossum3527f591999-03-29 20:23:41 +0000460 # In case the server sent a relative URL, join with original:
461 newurl = basejoin("http:" + url, newurl)
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000462 return self.open(newurl, data)
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000463
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000464 # Error 301 -- also relocated (permanently)
465 http_error_301 = http_error_302
Guido van Rossume6ad8911996-09-10 17:02:56 +0000466
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000467 # Error 401 -- authentication required
468 # See this URL for a description of the basic authentication scheme:
469 # http://www.ics.uci.edu/pub/ietf/http/draft-ietf-http-v10-spec-00.txt
470 def http_error_401(self, url, fp, errcode, errmsg, headers,
471 data=None):
472 if headers.has_key('www-authenticate'):
473 stuff = headers['www-authenticate']
474 import re
475 match = re.match('[ \t]*([^ \t]+)[ \t]+realm="([^"]*)"', stuff)
476 if match:
477 scheme, realm = match.groups()
478 if string.lower(scheme) == 'basic':
479 return self.retry_http_basic_auth(url, realm, data)
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000480
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000481 def retry_http_basic_auth(self, url, realm, data):
482 host, selector = splithost(url)
483 i = string.find(host, '@') + 1
484 host = host[i:]
485 user, passwd = self.get_user_passwd(host, realm, i)
486 if not (user or passwd): return None
487 host = user + ':' + passwd + '@' + host
488 newurl = 'http://' + host + selector
489 return self.open(newurl, data)
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000490
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000491 def get_user_passwd(self, host, realm, clear_cache = 0):
492 key = realm + '@' + string.lower(host)
493 if self.auth_cache.has_key(key):
494 if clear_cache:
495 del self.auth_cache[key]
496 else:
497 return self.auth_cache[key]
498 user, passwd = self.prompt_user_passwd(host, realm)
499 if user or passwd: self.auth_cache[key] = (user, passwd)
500 return user, passwd
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000501
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000502 def prompt_user_passwd(self, host, realm):
503 # Override this in a GUI environment!
504 import getpass
505 try:
506 user = raw_input("Enter username for %s at %s: " % (realm,
507 host))
508 passwd = getpass.getpass("Enter password for %s in %s at %s: " %
509 (user, realm, host))
510 return user, passwd
511 except KeyboardInterrupt:
512 print
513 return None, None
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000514
515
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000516# Utility functions
517
518# Return the IP address of the magic hostname 'localhost'
519_localhost = None
520def localhost():
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000521 global _localhost
522 if not _localhost:
523 _localhost = socket.gethostbyname('localhost')
524 return _localhost
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000525
526# Return the IP address of the current host
527_thishost = None
528def thishost():
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000529 global _thishost
530 if not _thishost:
531 _thishost = socket.gethostbyname(socket.gethostname())
532 return _thishost
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000533
534# Return the set of errors raised by the FTP class
535_ftperrors = None
536def ftperrors():
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000537 global _ftperrors
538 if not _ftperrors:
539 import ftplib
540 _ftperrors = ftplib.all_errors
541 return _ftperrors
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000542
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000543# Return an empty mimetools.Message object
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000544_noheaders = None
545def noheaders():
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000546 global _noheaders
547 if not _noheaders:
548 import mimetools
549 import StringIO
550 _noheaders = mimetools.Message(StringIO.StringIO(), 0)
551 _noheaders.fp.close() # Recycle file descriptor
552 return _noheaders
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000553
554
555# Utility classes
556
557# Class used by open_ftp() for cache of open FTP connections
558class ftpwrapper:
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000559 def __init__(self, user, passwd, host, port, dirs):
560 self.user = user
561 self.passwd = passwd
562 self.host = host
563 self.port = port
564 self.dirs = dirs
565 self.init()
566 def init(self):
567 import ftplib
568 self.busy = 0
569 self.ftp = ftplib.FTP()
570 self.ftp.connect(self.host, self.port)
571 self.ftp.login(self.user, self.passwd)
572 for dir in self.dirs:
573 self.ftp.cwd(dir)
574 def retrfile(self, file, type):
575 import ftplib
576 self.endtransfer()
577 if type in ('d', 'D'): cmd = 'TYPE A'; isdir = 1
578 else: cmd = 'TYPE ' + type; isdir = 0
579 try:
580 self.ftp.voidcmd(cmd)
581 except ftplib.all_errors:
582 self.init()
583 self.ftp.voidcmd(cmd)
584 conn = None
585 if file and not isdir:
586 # Use nlst to see if the file exists at all
587 try:
588 self.ftp.nlst(file)
589 except ftplib.error_perm, reason:
590 raise IOError, ('ftp error', reason), sys.exc_info()[2]
591 # Restore the transfer mode!
592 self.ftp.voidcmd(cmd)
593 # Try to retrieve as a file
594 try:
595 cmd = 'RETR ' + file
596 conn = self.ftp.ntransfercmd(cmd)
597 except ftplib.error_perm, reason:
598 if reason[:3] != '550':
599 raise IOError, ('ftp error', reason), sys.exc_info()[2]
600 if not conn:
601 # Set transfer mode to ASCII!
602 self.ftp.voidcmd('TYPE A')
603 # Try a directory listing
604 if file: cmd = 'LIST ' + file
605 else: cmd = 'LIST'
606 conn = self.ftp.ntransfercmd(cmd)
607 self.busy = 1
608 # Pass back both a suitably decorated object and a retrieval length
609 return (addclosehook(conn[0].makefile('rb'),
610 self.endtransfer), conn[1])
611 def endtransfer(self):
612 if not self.busy:
613 return
614 self.busy = 0
615 try:
616 self.ftp.voidresp()
617 except ftperrors():
618 pass
619 def close(self):
620 self.endtransfer()
621 try:
622 self.ftp.close()
623 except ftperrors():
624 pass
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000625
626# Base class for addinfo and addclosehook
627class addbase:
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000628 def __init__(self, fp):
629 self.fp = fp
630 self.read = self.fp.read
631 self.readline = self.fp.readline
632 self.readlines = self.fp.readlines
633 self.fileno = self.fp.fileno
634 def __repr__(self):
635 return '<%s at %s whose fp = %s>' % (self.__class__.__name__,
636 `id(self)`, `self.fp`)
637 def close(self):
638 self.read = None
639 self.readline = None
640 self.readlines = None
641 self.fileno = None
642 if self.fp: self.fp.close()
643 self.fp = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000644
645# Class to add a close hook to an open file
646class addclosehook(addbase):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000647 def __init__(self, fp, closehook, *hookargs):
648 addbase.__init__(self, fp)
649 self.closehook = closehook
650 self.hookargs = hookargs
651 def close(self):
652 if self.closehook:
653 apply(self.closehook, self.hookargs)
654 self.closehook = None
655 self.hookargs = None
656 addbase.close(self)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000657
658# class to add an info() method to an open file
659class addinfo(addbase):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000660 def __init__(self, fp, headers):
661 addbase.__init__(self, fp)
662 self.headers = headers
663 def info(self):
664 return self.headers
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000665
Guido van Rossume6ad8911996-09-10 17:02:56 +0000666# class to add info() and geturl() methods to an open file
667class addinfourl(addbase):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000668 def __init__(self, fp, headers, url):
669 addbase.__init__(self, fp)
670 self.headers = headers
671 self.url = url
672 def info(self):
673 return self.headers
674 def geturl(self):
675 return self.url
Guido van Rossume6ad8911996-09-10 17:02:56 +0000676
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000677
678# Utility to combine a URL with a base URL to form a new URL
679
680def basejoin(base, url):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000681 type, path = splittype(url)
682 if type:
683 # if url is complete (i.e., it contains a type), return it
684 return url
685 host, path = splithost(path)
686 type, basepath = splittype(base) # inherit type from base
687 if host:
688 # if url contains host, just inherit type
689 if type: return type + '://' + host + path
690 else:
691 # no type inherited, so url must have started with //
692 # just return it
693 return url
694 host, basepath = splithost(basepath) # inherit host
695 basepath, basetag = splittag(basepath) # remove extraneuous cruft
696 basepath, basequery = splitquery(basepath) # idem
697 if path[:1] != '/':
698 # non-absolute path name
699 if path[:1] in ('#', '?'):
700 # path is just a tag or query, attach to basepath
701 i = len(basepath)
702 else:
703 # else replace last component
704 i = string.rfind(basepath, '/')
705 if i < 0:
706 # basepath not absolute
707 if host:
708 # host present, make absolute
709 basepath = '/'
710 else:
711 # else keep non-absolute
712 basepath = ''
713 else:
714 # remove last file component
715 basepath = basepath[:i+1]
716 # Interpret ../ (important because of symlinks)
717 while basepath and path[:3] == '../':
718 path = path[3:]
719 i = string.rfind(basepath[:-1], '/')
720 if i > 0:
721 basepath = basepath[:i+1]
722 elif i == 0:
723 basepath = '/'
724 break
725 else:
726 basepath = ''
727
728 path = basepath + path
729 if type and host: return type + '://' + host + path
730 elif type: return type + ':' + path
731 elif host: return '//' + host + path # don't know what this means
732 else: return path
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000733
734
Guido van Rossum7c395db1994-07-04 22:14:49 +0000735# Utilities to parse URLs (most of these return None for missing parts):
Sjoerd Mullendere0371b81995-11-10 10:36:07 +0000736# unwrap('<URL:type://host/path>') --> 'type://host/path'
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000737# splittype('type:opaquestring') --> 'type', 'opaquestring'
738# splithost('//host[:port]/path') --> 'host[:port]', '/path'
Guido van Rossum7c395db1994-07-04 22:14:49 +0000739# splituser('user[:passwd]@host[:port]') --> 'user[:passwd]', 'host[:port]'
740# splitpasswd('user:passwd') -> 'user', 'passwd'
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000741# splitport('host:port') --> 'host', 'port'
742# splitquery('/path?query') --> '/path', 'query'
743# splittag('/path#tag') --> '/path', 'tag'
Guido van Rossum7c395db1994-07-04 22:14:49 +0000744# splitattr('/path;attr1=value1;attr2=value2;...') ->
745# '/path', ['attr1=value1', 'attr2=value2', ...]
746# splitvalue('attr=value') --> 'attr', 'value'
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000747# splitgophertype('/Xselector') --> 'X', 'selector'
748# unquote('abc%20def') -> 'abc def'
749# quote('abc def') -> 'abc%20def')
750
751def unwrap(url):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000752 url = string.strip(url)
753 if url[:1] == '<' and url[-1:] == '>':
754 url = string.strip(url[1:-1])
755 if url[:4] == 'URL:': url = string.strip(url[4:])
756 return url
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000757
Guido van Rossum332e1441997-09-29 23:23:46 +0000758_typeprog = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000759def splittype(url):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000760 global _typeprog
761 if _typeprog is None:
762 import re
763 _typeprog = re.compile('^([^/:]+):')
Guido van Rossum332e1441997-09-29 23:23:46 +0000764
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000765 match = _typeprog.match(url)
766 if match:
767 scheme = match.group(1)
768 return scheme, url[len(scheme) + 1:]
769 return None, url
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000770
Guido van Rossum332e1441997-09-29 23:23:46 +0000771_hostprog = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000772def splithost(url):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000773 global _hostprog
774 if _hostprog is None:
775 import re
Guido van Rossum3427c1f1999-07-01 23:20:56 +0000776 _hostprog = re.compile('^//([^/]*)(.*)$')
Guido van Rossum332e1441997-09-29 23:23:46 +0000777
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000778 match = _hostprog.match(url)
779 if match: return match.group(1, 2)
780 return None, url
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000781
Guido van Rossum332e1441997-09-29 23:23:46 +0000782_userprog = None
Guido van Rossum7c395db1994-07-04 22:14:49 +0000783def splituser(host):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000784 global _userprog
785 if _userprog is None:
786 import re
787 _userprog = re.compile('^([^@]*)@(.*)$')
Guido van Rossum332e1441997-09-29 23:23:46 +0000788
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000789 match = _userprog.match(host)
790 if match: return match.group(1, 2)
791 return None, host
Guido van Rossum7c395db1994-07-04 22:14:49 +0000792
Guido van Rossum332e1441997-09-29 23:23:46 +0000793_passwdprog = None
Guido van Rossum7c395db1994-07-04 22:14:49 +0000794def splitpasswd(user):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000795 global _passwdprog
796 if _passwdprog is None:
797 import re
798 _passwdprog = re.compile('^([^:]*):(.*)$')
Guido van Rossum332e1441997-09-29 23:23:46 +0000799
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000800 match = _passwdprog.match(user)
801 if match: return match.group(1, 2)
802 return user, None
Guido van Rossum7c395db1994-07-04 22:14:49 +0000803
Guido van Rossum332e1441997-09-29 23:23:46 +0000804_portprog = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000805def splitport(host):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000806 global _portprog
807 if _portprog is None:
808 import re
809 _portprog = re.compile('^(.*):([0-9]+)$')
Guido van Rossum332e1441997-09-29 23:23:46 +0000810
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000811 match = _portprog.match(host)
812 if match: return match.group(1, 2)
813 return host, None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000814
Guido van Rossum53725a21996-06-13 19:12:35 +0000815# Split host and port, returning numeric port.
816# Return given default port if no ':' found; defaults to -1.
Guido van Rossum84a00a81996-06-17 17:11:40 +0000817# Return numerical port if a valid number are found after ':'.
818# Return None if ':' but not a valid number.
Guido van Rossum332e1441997-09-29 23:23:46 +0000819_nportprog = None
Guido van Rossum53725a21996-06-13 19:12:35 +0000820def splitnport(host, defport=-1):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000821 global _nportprog
822 if _nportprog is None:
823 import re
824 _nportprog = re.compile('^(.*):(.*)$')
Guido van Rossum7e7ca0b1998-03-26 21:01:39 +0000825
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000826 match = _nportprog.match(host)
827 if match:
828 host, port = match.group(1, 2)
829 try:
830 if not port: raise string.atoi_error, "no digits"
831 nport = string.atoi(port)
832 except string.atoi_error:
833 nport = None
834 return host, nport
835 return host, defport
Guido van Rossum53725a21996-06-13 19:12:35 +0000836
Guido van Rossum332e1441997-09-29 23:23:46 +0000837_queryprog = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000838def splitquery(url):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000839 global _queryprog
840 if _queryprog is None:
841 import re
842 _queryprog = re.compile('^(.*)\?([^?]*)$')
Guido van Rossum332e1441997-09-29 23:23:46 +0000843
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000844 match = _queryprog.match(url)
845 if match: return match.group(1, 2)
846 return url, None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000847
Guido van Rossum332e1441997-09-29 23:23:46 +0000848_tagprog = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000849def splittag(url):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000850 global _tagprog
851 if _tagprog is None:
852 import re
853 _tagprog = re.compile('^(.*)#([^#]*)$')
Guido van Rossum7e7ca0b1998-03-26 21:01:39 +0000854
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000855 match = _tagprog.match(url)
856 if match: return match.group(1, 2)
857 return url, None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000858
Guido van Rossum7c395db1994-07-04 22:14:49 +0000859def splitattr(url):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000860 words = string.splitfields(url, ';')
861 return words[0], words[1:]
Guido van Rossum7c395db1994-07-04 22:14:49 +0000862
Guido van Rossum332e1441997-09-29 23:23:46 +0000863_valueprog = None
Guido van Rossum7c395db1994-07-04 22:14:49 +0000864def splitvalue(attr):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000865 global _valueprog
866 if _valueprog is None:
867 import re
868 _valueprog = re.compile('^([^=]*)=(.*)$')
Guido van Rossum332e1441997-09-29 23:23:46 +0000869
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000870 match = _valueprog.match(attr)
871 if match: return match.group(1, 2)
872 return attr, None
Guido van Rossum7c395db1994-07-04 22:14:49 +0000873
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000874def splitgophertype(selector):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000875 if selector[:1] == '/' and selector[1:2]:
876 return selector[1], selector[2:]
877 return None, selector
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000878
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000879def unquote(s):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000880 mychr = chr
881 myatoi = string.atoi
882 list = string.split(s, '%')
883 res = [list[0]]
884 myappend = res.append
885 del list[0]
886 for item in list:
887 if item[1:2]:
888 try:
889 myappend(mychr(myatoi(item[:2], 16))
890 + item[2:])
891 except:
892 myappend('%' + item)
893 else:
894 myappend('%' + item)
895 return string.join(res, "")
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000896
Guido van Rossum0564e121996-12-13 14:47:36 +0000897def unquote_plus(s):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000898 if '+' in s:
899 # replace '+' with ' '
900 s = string.join(string.split(s, '+'), ' ')
901 return unquote(s)
Guido van Rossum0564e121996-12-13 14:47:36 +0000902
Guido van Rossum3bb54481994-08-29 10:52:58 +0000903always_safe = string.letters + string.digits + '_,.-'
Guido van Rossum7c395db1994-07-04 22:14:49 +0000904def quote(s, safe = '/'):
Guido van Rossum0dee4ee1999-06-09 15:14:50 +0000905 # XXX Can speed this up an order of magnitude
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000906 safe = always_safe + safe
907 res = list(s)
908 for i in range(len(res)):
909 c = res[i]
910 if c not in safe:
911 res[i] = '%%%02x' % ord(c)
912 return string.joinfields(res, '')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000913
Guido van Rossum0564e121996-12-13 14:47:36 +0000914def quote_plus(s, safe = '/'):
Guido van Rossum0dee4ee1999-06-09 15:14:50 +0000915 # XXX Can speed this up an order of magnitude
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000916 if ' ' in s:
917 # replace ' ' with '+'
918 l = string.split(s, ' ')
919 for i in range(len(l)):
920 l[i] = quote(l[i], safe)
921 return string.join(l, '+')
922 else:
923 return quote(s, safe)
Guido van Rossum0564e121996-12-13 14:47:36 +0000924
Guido van Rossum810a3391998-07-22 21:33:23 +0000925def urlencode(dict):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000926 l = []
927 for k, v in dict.items():
928 k = quote_plus(str(k))
929 v = quote_plus(str(v))
930 l.append(k + '=' + v)
931 return string.join(l, '&')
Guido van Rossum810a3391998-07-22 21:33:23 +0000932
Guido van Rossum442e7201996-03-20 15:33:11 +0000933
934# Proxy handling
Guido van Rossum4163e701998-08-06 13:39:09 +0000935if os.name == 'mac':
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000936 def getproxies():
937 """Return a dictionary of scheme -> proxy server URL mappings.
Guido van Rossum442e7201996-03-20 15:33:11 +0000938
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000939 By convention the mac uses Internet Config to store
940 proxies. An HTTP proxy, for instance, is stored under
941 the HttpProxy key.
Guido van Rossum442e7201996-03-20 15:33:11 +0000942
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000943 """
944 try:
945 import ic
946 except ImportError:
947 return {}
948
949 try:
950 config = ic.IC()
951 except ic.error:
952 return {}
953 proxies = {}
954 # HTTP:
955 if config.has_key('UseHTTPProxy') and config['UseHTTPProxy']:
956 try:
957 value = config['HTTPProxyHost']
958 except ic.error:
959 pass
960 else:
961 proxies['http'] = 'http://%s' % value
962 # FTP: XXXX To be done.
963 # Gopher: XXXX To be done.
964 return proxies
965
Guido van Rossum4163e701998-08-06 13:39:09 +0000966else:
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000967 def getproxies():
968 """Return a dictionary of scheme -> proxy server URL mappings.
969
970 Scan the environment for variables named <scheme>_proxy;
971 this seems to be the standard convention. If you need a
972 different way, you can pass a proxies dictionary to the
973 [Fancy]URLopener constructor.
974
975 """
976 proxies = {}
977 for name, value in os.environ.items():
978 name = string.lower(name)
979 if value and name[-6:] == '_proxy':
980 proxies[name[:-6]] = value
981 return proxies
Guido van Rossum442e7201996-03-20 15:33:11 +0000982
983
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000984# Test and time quote() and unquote()
985def test1():
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000986 import time
987 s = ''
988 for i in range(256): s = s + chr(i)
989 s = s*4
990 t0 = time.time()
991 qs = quote(s)
992 uqs = unquote(qs)
993 t1 = time.time()
994 if uqs != s:
995 print 'Wrong!'
996 print `s`
997 print `qs`
998 print `uqs`
999 print round(t1 - t0, 3), 'sec'
Guido van Rossum7c6ebb51994-03-22 12:05:32 +00001000
1001
Guido van Rossum9ab96d41998-09-28 14:07:00 +00001002def reporthook(blocknum, blocksize, totalsize):
1003 # Report during remote transfers
1004 print "Block number: %d, Block size: %d, Total size: %d" % (blocknum, blocksize, totalsize)
1005
Guido van Rossum7c6ebb51994-03-22 12:05:32 +00001006# Test program
Guido van Rossum23490151998-06-25 02:39:00 +00001007def test(args=[]):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001008 if not args:
1009 args = [
1010 '/etc/passwd',
1011 'file:/etc/passwd',
1012 'file://localhost/etc/passwd',
1013 'ftp://ftp.python.org/etc/passwd',
1014## 'gopher://gopher.micro.umn.edu/1/',
1015 'http://www.python.org/index.html',
1016 ]
1017 try:
1018 for url in args:
1019 print '-'*10, url, '-'*10
1020 fn, h = urlretrieve(url, None, reporthook)
1021 print fn, h
1022 if h:
1023 print '======'
1024 for k in h.keys(): print k + ':', h[k]
1025 print '======'
1026 fp = open(fn, 'rb')
1027 data = fp.read()
1028 del fp
1029 if '\r' in data:
1030 table = string.maketrans("", "")
1031 data = string.translate(data, table, "\r")
1032 print data
1033 fn, h = None, None
1034 print '-'*40
1035 finally:
1036 urlcleanup()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +00001037
Guido van Rossum23490151998-06-25 02:39:00 +00001038def main():
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001039 import getopt, sys
1040 try:
1041 opts, args = getopt.getopt(sys.argv[1:], "th")
1042 except getopt.error, msg:
1043 print msg
1044 print "Use -h for help"
1045 return
1046 t = 0
1047 for o, a in opts:
1048 if o == '-t':
1049 t = t + 1
1050 if o == '-h':
1051 print "Usage: python urllib.py [-t] [url ...]"
1052 print "-t runs self-test;",
1053 print "otherwise, contents of urls are printed"
1054 return
1055 if t:
1056 if t > 1:
1057 test1()
1058 test(args)
1059 else:
1060 if not args:
1061 print "Use -h for help"
1062 for url in args:
1063 print urlopen(url).read(),
Guido van Rossum23490151998-06-25 02:39:00 +00001064
Guido van Rossum7c6ebb51994-03-22 12:05:32 +00001065# Run test program when run as a script
1066if __name__ == '__main__':
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001067 main()