-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathairport-lookup.py
More file actions
executable file
·88 lines (72 loc) · 2.48 KB
/
airport-lookup.py
File metadata and controls
executable file
·88 lines (72 loc) · 2.48 KB
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
#!/usr/bin/env -S uv --quiet run --no-project --script --
# https://peps.python.org/pep-0723/
# https://github.com/astral-sh/uv
# /// script
# # Docopt issues SyntaxWarning in Python 3.12
# requires-python = ">=3.11,<3.12"
# dependencies = [
# "docopt >=0.6.2",
# "python-dateutil >=2.7.3",
# ]
# ///
"""
Usage:
{prog} (--airport=<airport>)... [--time=<time>]
{prog} --help
{prog} --version
Options:
--airport, -a <airport> Name, IATA/FAA, or ICAO code of the airport to lookup.
--time, -t <time> Date and time in the airport local timezone to calculate.
Please note that the timezone provided in this parameter is ignored.
[default: now]
"""
import sys, csv, urllib.request, cgi, json, datetime
import docopt
import dateutil.parser, dateutil.tz
__prog__ = "airport-lookup.py"
__product__ = f"The {json.dumps(__prog__)} Script"
__version__ = "0.0.0"
def main(*, args):
params = docopt.docopt(
doc=__doc__.format(
prog=__prog__,
),
argv=args,
help=True,
version=__version__,
options_first=False,
)
print(params)
assert params.pop("--help") == False
assert params.pop("--version") == False
lookup_airports = params.pop("--airport")
lookup_time = params.pop("--time")
assert not params, params
airpots_data_url = "https://raw.githubusercontent.com/jpatokal/openflights/master/data/airports.dat"
airpots_data_fieldnames = [
"id", "name", "city", "country", "iata/faa", "icao", "latitude", "longitude",
"elevation", "utcoffset", "unknown_field_1", "timezone", "type", "database",
]
with urllib.request.urlopen(airpots_data_url) as fo:
contentType, contentTypeOptions = cgi.parse_header(fo.info()["Content-Type"])
assert contentType == "text/plain", contentType
charset = contentTypeOptions.pop("charset")
assert not contentTypeOptions, contentTypeOptions
airports = fo.read().decode(charset)
if lookup_time == "now":
lookup_time = datetime.datetime.now()
else:
lookup_time = dateutil.parser.parse(lookup_time)
result = []
reader = csv.DictReader(airports.splitlines(), fieldnames=airpots_data_fieldnames)
for a in reader:
for lookup_airport in lookup_airports:
if lookup_airport not in (a["name"], a["iata/faa"], a["icao"]):
continue
a["datetime"] = "{:%Y-%m-%dT%H:%M:%S%z}".format(
lookup_time.replace(tzinfo=dateutil.tz.gettz(a["timezone"]))
)
result.append(a)
print(json.dumps(result, indent="\t"))
if __name__ == "__main__":
sys.exit(main(args=sys.argv[1:]))