Initial commit

This commit is contained in:
David Beazley
2023-07-16 20:21:00 -05:00
parent 82e815fab2
commit 7d4b30154a
259 changed files with 600233 additions and 2 deletions

40
Solutions/8_4/cofollow.py Normal file
View File

@@ -0,0 +1,40 @@
# cofollow.py
import os
import time
import csv
def follow(filename,target):
with open(filename,"r") as f:
f.seek(0,os.SEEK_END)
while True:
line = f.readline()
if line != '':
target.send(line)
else:
time.sleep(0.1)
# Decorator for coroutines
from functools import wraps
def consumer(func):
@wraps(func)
def start(*args,**kwargs):
f = func(*args,**kwargs)
f.send(None)
return f
return start
# Sample coroutine
@consumer
def printer():
while True:
try:
item = yield
print(item)
except Exception as e:
print('ERROR: %r' % e)
# Example use.
if __name__ == '__main__':
follow('../../Data/stocklog.csv', printer())

56
Solutions/8_4/follow.py Normal file
View File

@@ -0,0 +1,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)