From ec6a317261861b40710d2cfcd71934571e4be792 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ra=C3=BAl=20Benencia?= Date: Wed, 19 Dec 2018 15:43:47 -0800 Subject: add a python fortune file reader --- fortune.py | 54 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100755 fortune.py diff --git a/fortune.py b/fortune.py new file mode 100755 index 0000000..64f9dd9 --- /dev/null +++ b/fortune.py @@ -0,0 +1,54 @@ +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) -- cgit v1.2.3