Browse Source

made code pep8 compliant

no_compress
Raphael Roberts 7 years ago
parent
commit
181b045f10
  1. 9
      ctabus.py
  2. 47
      main.py
  3. 23
      print2d.py
  4. 16
      search.py

9
ctabus.py

@ -1,8 +1,9 @@
from urllib.parse import urlencode
from urllib.request import urlopen
import json
import os.path as osp
from sensitive import api
def get_data(type, api_key=api, **args):
base_url = "http://www.ctabustracker.com/bustime/api/v2/{type}?{query}"
args['key'] = api_key
@ -16,16 +17,18 @@ def get_data(type,api_key = api,**args):
except KeyError:
return data
def get_times(stop_id, api_key=api):
return get_data('getpredictions', api_key, stpid=stop_id)
def get_routes(api_key=api):
return get_data('getroutes', api_key)
def get_directions(route, api_key=api):
return get_data('getdirections', api_key, rt=route)
def get_stops(route, direction, api_key=api):
return get_data('getstops', api_key, rt=route, dir=direction)
#

47
main.py

@ -10,11 +10,14 @@ import time
# for logging
import os.path as osp
import sys
import re
CHICAGO_TZ = tz.gettz("America/Chicago")
# https://stackoverflow.com/a/5967539
def atoi(text):
return int(text) if text.isdigit() else text
def numb_sort(text):
'''
alist.sort(key=natural_keys) sorts in human order
@ -23,9 +26,11 @@ def numb_sort(text):
'''
return [atoi(c) for c in re.split(r'(\d+)', text)]
def clearscr():
os.system('cls' if os.name == 'nt' else 'clear')
def pprint_delta(delta):
delta = str(delta)
days = None
@ -42,17 +47,20 @@ def pprint_delta(delta):
if minute:
if time and not time.endswith(', '):
time += ', '
time += '{minute} minute'.format(minute=minute) + ('s' if minute != 1 else '')
time += '{minute} minute'.format(minute=minute) + \
('s' if minute != 1 else '')
if second:
if time and not time.endswith(', '):
time += ', '
time += '{second} second'.format(second=second) + ('s' if second != 1 else '')
time += '{second} second'.format(second=second) + \
('s' if second != 1 else '')
ret = ''
if days:
ret = days + ', ' if time else ''
ret += time
return ret
def gen_list(objs, data, *displays, key=None, sort=0, num_pic=True):
k = displays[sort]
display_data = {obj[k]: obj[data] for obj in objs}
@ -97,11 +105,14 @@ def gen_list(objs,data,*displays,key = None,sort = 0,num_pic = True):
pass
return ret
config = '''\
{route} - {end} ({direction})
{nm}, stop {stop_id}
{delta} ({t})\
'''
def show(data, rt_filter=None, _clear=False):
times = data['prd']
today = datetime.datetime.now(CHICAGO_TZ)
@ -110,25 +121,29 @@ def show(data,rt_filter=None,_clear=False):
arrivals = filter(lambda arrival: arrival['rt'] == rt_filter, arrivals)
if _clear:
clearscr()
for time in arrivals:
before = date_parse(time['prdtm'])
for bustime in arrivals:
before = date_parse(bustime['prdtm'])
arrival = before.replace(tzinfo=CHICAGO_TZ)
if arrival > today:
stop_id = time['stpid']
stop_id = bustime['stpid']
delta = pprint_delta(arrival-today)
t = arrival.strftime('%H:%M:%S')
route = time['rt']
direction = time['rtdir']
end = time['des']
nm = time['stpnm'].rstrip()
route = bustime['rt']
direction = bustime['rtdir']
end = bustime['des']
nm = bustime['stpnm'].rstrip()
print(
config.format(**locals()), end='\n'*2
)
print("="*36)
if __name__ == '__main__':
parser = argparse.ArgumentParser(prog='ctabus')
parser.add_argument('-l','--lucky',action='store_true',help = 'picks first result')
parser.add_argument('-p','--periodic',metavar = 'SEC',type=int,help='checks periodically')
parser.add_argument('-l', '--lucky', action='store_true',
help='picks first result')
parser.add_argument('-p', '--periodic', metavar='SEC',
type=int, help='checks periodically')
parser.add_argument('-r', '--route', default=None)
parser.add_argument('-d', '--direction', default=None)
parser.add_argument('arg', nargs='+', metavar='(stop-id | cross streets)')
@ -143,7 +158,8 @@ if __name__ == '__main__':
# routes
if not args.route:
data = ctabus.get_routes()['routes']
route = gen_list(data,'rt','rt','rtnm',num_pic = False,key=numb_sort)
route = gen_list(data, 'rt', 'rt', 'rtnm',
num_pic=False, key=numb_sort)
else:
route = args.route
data = ctabus.get_directions(route)['directions']
@ -157,7 +173,8 @@ if __name__ == '__main__':
stops = ctabus.get_stops(route, direction)['stops']
s = StopSearch(args.arg)
if args.lucky:
stop_id = sorted(stops,key=lambda stop: s(stop['stpnm']))[0]['stpid']
stop_id = sorted(stops, key=lambda stop: s(stop['stpnm']))[
0]['stpid']
else:
stop_id = gen_list(stops, 'stpid', 'stpnm', key=s)
else:
@ -173,7 +190,7 @@ if __name__ == '__main__':
e = time.perf_counter() - s
if e < args.periodic:
time.sleep(args.periodic-e)
except KeyboardInterrupt as e:
except KeyboardInterrupt:
_done = True
else:
show(data, args.route)

