''' lucky.py - both a joke and an implementation The joke: New in Python X.X: Integrated Google search in urllib. Example: >>> import urllib >>> f = urllib.urlopen('miserable failure') >>> print f.geturl() http://www.whitehouse.gov/president/gwbbio.html And for some reason, I decided to implement it: >>> import lucky >>> lucky.magic() >>> import urllib >>> f = urllib.urlopen('miserable failure') >>> print f.geturl() http://www.whitehouse.gov/president/gwbbio.html ''' # lucky.py - Integrated Google search in urllib # Copyright (C) 2006 Lenny Domnitser # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, # Boston, MA 02110-1301, USA. import httplib import urllib import urlparse __author__ = 'Lenny Domnitser ' __license__ = 'GNU_GPL' __version__ = '0.1' # 2006-09-11 __all__ = 'BadLuck', 'magic', 'unmagic', 'urlopen' URL_TEMPLATE = 'http://www.google.com/search?btnI=&q=%s' class BadLuck(IOError): '''No page matches keywords.''' pass _normal_urlopen = urllib.urlopen def magic(): urllib.urlopen = urlopen def unmagic(): urllib.urlopen = _normal_urlopen def urlopen(url, data = None, proxies = None): '''If url is not really a URL, then get the most likely matching web page. Otherwise works like urllib.urlopen''' if not data and not urlparse.urlparse(url)[0]: return lucky_open(url, proxies) else: return _normal_urlopen(url, data, proxies) def lucky_open(keywords, proxies = None): url = URL_TEMPLATE % urllib.quote_plus(keywords) url_opener = urllib.URLopener(proxies) url_opener.addheaders = [('User-Agent', 'lucky.py/%s' % __version__)] try: # the opener will raise an error on 302 Found # if it doesn't raise an error, we do url_opener.open(url) raise BadLuck('No page matches keywords: %s' % keywords) except IOError, e: message = e[-1] if not isinstance(message, httplib.HTTPMessage): raise e location = message.get('Location') return _normal_urlopen(location, None, proxies) if __name__ == '__main__': import sys print urlopen(' '.join(sys.argv[1:])).geturl()