summaryrefslogtreecommitdiff
path: root/fortune.py
diff options
context:
space:
mode:
authorRaúl Benencia <rul@kalgan.cc>2018-12-19 15:43:47 -0800
committerRaúl Benencia <rul@kalgan.cc>2018-12-19 15:44:26 -0800
commitec6a317261861b40710d2cfcd71934571e4be792 (patch)
tree49e4d86460b03ee97b825316c6f1bad48f8bab57 /fortune.py
parent0800363a1234c47f25ac266b3a088e4c585f5c19 (diff)
add a python fortune file reader
Diffstat (limited to 'fortune.py')
-rwxr-xr-xfortune.py54
1 files changed, 54 insertions, 0 deletions
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: {} <fortune filename>".format(sys.argv[0]))
+ sys.exit(1)
+
+ ff = FortuneFile(sys.argv[1])
+ cookie = ff.get_random_cookie()
+
+ sys.stdout.write(cookie.msg)
nihil fit ex nihilo