23
print2d.py

@ -1,15 +1,27 @@
import datetime
from pydoc import pager
def str_coerce(s, **kwargs):
if isinstance(s, datetime.datetime):
return s.strftime(kwargs['datetime_format'])
else:
return str(s)
def print2d(l,datetime_format = "%A, %B %e, %Y %H:%M:%S",seperator= ' | ',spacer = ' ',bottom = '=',l_end = '|',r_end = '|',interactive = False):
l = [[str_coerce(s,datetime_format = datetime_format) for s in row] for row in l]
def print2d(list_param,
datetime_format="%A, %B %e, %Y %H:%M:%S",
seperator=' | ',
spacer=' ',
bottom='=',
l_end='|', r_end='|',
interactive=False
):
list_param = [[str_coerce(s, datetime_format=datetime_format)
for s in row] for row in list_param]
max_col = []
for row in l:
for row in list_param:
for i, col in enumerate(row):
try:
max_col[i] = max(max_col[i], len(col))
@ -23,8 +35,9 @@ def print2d(l,datetime_format = "%A, %B %e, %Y %H:%M:%S",seperator= ' | ',spacer
fmt_row = '{} {}'.format(fmt_row, r_end)
done = []
for row in l:
content = seperator.join(col.ljust(max_col[i],spacer if i < len(row)-1 or r_end else ' ') for i,col in enumerate(row))
for row in list_param:
content = seperator.join(col.ljust(max_col[i], spacer if i < len(
row)-1 or r_end else ' ') for i, col in enumerate(row))
done.append(fmt_row.format(content=content))
if bottom:

16
search.py

@ -1,18 +1,27 @@
import edlib
def editdistance(a,b):
return edlib.align(a,b)['editDistance']
import re
import json
def editdistance(a, b):
return edlib.align(a, b)['editDistance']
class Search:
def __init__(self, query):
self.raw_lower = query.lower()
def __call__(self, arg):
arg = arg.lower()
return editdistance(self.raw_lower, arg)
def __str__(self):
print(self.raw_lower)
def __repr__(self):
return str(self)
class StopSearch(Search):
def __init__(self, query):
super().__init__(query)
@ -20,6 +29,7 @@ class StopSearch(Search):
parts = re.split(r' ?(?:(?<!\w)and(?!\w)|&) ?', query)
self.query = ' & '.join(parts)
self.query_reversed = ' & '.join(reversed(parts))
def __call__(self, stop):
stop = stop.lower()
paren = re.search(r'\((?P<data>[^\)]+)\)', stop)
@ -35,9 +45,11 @@ class StopSearch(Search):
return min(
ret
)
def __str__(self):
return '{}|{}'.format(self.query, self.query_reversed)
if __name__ == "__main__":
with open('stops_out.json') as file:
data = json.load(file)

Loading…
Cancel
Save