Debian Codegraph @

misc/getstation.py

raw symbols SCIP
1 #!/usr/bin/python
2 from __future__ import print_function
3 import os
4 import sys
5 import getopt
6 import datetime
7
8 # Python 2 and 3: alternative 4
9 try:
10 from urllib.request import urlopen
11 except ImportError:
12 from urllib2 import urlopen
13
14
15 BASE_URL = "https://tgftp.nws.noaa.gov/data/observations/metar/stations"
16
17
18 def usage():
19 print("Usage: $0 ")
20
21
22 def usage():
23 program = os.path.basename(sys.argv[0])
24 print("Usage: %s [-p] <station> [ <station> ... ]" % (program,))
25 print(
26 """Options:
27 <station> . a four-letter ICAO station code (e.g., "KEWR")
28 -p ........ send downloaded data to stdout, ratherthan a file.
29 """
30 )
31 sys.exit(1)
32
33
34 today = datetime.datetime.now(datetime.timezone.utc)
35
36 stations = []
37 pipe = False
38 debug = False
39
40 try:
41 opts, stations = getopt.getopt(sys.argv[1:], "dp")
42 for opt in opts:
43 if opt[0] == "-p":
44 pipe = True
45 elif opt[0] == "-d":
46 debug = True
47 except Exception as _exp:
48 usage()
49
50 if not stations:
51 usage()
52
53 for name in stations:
54 url = "%s/%s.TXT" % (BASE_URL, name)
55 if debug:
56 sys.stderr.write("[ " + url + " ]")
57 try:
58 urlh = urlopen(url)
59 for line in urlh:
60 line = line.decode("ascii", "ignore")
61 if line.startswith(name):
62 report = line.strip()
63 groups = report.split()
64 if groups[1].endswith("Z"):
65 date_str = "%02d%02d%s-%s" % (
66 today.year - 2000,
67 today.month,
68 groups[1][:2],
69 groups[1][2:],
70 )
71 else:
72 date_str = ("%02d%02d%02d-%02d%02dZ") % (
73 today.year - 2000,
74 today.month,
75 today.day,
76 today.hour,
77 today.minute,
78 )
79 break
80 except Exception as exp:
81 print("Error retrieving %s data\n%s" % (name, exp))
82 continue
83 if pipe:
84 print("%s\n" % (report,))
85 else:
86 fn = "%s-%s.metar" % (name, date_str)
87 print("Saving current METAR report for station %s in %s" % (name, fn))
88 fileh = open(fn, "w")
89 fileh.write(report + "\n")
90 fileh.close()