#!/usr/bin/python ############################################################################## # GCALC - A command-line interface to the Google calculation. Simply passes # the command-line arguments to the Google web-site and displays the # results. # # Published under the GNU Public License: http://www.gnu.org/copyleft/gpl.html # # $Id: $ from httplib import HTTPConnection; import sys, re, urllib, htmlentitydefs ############################################################################## # HTTP Constants GoogleServer = 'www.google.co.uk'; RequestBase = '/search?num=1&q='; Headers = { 'User-Agent' : 'Mozilla/4.0' }; ############################################################################## # Regular Expressions CoarseMatchEx = re.compile ( '.*calc_img\.gif[^>]*>(?P.+)<\/b>', re.DOTALL ); FineMatchEx = re.compile ( '.*(?P.*)' ); PostProcessExs = [ ( re.compile ( pattern ), subst ) for pattern, subst in ( ( '', '^' ), ( '<[^>]*>', '' ) ) ]; ############################################################################## # Script # Construct the request string (the path component of the HTTP request) calculation = ' '.join ( sys.argv [ 1 : ] ).strip ( ); if not calculation: sys.exit ( 'Must provide something to calculate!' ); requeststring = RequestBase + urllib.quote ( calculation ); # Connect to the Google server, make the request and retrieve the response try: connection = HTTPConnection ( GoogleServer ); connection.request ( method = 'GET', url = requeststring, headers = Headers ); response = connection.getresponse ( ).read ( ).strip ( ); except Exception, exception: sys.exit ( 'Unable to make request "http://%s/%s" - %s' % ( GoogleServer, requeststring, exception ) ); # Process the response and display the Google Calculator response, if any coarsematch = CoarseMatchEx.match ( response ); if coarsematch: finematch = FineMatchEx.match ( coarsematch.group ( 'match' ) ); if finematch: value = finematch.group ( 'match' ); # Pass the value through the post processing regular expressions for regex, subst in PostProcessExs: value = regex.sub ( subst, value ); # Expand any unicode values to ASCII for unicode in htmlentitydefs.codepoint2name: if '&#%d;' % unicode in value: entity = htmlentitydefs.codepoint2name [ unicode ]; if entity in htmlentitydefs.entitydefs: value = value.replace ( '&#%d;' % unicode, htmlentitydefs.entitydefs [ entity ] ); else: value = value.replace ( '&#%d;' % unicode, '' ); # Expand any entity definitions to ASCII for entity in htmlentitydefs.entitydefs: if '&%s;' % entity in value: value = value.replace ( '&%s;' % entity, htmlentitydefs.entitydefs [ entity ] ); # Done! print value; else: sys.exit ( 'Warning - Google appears to have changed its page layout, update Fine Match expression' ); else: print 'Google Calculator did not understand : %s' % calculation;