blob: ceacc61303dcc4cbe7a1ba62dd56eacbafbcfb31 [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
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):
41 return pathname
42 def pathname2url(pathname):
43 return pathname
Guido van Rossum6cb15a01995-06-22 19:00:13 +000044
Guido van Rossum33add0a1998-12-18 15:25:22 +000045_url2pathname = url2pathname
46def url2pathname(url):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +000047 return _url2pathname(unquote(url))
Guido van Rossum33add0a1998-12-18 15:25:22 +000048_pathname2url = pathname2url
49def pathname2url(p):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +000050 return quote(_pathname2url(p))
Guido van Rossum33add0a1998-12-18 15:25:22 +000051
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000052# This really consists of two pieces:
53# (1) a class which handles opening of all sorts of URLs
54# (plus assorted utilities etc.)
55# (2) a set of functions for parsing URLs
56# XXX Should these be separated out into different modules?
57
58
59# Shortcut for basic usage
60_urlopener = None
Guido van Rossumbd013741996-12-10 16:00:28 +000061def urlopen(url, data=None):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +000062 global _urlopener
63 if not _urlopener:
64 _urlopener = FancyURLopener()
65 if data is None:
66 return _urlopener.open(url)
67 else:
68 return _urlopener.open(url, data)
Guido van Rossum9ab96d41998-09-28 14:07:00 +000069def urlretrieve(url, filename=None, reporthook=None):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +000070 global _urlopener
71 if not _urlopener:
72 _urlopener = FancyURLopener()
73 return _urlopener.retrieve(url, filename, reporthook)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000074def urlcleanup():
Jeremy Hyltonf90b0021999-02-25 16:12:12 +000075 if _urlopener:
76 _urlopener.cleanup()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000077
78
79# Class to open URLs.
80# This is a class rather than just a subroutine because we may need
81# more than one set of global protocol-specific options.
Guido van Rossumbbb0a051995-08-04 04:29:05 +000082# Note -- this is a base class for those who don't want the
83# automatic handling of errors type 302 (relocated) and 401
84# (authorization needed).
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000085ftpcache = {}
86class URLopener:
87
Jeremy Hyltonf90b0021999-02-25 16:12:12 +000088 __tempfiles = None
Guido van Rossum29e77811996-11-27 19:39:58 +000089
Jeremy Hyltonf90b0021999-02-25 16:12:12 +000090 # Constructor
91 def __init__(self, proxies=None):
92 if proxies is None:
93 proxies = getproxies()
94 assert hasattr(proxies, 'has_key'), "proxies must be a mapping"
95 self.proxies = proxies
96 server_version = "Python-urllib/%s" % __version__
97 self.addheaders = [('User-agent', server_version)]
98 self.__tempfiles = []
99 self.__unlink = os.unlink # See cleanup()
100 self.tempcache = None
101 # Undocumented feature: if you assign {} to tempcache,
102 # it is used to cache files retrieved with
103 # self.retrieve(). This is not enabled by default
104 # since it does not work for changing documents (and I
105 # haven't got the logic to check expiration headers
106 # yet).
107 self.ftpcache = ftpcache
108 # Undocumented feature: you can use a different
109 # ftp cache by assigning to the .ftpcache member;
110 # in case you want logically independent URL openers
111 # XXX This is not threadsafe. Bah.
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000112
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000113 def __del__(self):
114 self.close()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000115
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000116 def close(self):
117 self.cleanup()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000118
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000119 def cleanup(self):
120 # This code sometimes runs when the rest of this module
121 # has already been deleted, so it can't use any globals
122 # or import anything.
123 if self.__tempfiles:
124 for file in self.__tempfiles:
125 try:
126 self.__unlink(file)
127 except:
128 pass
129 del self.__tempfiles[:]
130 if self.tempcache:
131 self.tempcache.clear()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000132
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000133 # Add a header to be used by the HTTP interface only
134 # e.g. u.addheader('Accept', 'sound/basic')
135 def addheader(self, *args):
136 self.addheaders.append(args)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000137
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000138 # External interface
139 # Use URLopener().open(file) instead of open(file, 'r')
140 def open(self, fullurl, data=None):
141 fullurl = unwrap(fullurl)
142 if self.tempcache and self.tempcache.has_key(fullurl):
143 filename, headers = self.tempcache[fullurl]
144 fp = open(filename, 'rb')
145 return addinfourl(fp, headers, fullurl)
146 type, url = splittype(fullurl)
147 if not type: type = 'file'
148 if self.proxies.has_key(type):
149 proxy = self.proxies[type]
150 type, proxy = splittype(proxy)
151 host, selector = splithost(proxy)
152 url = (host, fullurl) # Signal special case to open_*()
153 name = 'open_' + type
154 if '-' in name:
155 # replace - with _
156 name = string.join(string.split(name, '-'), '_')
157 if not hasattr(self, name):
158 if data is None:
159 return self.open_unknown(fullurl)
160 else:
161 return self.open_unknown(fullurl, data)
162 try:
163 if data is None:
164 return getattr(self, name)(url)
165 else:
166 return getattr(self, name)(url, data)
167 except socket.error, msg:
168 raise IOError, ('socket error', msg), sys.exc_info()[2]
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000169
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000170 # Overridable interface to open unknown URL type
171 def open_unknown(self, fullurl, data=None):
172 type, url = splittype(fullurl)
173 raise IOError, ('url error', 'unknown url type', type)
Guido van Rossumca445401995-08-29 19:19:12 +0000174
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000175 # External interface
176 # retrieve(url) returns (filename, None) for a local object
177 # or (tempfilename, headers) for a remote object
178 def retrieve(self, url, filename=None, reporthook=None):
179 url = unwrap(url)
180 if self.tempcache and self.tempcache.has_key(url):
181 return self.tempcache[url]
182 type, url1 = splittype(url)
183 if not filename and (not type or type == 'file'):
184 try:
185 fp = self.open_local_file(url1)
186 hdrs = fp.info()
187 del fp
188 return url2pathname(splithost(url1)[1]), hdrs
189 except IOError, msg:
190 pass
191 fp = self.open(url)
192 headers = fp.info()
193 if not filename:
194 import tempfile
195 garbage, path = splittype(url)
196 garbage, path = splithost(path or "")
197 path, garbage = splitquery(path or "")
198 path, garbage = splitattr(path or "")
199 suffix = os.path.splitext(path)[1]
200 filename = tempfile.mktemp(suffix)
201 self.__tempfiles.append(filename)
202 result = filename, headers
203 if self.tempcache is not None:
204 self.tempcache[url] = result
205 tfp = open(filename, 'wb')
206 bs = 1024*8
207 size = -1
208 blocknum = 1
209 if reporthook:
210 if headers.has_key("content-length"):
211 size = int(headers["Content-Length"])
212 reporthook(0, bs, size)
213 block = fp.read(bs)
214 if reporthook:
215 reporthook(1, bs, size)
216 while block:
217 tfp.write(block)
218 block = fp.read(bs)
219 blocknum = blocknum + 1
220 if reporthook:
221 reporthook(blocknum, bs, size)
222 fp.close()
223 tfp.close()
224 del fp
225 del tfp
226 return result
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000227
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000228 # Each method named open_<type> knows how to open that type of URL
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000229
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000230 # Use HTTP protocol
231 def open_http(self, url, data=None):
232 import httplib
233 user_passwd = None
234 if type(url) is type(""):
235 host, selector = splithost(url)
236 if host:
237 user_passwd, host = splituser(host)
238 host = unquote(host)
239 realhost = host
240 else:
241 host, selector = url
242 urltype, rest = splittype(selector)
243 url = rest
244 user_passwd = None
245 if string.lower(urltype) != 'http':
246 realhost = None
247 else:
248 realhost, rest = splithost(rest)
249 if realhost:
250 user_passwd, realhost = splituser(realhost)
251 if user_passwd:
252 selector = "%s://%s%s" % (urltype, realhost, rest)
253 #print "proxy via http:", host, selector
254 if not host: raise IOError, ('http error', 'no host given')
255 if user_passwd:
256 import base64
257 auth = string.strip(base64.encodestring(user_passwd))
258 else:
259 auth = None
260 h = httplib.HTTP(host)
261 if data is not None:
262 h.putrequest('POST', selector)
263 h.putheader('Content-type', 'application/x-www-form-urlencoded')
264 h.putheader('Content-length', '%d' % len(data))
265 else:
266 h.putrequest('GET', selector)
267 if auth: h.putheader('Authorization', 'Basic %s' % auth)
268 if realhost: h.putheader('Host', realhost)
269 for args in self.addheaders: apply(h.putheader, args)
270 h.endheaders()
271 if data is not None:
272 h.send(data + '\r\n')
273 errcode, errmsg, headers = h.getreply()
274 fp = h.getfile()
275 if errcode == 200:
276 return addinfourl(fp, headers, "http:" + url)
277 else:
278 if data is None:
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000279 return self.http_error(url, fp, errcode, errmsg, headers)
Guido van Rossum29aab751999-03-09 19:31:21 +0000280 else:
281 return self.http_error(url, fp, errcode, errmsg, headers, data)
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000282
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000283 # Handle http errors.
284 # Derived class can override this, or provide specific handlers
285 # named http_error_DDD where DDD is the 3-digit error code
286 def http_error(self, url, fp, errcode, errmsg, headers, data=None):
287 # First check if there's a specific handler for this error
288 name = 'http_error_%d' % errcode
289 if hasattr(self, name):
290 method = getattr(self, name)
291 if data is None:
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000292 result = method(url, fp, errcode, errmsg, headers)
Jeremy Hyltonb30f52a1999-02-25 16:14:58 +0000293 else:
294 result = method(url, fp, errcode, errmsg, headers, data)
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000295 if result: return result
Jeremy Hyltonb30f52a1999-02-25 16:14:58 +0000296 return self.http_error_default(url, fp, errcode, errmsg, headers)
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000297
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000298 # Default http error handler: close the connection and raises IOError
299 def http_error_default(self, url, fp, errcode, errmsg, headers):
300 void = fp.read()
301 fp.close()
302 raise IOError, ('http error', errcode, errmsg, headers)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000303
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000304 # Use Gopher protocol
305 def open_gopher(self, url):
306 import gopherlib
307 host, selector = splithost(url)
308 if not host: raise IOError, ('gopher error', 'no host given')
309 host = unquote(host)
310 type, selector = splitgophertype(selector)
311 selector, query = splitquery(selector)
312 selector = unquote(selector)
313 if query:
314 query = unquote(query)
315 fp = gopherlib.send_query(selector, query, host)
316 else:
317 fp = gopherlib.send_selector(selector, host)
318 return addinfourl(fp, noheaders(), "gopher:" + url)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000319
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000320 # Use local file or FTP depending on form of URL
321 def open_file(self, url):
322 if url[:2] == '//' and url[2:3] != '/':
323 return self.open_ftp(url)
324 else:
325 return self.open_local_file(url)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000326
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000327 # Use local file
328 def open_local_file(self, url):
329 import mimetypes, mimetools, StringIO
330 mtype = mimetypes.guess_type(url)[0]
331 headers = mimetools.Message(StringIO.StringIO(
332 'Content-Type: %s\n' % (mtype or 'text/plain')))
333 host, file = splithost(url)
334 if not host:
335 return addinfourl(open(url2pathname(file), 'rb'),
336 headers, 'file:'+pathname2url(file))
337 host, port = splitport(host)
338 if not port \
339 and socket.gethostbyname(host) in (localhost(), thishost()):
340 return addinfourl(open(url2pathname(file), 'rb'),
341 headers, 'file:'+pathname2url(file))
342 raise IOError, ('local file error', 'not on local host')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000343
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000344 # Use FTP protocol
345 def open_ftp(self, url):
346 host, path = splithost(url)
347 if not host: raise IOError, ('ftp error', 'no host given')
348 host, port = splitport(host)
349 user, host = splituser(host)
350 if user: user, passwd = splitpasswd(user)
351 else: passwd = None
352 host = unquote(host)
353 user = unquote(user or '')
354 passwd = unquote(passwd or '')
355 host = socket.gethostbyname(host)
356 if not port:
357 import ftplib
358 port = ftplib.FTP_PORT
359 else:
360 port = int(port)
361 path, attrs = splitattr(path)
362 path = unquote(path)
363 dirs = string.splitfields(path, '/')
364 dirs, file = dirs[:-1], dirs[-1]
365 if dirs and not dirs[0]: dirs = dirs[1:]
366 key = (user, host, port, string.joinfields(dirs, '/'))
367 # XXX thread unsafe!
368 if len(self.ftpcache) > MAXFTPCACHE:
369 # Prune the cache, rather arbitrarily
370 for k in self.ftpcache.keys():
371 if k != key:
372 v = self.ftpcache[k]
373 del self.ftpcache[k]
374 v.close()
375 try:
376 if not self.ftpcache.has_key(key):
377 self.ftpcache[key] = \
378 ftpwrapper(user, passwd, host, port, dirs)
379 if not file: type = 'D'
380 else: type = 'I'
381 for attr in attrs:
382 attr, value = splitvalue(attr)
383 if string.lower(attr) == 'type' and \
384 value in ('a', 'A', 'i', 'I', 'd', 'D'):
385 type = string.upper(value)
386 (fp, retrlen) = self.ftpcache[key].retrfile(file, type)
387 if retrlen is not None and retrlen >= 0:
388 import mimetools, StringIO
389 headers = mimetools.Message(StringIO.StringIO(
390 'Content-Length: %d\n' % retrlen))
391 else:
392 headers = noheaders()
393 return addinfourl(fp, headers, "ftp:" + url)
394 except ftperrors(), msg:
395 raise IOError, ('ftp error', msg), sys.exc_info()[2]
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000396
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000397 # Use "data" URL
398 def open_data(self, url, data=None):
399 # ignore POSTed data
400 #
401 # syntax of data URLs:
402 # dataurl := "data:" [ mediatype ] [ ";base64" ] "," data
403 # mediatype := [ type "/" subtype ] *( ";" parameter )
404 # data := *urlchar
405 # parameter := attribute "=" value
406 import StringIO, mimetools, time
407 try:
408 [type, data] = string.split(url, ',', 1)
409 except ValueError:
410 raise IOError, ('data error', 'bad data URL')
411 if not type:
412 type = 'text/plain;charset=US-ASCII'
413 semi = string.rfind(type, ';')
414 if semi >= 0 and '=' not in type[semi:]:
415 encoding = type[semi+1:]
416 type = type[:semi]
417 else:
418 encoding = ''
419 msg = []
420 msg.append('Date: %s'%time.strftime('%a, %d %b %Y %T GMT',
421 time.gmtime(time.time())))
422 msg.append('Content-type: %s' % type)
423 if encoding == 'base64':
424 import base64
425 data = base64.decodestring(data)
426 else:
427 data = unquote(data)
428 msg.append('Content-length: %d' % len(data))
429 msg.append('')
430 msg.append(data)
431 msg = string.join(msg, '\n')
432 f = StringIO.StringIO(msg)
433 headers = mimetools.Message(f, 0)
434 f.fileno = None # needed for addinfourl
435 return addinfourl(f, headers, url)
Guido van Rossum6d4d1c21998-03-12 14:32:55 +0000436
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000437
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000438# Derived class with handlers for errors we can handle (perhaps)
439class FancyURLopener(URLopener):
440
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000441 def __init__(self, *args):
442 apply(URLopener.__init__, (self,) + args)
443 self.auth_cache = {}
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000444
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000445 # Default error handling -- don't raise an exception
446 def http_error_default(self, url, fp, errcode, errmsg, headers):
447 return addinfourl(fp, headers, "http:" + url)
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000448
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000449 # Error 302 -- relocated (temporarily)
450 def http_error_302(self, url, fp, errcode, errmsg, headers,
451 data=None):
452 # XXX The server can force infinite recursion here!
453 if headers.has_key('location'):
454 newurl = headers['location']
455 elif headers.has_key('uri'):
456 newurl = headers['uri']
457 else:
458 return
459 void = fp.read()
460 fp.close()
461 return self.open(newurl, data)
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000462
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000463 # Error 301 -- also relocated (permanently)
464 http_error_301 = http_error_302
Guido van Rossume6ad8911996-09-10 17:02:56 +0000465
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000466 # Error 401 -- authentication required
467 # See this URL for a description of the basic authentication scheme:
468 # http://www.ics.uci.edu/pub/ietf/http/draft-ietf-http-v10-spec-00.txt
469 def http_error_401(self, url, fp, errcode, errmsg, headers,
470 data=None):
471 if headers.has_key('www-authenticate'):
472 stuff = headers['www-authenticate']
473 import re
474 match = re.match('[ \t]*([^ \t]+)[ \t]+realm="([^"]*)"', stuff)
475 if match:
476 scheme, realm = match.groups()
477 if string.lower(scheme) == 'basic':
478 return self.retry_http_basic_auth(url, realm, data)
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000479
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000480 def retry_http_basic_auth(self, url, realm, data):
481 host, selector = splithost(url)
482 i = string.find(host, '@') + 1
483 host = host[i:]
484 user, passwd = self.get_user_passwd(host, realm, i)
485 if not (user or passwd): return None
486 host = user + ':' + passwd + '@' + host
487 newurl = 'http://' + host + selector
488 return self.open(newurl, data)
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000489
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000490 def get_user_passwd(self, host, realm, clear_cache = 0):
491 key = realm + '@' + string.lower(host)
492 if self.auth_cache.has_key(key):
493 if clear_cache:
494 del self.auth_cache[key]
495 else:
496 return self.auth_cache[key]
497 user, passwd = self.prompt_user_passwd(host, realm)
498 if user or passwd: self.auth_cache[key] = (user, passwd)
499 return user, passwd
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000500
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000501 def prompt_user_passwd(self, host, realm):
502 # Override this in a GUI environment!
503 import getpass
504 try:
505 user = raw_input("Enter username for %s at %s: " % (realm,
506 host))
507 passwd = getpass.getpass("Enter password for %s in %s at %s: " %
508 (user, realm, host))
509 return user, passwd
510 except KeyboardInterrupt:
511 print
512 return None, None
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000513
514
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000515# Utility functions
516
517# Return the IP address of the magic hostname 'localhost'
518_localhost = None
519def localhost():
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000520 global _localhost
521 if not _localhost:
522 _localhost = socket.gethostbyname('localhost')
523 return _localhost
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000524
525# Return the IP address of the current host
526_thishost = None
527def thishost():
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000528 global _thishost
529 if not _thishost:
530 _thishost = socket.gethostbyname(socket.gethostname())
531 return _thishost
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000532
533# Return the set of errors raised by the FTP class
534_ftperrors = None
535def ftperrors():
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000536 global _ftperrors
537 if not _ftperrors:
538 import ftplib
539 _ftperrors = ftplib.all_errors
540 return _ftperrors
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000541
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000542# Return an empty mimetools.Message object
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000543_noheaders = None
544def noheaders():
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000545 global _noheaders
546 if not _noheaders:
547 import mimetools
548 import StringIO
549 _noheaders = mimetools.Message(StringIO.StringIO(), 0)
550 _noheaders.fp.close() # Recycle file descriptor
551 return _noheaders
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000552
553
554# Utility classes
555
556# Class used by open_ftp() for cache of open FTP connections
557class ftpwrapper:
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000558 def __init__(self, user, passwd, host, port, dirs):
559 self.user = user
560 self.passwd = passwd
561 self.host = host
562 self.port = port
563 self.dirs = dirs
564 self.init()
565 def init(self):
566 import ftplib
567 self.busy = 0
568 self.ftp = ftplib.FTP()
569 self.ftp.connect(self.host, self.port)
570 self.ftp.login(self.user, self.passwd)
571 for dir in self.dirs:
572 self.ftp.cwd(dir)
573 def retrfile(self, file, type):
574 import ftplib
575 self.endtransfer()
576 if type in ('d', 'D'): cmd = 'TYPE A'; isdir = 1
577 else: cmd = 'TYPE ' + type; isdir = 0
578 try:
579 self.ftp.voidcmd(cmd)
580 except ftplib.all_errors:
581 self.init()
582 self.ftp.voidcmd(cmd)
583 conn = None
584 if file and not isdir:
585 # Use nlst to see if the file exists at all
586 try:
587 self.ftp.nlst(file)
588 except ftplib.error_perm, reason:
589 raise IOError, ('ftp error', reason), sys.exc_info()[2]
590 # Restore the transfer mode!
591 self.ftp.voidcmd(cmd)
592 # Try to retrieve as a file
593 try:
594 cmd = 'RETR ' + file
595 conn = self.ftp.ntransfercmd(cmd)
596 except ftplib.error_perm, reason:
597 if reason[:3] != '550':
598 raise IOError, ('ftp error', reason), sys.exc_info()[2]
599 if not conn:
600 # Set transfer mode to ASCII!
601 self.ftp.voidcmd('TYPE A')
602 # Try a directory listing
603 if file: cmd = 'LIST ' + file
604 else: cmd = 'LIST'
605 conn = self.ftp.ntransfercmd(cmd)
606 self.busy = 1
607 # Pass back both a suitably decorated object and a retrieval length
608 return (addclosehook(conn[0].makefile('rb'),
609 self.endtransfer), conn[1])
610 def endtransfer(self):
611 if not self.busy:
612 return
613 self.busy = 0
614 try:
615 self.ftp.voidresp()
616 except ftperrors():
617 pass
618 def close(self):
619 self.endtransfer()
620 try:
621 self.ftp.close()
622 except ftperrors():
623 pass
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000624
625# Base class for addinfo and addclosehook
626class addbase:
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000627 def __init__(self, fp):
628 self.fp = fp
629 self.read = self.fp.read
630 self.readline = self.fp.readline
631 self.readlines = self.fp.readlines
632 self.fileno = self.fp.fileno
633 def __repr__(self):
634 return '<%s at %s whose fp = %s>' % (self.__class__.__name__,
635 `id(self)`, `self.fp`)
636 def close(self):
637 self.read = None
638 self.readline = None
639 self.readlines = None
640 self.fileno = None
641 if self.fp: self.fp.close()
642 self.fp = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000643
644# Class to add a close hook to an open file
645class addclosehook(addbase):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000646 def __init__(self, fp, closehook, *hookargs):
647 addbase.__init__(self, fp)
648 self.closehook = closehook
649 self.hookargs = hookargs
650 def close(self):
651 if self.closehook:
652 apply(self.closehook, self.hookargs)
653 self.closehook = None
654 self.hookargs = None
655 addbase.close(self)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000656
657# class to add an info() method to an open file
658class addinfo(addbase):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000659 def __init__(self, fp, headers):
660 addbase.__init__(self, fp)
661 self.headers = headers
662 def info(self):
663 return self.headers
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000664
Guido van Rossume6ad8911996-09-10 17:02:56 +0000665# class to add info() and geturl() methods to an open file
666class addinfourl(addbase):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000667 def __init__(self, fp, headers, url):
668 addbase.__init__(self, fp)
669 self.headers = headers
670 self.url = url
671 def info(self):
672 return self.headers
673 def geturl(self):
674 return self.url
Guido van Rossume6ad8911996-09-10 17:02:56 +0000675
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000676
677# Utility to combine a URL with a base URL to form a new URL
678
679def basejoin(base, url):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000680 type, path = splittype(url)
681 if type:
682 # if url is complete (i.e., it contains a type), return it
683 return url
684 host, path = splithost(path)
685 type, basepath = splittype(base) # inherit type from base
686 if host:
687 # if url contains host, just inherit type
688 if type: return type + '://' + host + path
689 else:
690 # no type inherited, so url must have started with //
691 # just return it
692 return url
693 host, basepath = splithost(basepath) # inherit host
694 basepath, basetag = splittag(basepath) # remove extraneuous cruft
695 basepath, basequery = splitquery(basepath) # idem
696 if path[:1] != '/':
697 # non-absolute path name
698 if path[:1] in ('#', '?'):
699 # path is just a tag or query, attach to basepath
700 i = len(basepath)
701 else:
702 # else replace last component
703 i = string.rfind(basepath, '/')
704 if i < 0:
705 # basepath not absolute
706 if host:
707 # host present, make absolute
708 basepath = '/'
709 else:
710 # else keep non-absolute
711 basepath = ''
712 else:
713 # remove last file component
714 basepath = basepath[:i+1]
715 # Interpret ../ (important because of symlinks)
716 while basepath and path[:3] == '../':
717 path = path[3:]
718 i = string.rfind(basepath[:-1], '/')
719 if i > 0:
720 basepath = basepath[:i+1]
721 elif i == 0:
722 basepath = '/'
723 break
724 else:
725 basepath = ''
726
727 path = basepath + path
728 if type and host: return type + '://' + host + path
729 elif type: return type + ':' + path
730 elif host: return '//' + host + path # don't know what this means
731 else: return path
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000732
733
Guido van Rossum7c395db1994-07-04 22:14:49 +0000734# Utilities to parse URLs (most of these return None for missing parts):
Sjoerd Mullendere0371b81995-11-10 10:36:07 +0000735# unwrap('<URL:type://host/path>') --> 'type://host/path'
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000736# splittype('type:opaquestring') --> 'type', 'opaquestring'
737# splithost('//host[:port]/path') --> 'host[:port]', '/path'
Guido van Rossum7c395db1994-07-04 22:14:49 +0000738# splituser('user[:passwd]@host[:port]') --> 'user[:passwd]', 'host[:port]'
739# splitpasswd('user:passwd') -> 'user', 'passwd'
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000740# splitport('host:port') --> 'host', 'port'
741# splitquery('/path?query') --> '/path', 'query'
742# splittag('/path#tag') --> '/path', 'tag'
Guido van Rossum7c395db1994-07-04 22:14:49 +0000743# splitattr('/path;attr1=value1;attr2=value2;...') ->
744# '/path', ['attr1=value1', 'attr2=value2', ...]
745# splitvalue('attr=value') --> 'attr', 'value'
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000746# splitgophertype('/Xselector') --> 'X', 'selector'
747# unquote('abc%20def') -> 'abc def'
748# quote('abc def') -> 'abc%20def')
749
750def unwrap(url):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000751 url = string.strip(url)
752 if url[:1] == '<' and url[-1:] == '>':
753 url = string.strip(url[1:-1])
754 if url[:4] == 'URL:': url = string.strip(url[4:])
755 return url
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000756
Guido van Rossum332e1441997-09-29 23:23:46 +0000757_typeprog = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000758def splittype(url):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000759 global _typeprog
760 if _typeprog is None:
761 import re
762 _typeprog = re.compile('^([^/:]+):')
Guido van Rossum332e1441997-09-29 23:23:46 +0000763
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000764 match = _typeprog.match(url)
765 if match:
766 scheme = match.group(1)
767 return scheme, url[len(scheme) + 1:]
768 return None, url
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000769
Guido van Rossum332e1441997-09-29 23:23:46 +0000770_hostprog = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000771def splithost(url):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000772 global _hostprog
773 if _hostprog is None:
774 import re
775 _hostprog = re.compile('^//([^/]+)(.*)$')
Guido van Rossum332e1441997-09-29 23:23:46 +0000776
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000777 match = _hostprog.match(url)
778 if match: return match.group(1, 2)
779 return None, url
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000780
Guido van Rossum332e1441997-09-29 23:23:46 +0000781_userprog = None
Guido van Rossum7c395db1994-07-04 22:14:49 +0000782def splituser(host):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000783 global _userprog
784 if _userprog is None:
785 import re
786 _userprog = re.compile('^([^@]*)@(.*)$')
Guido van Rossum332e1441997-09-29 23:23:46 +0000787
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000788 match = _userprog.match(host)
789 if match: return match.group(1, 2)
790 return None, host
Guido van Rossum7c395db1994-07-04 22:14:49 +0000791
Guido van Rossum332e1441997-09-29 23:23:46 +0000792_passwdprog = None
Guido van Rossum7c395db1994-07-04 22:14:49 +0000793def splitpasswd(user):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000794 global _passwdprog
795 if _passwdprog is None:
796 import re
797 _passwdprog = re.compile('^([^:]*):(.*)$')
Guido van Rossum332e1441997-09-29 23:23:46 +0000798
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000799 match = _passwdprog.match(user)
800 if match: return match.group(1, 2)
801 return user, None
Guido van Rossum7c395db1994-07-04 22:14:49 +0000802
Guido van Rossum332e1441997-09-29 23:23:46 +0000803_portprog = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000804def splitport(host):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000805 global _portprog
806 if _portprog is None:
807 import re
808 _portprog = re.compile('^(.*):([0-9]+)$')
Guido van Rossum332e1441997-09-29 23:23:46 +0000809
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000810 match = _portprog.match(host)
811 if match: return match.group(1, 2)
812 return host, None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000813
Guido van Rossum53725a21996-06-13 19:12:35 +0000814# Split host and port, returning numeric port.
815# Return given default port if no ':' found; defaults to -1.
Guido van Rossum84a00a81996-06-17 17:11:40 +0000816# Return numerical port if a valid number are found after ':'.
817# Return None if ':' but not a valid number.
Guido van Rossum332e1441997-09-29 23:23:46 +0000818_nportprog = None
Guido van Rossum53725a21996-06-13 19:12:35 +0000819def splitnport(host, defport=-1):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000820 global _nportprog
821 if _nportprog is None:
822 import re
823 _nportprog = re.compile('^(.*):(.*)$')
Guido van Rossum7e7ca0b1998-03-26 21:01:39 +0000824
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000825 match = _nportprog.match(host)
826 if match:
827 host, port = match.group(1, 2)
828 try:
829 if not port: raise string.atoi_error, "no digits"
830 nport = string.atoi(port)
831 except string.atoi_error:
832 nport = None
833 return host, nport
834 return host, defport
Guido van Rossum53725a21996-06-13 19:12:35 +0000835
Guido van Rossum332e1441997-09-29 23:23:46 +0000836_queryprog = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000837def splitquery(url):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000838 global _queryprog
839 if _queryprog is None:
840 import re
841 _queryprog = re.compile('^(.*)\?([^?]*)$')
Guido van Rossum332e1441997-09-29 23:23:46 +0000842
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000843 match = _queryprog.match(url)
844 if match: return match.group(1, 2)
845 return url, None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000846
Guido van Rossum332e1441997-09-29 23:23:46 +0000847_tagprog = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000848def splittag(url):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000849 global _tagprog
850 if _tagprog is None:
851 import re
852 _tagprog = re.compile('^(.*)#([^#]*)$')
Guido van Rossum7e7ca0b1998-03-26 21:01:39 +0000853
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000854 match = _tagprog.match(url)
855 if match: return match.group(1, 2)
856 return url, None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000857
Guido van Rossum7c395db1994-07-04 22:14:49 +0000858def splitattr(url):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000859 words = string.splitfields(url, ';')
860 return words[0], words[1:]
Guido van Rossum7c395db1994-07-04 22:14:49 +0000861
Guido van Rossum332e1441997-09-29 23:23:46 +0000862_valueprog = None
Guido van Rossum7c395db1994-07-04 22:14:49 +0000863def splitvalue(attr):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000864 global _valueprog
865 if _valueprog is None:
866 import re
867 _valueprog = re.compile('^([^=]*)=(.*)$')
Guido van Rossum332e1441997-09-29 23:23:46 +0000868
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000869 match = _valueprog.match(attr)
870 if match: return match.group(1, 2)
871 return attr, None
Guido van Rossum7c395db1994-07-04 22:14:49 +0000872
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000873def splitgophertype(selector):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000874 if selector[:1] == '/' and selector[1:2]:
875 return selector[1], selector[2:]
876 return None, selector
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000877
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000878def unquote(s):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000879 mychr = chr
880 myatoi = string.atoi
881 list = string.split(s, '%')
882 res = [list[0]]
883 myappend = res.append
884 del list[0]
885 for item in list:
886 if item[1:2]:
887 try:
888 myappend(mychr(myatoi(item[:2], 16))
889 + item[2:])
890 except:
891 myappend('%' + item)
892 else:
893 myappend('%' + item)
894 return string.join(res, "")
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000895
Guido van Rossum0564e121996-12-13 14:47:36 +0000896def unquote_plus(s):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000897 if '+' in s:
898 # replace '+' with ' '
899 s = string.join(string.split(s, '+'), ' ')
900 return unquote(s)
Guido van Rossum0564e121996-12-13 14:47:36 +0000901
Guido van Rossum3bb54481994-08-29 10:52:58 +0000902always_safe = string.letters + string.digits + '_,.-'
Guido van Rossum7c395db1994-07-04 22:14:49 +0000903def quote(s, safe = '/'):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000904 safe = always_safe + safe
905 res = list(s)
906 for i in range(len(res)):
907 c = res[i]
908 if c not in safe:
909 res[i] = '%%%02x' % ord(c)
910 return string.joinfields(res, '')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000911
Guido van Rossum0564e121996-12-13 14:47:36 +0000912def quote_plus(s, safe = '/'):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000913 if ' ' in s:
914 # replace ' ' with '+'
915 l = string.split(s, ' ')
916 for i in range(len(l)):
917 l[i] = quote(l[i], safe)
918 return string.join(l, '+')
919 else:
920 return quote(s, safe)
Guido van Rossum0564e121996-12-13 14:47:36 +0000921
Guido van Rossum810a3391998-07-22 21:33:23 +0000922def urlencode(dict):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000923 l = []
924 for k, v in dict.items():
925 k = quote_plus(str(k))
926 v = quote_plus(str(v))
927 l.append(k + '=' + v)
928 return string.join(l, '&')
Guido van Rossum810a3391998-07-22 21:33:23 +0000929
Guido van Rossum442e7201996-03-20 15:33:11 +0000930
931# Proxy handling
Guido van Rossum4163e701998-08-06 13:39:09 +0000932if os.name == 'mac':
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000933 def getproxies():
934 """Return a dictionary of scheme -> proxy server URL mappings.
Guido van Rossum442e7201996-03-20 15:33:11 +0000935
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000936 By convention the mac uses Internet Config to store
937 proxies. An HTTP proxy, for instance, is stored under
938 the HttpProxy key.
Guido van Rossum442e7201996-03-20 15:33:11 +0000939
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000940 """
941 try:
942 import ic
943 except ImportError:
944 return {}
945
946 try:
947 config = ic.IC()
948 except ic.error:
949 return {}
950 proxies = {}
951 # HTTP:
952 if config.has_key('UseHTTPProxy') and config['UseHTTPProxy']:
953 try:
954 value = config['HTTPProxyHost']
955 except ic.error:
956 pass
957 else:
958 proxies['http'] = 'http://%s' % value
959 # FTP: XXXX To be done.
960 # Gopher: XXXX To be done.
961 return proxies
962
Guido van Rossum4163e701998-08-06 13:39:09 +0000963else:
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000964 def getproxies():
965 """Return a dictionary of scheme -> proxy server URL mappings.
966
967 Scan the environment for variables named <scheme>_proxy;
968 this seems to be the standard convention. If you need a
969 different way, you can pass a proxies dictionary to the
970 [Fancy]URLopener constructor.
971
972 """
973 proxies = {}
974 for name, value in os.environ.items():
975 name = string.lower(name)
976 if value and name[-6:] == '_proxy':
977 proxies[name[:-6]] = value
978 return proxies
Guido van Rossum442e7201996-03-20 15:33:11 +0000979
980
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000981# Test and time quote() and unquote()
982def test1():
Jeremy Hyltonf90b0021999-02-25 16:12:12 +0000983 import time
984 s = ''
985 for i in range(256): s = s + chr(i)
986 s = s*4
987 t0 = time.time()
988 qs = quote(s)
989 uqs = unquote(qs)
990 t1 = time.time()
991 if uqs != s:
992 print 'Wrong!'
993 print `s`
994 print `qs`
995 print `uqs`
996 print round(t1 - t0, 3), 'sec'
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000997
998
Guido van Rossum9ab96d41998-09-28 14:07:00 +0000999def reporthook(blocknum, blocksize, totalsize):
1000 # Report during remote transfers
1001 print "Block number: %d, Block size: %d, Total size: %d" % (blocknum, blocksize, totalsize)
1002
Guido van Rossum7c6ebb51994-03-22 12:05:32 +00001003# Test program
Guido van Rossum23490151998-06-25 02:39:00 +00001004def test(args=[]):
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001005 if not args:
1006 args = [
1007 '/etc/passwd',
1008 'file:/etc/passwd',
1009 'file://localhost/etc/passwd',
1010 'ftp://ftp.python.org/etc/passwd',
1011## 'gopher://gopher.micro.umn.edu/1/',
1012 'http://www.python.org/index.html',
1013 ]
1014 try:
1015 for url in args:
1016 print '-'*10, url, '-'*10
1017 fn, h = urlretrieve(url, None, reporthook)
1018 print fn, h
1019 if h:
1020 print '======'
1021 for k in h.keys(): print k + ':', h[k]
1022 print '======'
1023 fp = open(fn, 'rb')
1024 data = fp.read()
1025 del fp
1026 if '\r' in data:
1027 table = string.maketrans("", "")
1028 data = string.translate(data, table, "\r")
1029 print data
1030 fn, h = None, None
1031 print '-'*40
1032 finally:
1033 urlcleanup()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +00001034
Guido van Rossum23490151998-06-25 02:39:00 +00001035def main():
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001036 import getopt, sys
1037 try:
1038 opts, args = getopt.getopt(sys.argv[1:], "th")
1039 except getopt.error, msg:
1040 print msg
1041 print "Use -h for help"
1042 return
1043 t = 0
1044 for o, a in opts:
1045 if o == '-t':
1046 t = t + 1
1047 if o == '-h':
1048 print "Usage: python urllib.py [-t] [url ...]"
1049 print "-t runs self-test;",
1050 print "otherwise, contents of urls are printed"
1051 return
1052 if t:
1053 if t > 1:
1054 test1()
1055 test(args)
1056 else:
1057 if not args:
1058 print "Use -h for help"
1059 for url in args:
1060 print urlopen(url).read(),
Guido van Rossum23490151998-06-25 02:39:00 +00001061
Guido van Rossum7c6ebb51994-03-22 12:05:32 +00001062# Run test program when run as a script
1063if __name__ == '__main__':
Jeremy Hyltonf90b0021999-02-25 16:12:12 +00001064 main()