forked from sudharsan2020/python-mastery
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfollow.py
56 lines (48 loc) · 1.52 KB
/
follow.py
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
# follow.py
import os
import time
def follow(filename):
'''
Generator that produces a sequence of lines being written at the end of a file.
'''
try:
with open(filename,'r') as f:
f.seek(0,os.SEEK_END)
while True:
line = f.readline()
if line == '':
time.sleep(0.1) # Sleep briefly to avoid busy wait
continue
yield line
except GeneratorExit:
print('Following Done')
def splitter(lines):
for line in lines:
yield line.split(',')
def make_records(rows,names):
for row in rows:
yield dict(zip(names,row))
def unquote(records,keylist):
for r in records:
for key in keylist:
r[key] = r[key].strip('"')
yield r
def convert(records,converter,keylist):
for r in records:
for key in keylist:
r[key] = converter(r[key])
yield r
def parse_stock_data(lines):
rows = splitter(lines)
records = make_records(rows,['name','price','date','time',
'change','open','high','low','volume'])
records = unquote(records,["name","date","time"])
records = convert(records,float,['price','change','open','high','low'])
records = convert(records,int,['volume'])
return records
# Sample use
if __name__ == '__main__':
lines = follow("../../Data/stocklog.dat")
records = parse_stock_data(lines)
for r in records:
print("%(name)10s %(price)10.2f %(change)10.2f" % r)