1
0
Fork 0

Fully working version with command line arguments

This commit is contained in:
Luca Beltrame 2020-01-06 04:05:27 +01:00
parent afd8bbe02e
commit 06e31af6ee
Signed by: einar
GPG key ID: 8DF631FD021DB0C5

View file

@ -5,7 +5,7 @@ from dataclasses import dataclass
from datetime import datetime from datetime import datetime
from itertools import zip_longest from itertools import zip_longest
import re import re
from typing import NamedTuple, Optional, List from typing import NamedTuple, Optional, List, Union
from urllib.parse import urlparse, urlencode, urlunparse from urllib.parse import urlparse, urlencode, urlunparse
from bs4 import BeautifulSoup from bs4 import BeautifulSoup
@ -57,8 +57,7 @@ def required_length(nmin, nmax):
class RequiredLength(argparse.Action): class RequiredLength(argparse.Action):
def __call__(self, parser, args, values, option_string=None): def __call__(self, parser, args, values, option_string=None):
if not nmin <= len(values) <= nmax: if not nmin <= len(values) <= nmax:
msg='argument "{f}" requires between {nmin} and {nmax} arguments'.format( msg = f'argument "{self.dest}" requires between {nmin} and {nmax} arguments'
f=self.dest,nmin=nmin,nmax=nmax)
raise argparse.ArgumentTypeError(msg) raise argparse.ArgumentTypeError(msg)
setattr(args, self.dest, values) setattr(args, self.dest, values)
return RequiredLength return RequiredLength
@ -308,7 +307,7 @@ def trip_summary(trip: HyperdiaTrip) -> str:
def hyperdia_search(start_station: str, end_station: str, hour: int, def hyperdia_search(start_station: str, end_station: str, hour: int,
minute: int, day: int = "15", month: str = "08", minute: int, day: int = "15", month: str = "08",
year: int = 2020, max_route: int = 5, year: int = 2020, max_route: int = 5,
via: List[str] = None) -> List[str]: via: List[str] = None, output_type: str = "md"):
# TODO: Error checking # TODO: Error checking
raw_result = get_hyperdia_data(start_station, end_station, raw_result = get_hyperdia_data(start_station, end_station,
@ -318,20 +317,27 @@ def hyperdia_search(start_station: str, end_station: str, hour: int,
results = parse_hyperdia_html(soup, year=year, month=month, day=day) results = parse_hyperdia_html(soup, year=year, month=month, day=day)
for trip in results: for trip in results:
print(trip_summary(trip))
if output_type == "md":
print(trip_summary(trip))
elif output_type == "json":
table = convert_trip_to_table(trip)
print(table.to_json(orient="records"))
def main(): def main():
parser = argparse.argumentParser() parser = argparse.ArgumentParser()
parser.add_argument("-t", "--time", help="Hour of travel", parser.add_argument("-t", "--time", help="Hour of travel",
type=lambda d: datetime.strptime(d, '%H.%M').time()) type=lambda d: datetime.strptime(d, '%H.%M').time())
parser.add_argument("-d", "--date", help="Date of travel", parser.add_argument("-d", "--date", help="Date of travel",
type=lambda d: datetime.strptime(d, "%Y-%m-%d").date()) type=lambda d: datetime.strptime(d, "%Y-%m-%d").date())
parser.add_arguments("--max-routes", help="Maximum number of routes", parser.add_argument("--max-routes", help="Maximum number of routes",
type=int) type=int)
parser.add_argument("--via", nargs='+', action=required_length(1, 3), parser.add_argument("--via", nargs='+', action=required_length(1, 3),
help="Stations to force route through (min 1, max 3)") help="Stations to force route through (min 1, max 3)")
parser.add_argument("--output-type", choices=("md", "json"), default="md",
help="Output type (markdown or JSON)")
parser.add_argument("start_station", help="Start station") parser.add_argument("start_station", help="Start station")
parser.add_argument("end_station", help="End station") parser.add_argument("end_station", help="End station")
@ -347,7 +353,8 @@ def main():
month = str(month) month = str(month)
hyperdia_search(options.start_station, options.end_station, hour, minute, hyperdia_search(options.start_station, options.end_station, hour, minute,
day, month, year, options.max_routes, via=options.via) day, month, year, options.max_routes, via=options.via,
output_type=options.output_type)
if __name__ == "__main__": if __name__ == "__main__":