-
Notifications
You must be signed in to change notification settings - Fork 161
Expand file tree
/
Copy pathpytip.py
More file actions
58 lines (45 loc) · 1.63 KB
/
Copy pathpytip.py
File metadata and controls
58 lines (45 loc) · 1.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
from collections import namedtuple
from contextlib import closing
import codecs
import csv
import ssl
import sys
try:
from urllib.request import urlopen
except ImportError:
from urllib2 import urlopen
LOCAL_CSV = 'daily-python-tip.csv' # for testing
REMOTE_CSV = 'https://t.co/oARrOmrin7'
FIELDS = 'time code name email admin1 admin2 published'.split()
CONTEXT = ssl._create_unverified_context()
TEST = False
Tip = namedtuple('Tip', 'time code name published')
def get_csv_entries():
if TEST:
action = open(LOCAL_CSV)
else:
action = closing(urlopen(REMOTE_CSV, context=CONTEXT))
with action as f:
if not TEST and sys.version_info.major > 2:
f = codecs.iterdecode(f, 'utf-8') # needed for urlopen and py3
for entry in csv.DictReader(f, fieldnames=FIELDS):
yield entry
def get_tips(terms):
for d in get_csv_entries():
tip = Tip(time=d['time'], code=d['code'],
name=d['name'], published=d['published'])
matches = all([i.lower() in tip.code.lower() for i in terms])
if matches:
yield tip
if __name__ == "__main__":
if len(sys.argv) < 2:
sys.exit('Call this script with one or more search terms')
terms = sys.argv[1:]
fmt = '{}.\n{} submitted a tip at {}:\n{}\n\n* Published: {}\n---\n\n'
tips = list(get_tips(terms))
if not tips:
print('Nothing found, you can submit a tip here: bit.ly/pythontip')
else:
for num, tip in enumerate(tips, 1):
pub = tip.published if bool(tip.published) else 'not yet'
print(fmt.format(num, tip.name, tip.time, tip.code, pub))