#!/usr/bin/env python # -*- coding: iso-8859-1 -*- from sys import argv import csv import string from GoogleStats import blogSearchMonthResultCount from time import sleep from Emailer import sendFile from Imdb import titleCode def sanitizeString(dirty): clean = "" allowed = string.ascii_letters + string.digits + " -.'\"" for i, v in enumerate(dirty): if allowed.find(str(v)) != -1: clean = clean + str(v) else: clean = clean + " " while clean.find(" ") != -1: clean = clean.replace(" ", " ") return clean.strip() def tryTenTimes(function): count = 10 while count > 0: count = count - 1 try: return function() except Exception as ex: print "Error:", ex, "... sleeping 5." sleep(5) return None emailMessage = "Hello %s,\n\nThis is an automated message. Attached are the requested blog statistics for these movies:\n" % argv[3][0:argv[3].find('@')] listFile = open(argv[1]) outFile = open(argv[2], "wb") output = csv.writer(outFile) header = ["Rank", "Movie", "Google Blog Search Result Count (past month)", "IMDB Title Code"] output.writerow(header) print header i = 0 for line in listFile: i = i + 1 movie = line.strip() emailMessage = emailMessage + "\n * %s" % movie searchString = sanitizeString(movie) blogSearch = tryTenTimes(lambda: blogSearchMonthResultCount(searchString)) if blogSearch is None: blogSearch = '???' imdbTitleCode = tryTenTimes(lambda: titleCode(searchString)) if imdbTitleCode is None: imdbTitleCode = '???' row = [str(i), movie, str(blogSearch), imdbTitleCode] output.writerow(row) outFile.flush() print row outFile.close() listFile.close() emailMessage += "\n\nEnjoy,\nJason" print "Sending email...", sendFile(argv[3], argv[2], emailMessage) print "sent!"