Debian Codegraph @

get_report.py

raw symbols SCIP
1 #!/usr/bin/python
2 #
3 from __future__ import print_function
4
5 import os
6 import sys
7 import getopt
8 import string
9
10 try:
11 from urllib2 import urlopen
12 except:
13 from urllib.request import urlopen
14 from metar import Metar
15
16 BASE_URL = "https://tgftp.nws.noaa.gov/data/observations/metar/stations"
17
18
19 def usage():
20 program = os.path.basename(sys.argv[0])
21 print("Usage: ", program, "<station> [ <station> ... ]")
22 print(
23 """Options:
24 <station> . a four-letter ICAO station code (e.g., "KEWR")
25 """
26 )
27 sys.exit(1)
28
29
30 stations = []
31 debug = False
32
33 try:
34 opts, stations = getopt.getopt(sys.argv[1:], "d")
35 for opt in opts:
36 if opt[0] == "-d":
37 debug = True
38 except:
39 usage()
40
41 if not stations:
42 usage()
43
44 for name in stations:
45 url = "%s/%s.TXT" % (BASE_URL, name)
46 if debug:
47 sys.stderr.write("[ " + url + " ]")
48 try:
49 urlh = urlopen(url)
50 report = ""
51 for line in urlh:
52 if not isinstance(line, str):
53 line = line.decode() # convert Python3 bytes buffer to string
54 if line.startswith(name):
55 report = line.strip()
56 obs = Metar.Metar(line)
57 print(obs.string())
58 break
59 if not report:
60 print("No data for ", name, "\n\n")
61 except Metar.ParserError as exc:
62 print("METAR code: ", line)
63 print(string.join(exc.args, ", "), "\n")
64 except:
65 import traceback
66
67 print(traceback.format_exc())
68 print("Error retrieving", name, "data", "\n")