import random import sys class FortuneCookie(): """"Holds a cookie""" def __init__(self, msg): self.msg = msg class FortuneFile(): """Contains methods for querying a cookie file""" def __init__(self, filename): self.filename = filename def fortunes(self): try: with open(self.filename) as f: current = "" for line in f: if line != "%\n": current += line else: cookie = FortuneCookie(current) current = "" yield cookie if current != "": yield FortuneCookie(current) except FileNotFoundError: print("[*] Can't find the file " + self.filename) except IOError: print("[*] Error opening the file.") def get_random_cookie(self): for i, v in enumerate(self.fortunes()): rand = random.randint(0, i) if rand == 0: ret = v return ret if __name__ == "__main__": if len(sys.argv) != 2: print("Usage: {} ".format(sys.argv[0])) sys.exit(1) ff = FortuneFile(sys.argv[1]) cookie = ff.get_random_cookie() sys.stdout.write(cookie.msg)