import argparse
import csv
import datetime
import io
import logging
import pip
try:
import requests
except:
pip.main([\'install\', \'requests\'])
import StringIO
import tempfile
import zipfile
logging.basicConfig(level=logging.DEBUG)
now = datetime.datetime.now()
is_weekday = \'Weekday\'
if now.strftime(\'%w\') == 0 or now.strftime(\'%w\') == 6:
is_weekday = now.strftime(\'%A\')
logging.debug(\'Schedule is {}\'.format(is_weekday))
parser = argparse.ArgumentParser(description=\'Find out when the next Caltrain is\')
parser.add_argument(\'--stop\', type=str, help=\'Stop Name\')
args = parser.parse_args()
# store our times in a list along with which way the train is going
times = []
# retrieve the information from remote
URL = \'http://www.caltrain.com/Assets/GTFS/caltrain/GTFS-Caltrain-Devs.zip\'
ctx = requests.get(URL, stream=True)
tfn = tempfile.NamedTemporaryFile(prefix="caltrain",suffix=".gtfs.zip")
tfn.write(ctx.content)
stop_name = \'\'
with zipfile.ZipFile(tfn, "r") as zipfp:
csv_ = zipfp.open(\'stops.txt\', \'rU\')
reader = csv.DictReader(csv_, fieldnames=[\'stop_id\',\'stop_code\',\'stop_name\',\'stop_desc\',\'stop_lat\',\'stop_lon\',\'zone_id\',\'stop_url\',\'location_type\',\'parent_station\',\'platform_code\'])
for line in reader:
if args.stop.lower() in line[\'stop_name\'].lower():
stop1 = \'{0} -- {1}\'.format(line[\'stop_code\'], line[\'platform_code\'])
stop2 = \'{0} -- {1}\'.format(str(int(line[\'stop_code\'])+1), line[\'platform_code\'])
stop_name = line[\'stop_name\']
break
reader = csv.DictReader(zipfp.open(\'stop_times.txt\',\'rU\'), fieldnames=[\'trip_id\',\'arrival_time\',\'departure_time\',\'stop_id\',\'stop_sequence\',\'pickup_type\',\'drop_off_type\'])
stop_id1 = stop1[:stop1.index(\' -- \')]
stop_id2 = stop2[:stop2.index(\' -- \')]
for line in reader:
if line[\'stop_id\'] == stop_id1:
if is_weekday in line[\'trip_id\']:
depart_time = line[\'departure_time\']
current_time = now.strftime(\'%H:%M:%S\')
if depart_time > current_time:
times.append(depart_time)
elif line[\'stop_id\'] == stop_id2:
if is_weekday in line[\'trip_id\']:
depart_time = line[\'departure_time\']
current_time = now.strftime(\'%H:%M:%S\')
if depart_time > current_time:
times.append(depart_time)
times = sorted(times)
print \'{0}, {1} are your next trains from {2}\'.format(times[0], times[1], stop_name)
tfn.close()