Get aviation METAR text with Python

Published on November 19, 2008

A simple command line tool written in Python to get the latest METAR text from NOAA's Aviation Weather Center.

#! /usr/bin/env python

import BeautifulSoup
import optparse
import urllib
import urllib2

class Metars(object):
    """Gets latest METAR text given 4-letter ICAO station identifier(s) and returns a list."""
    def __init__(self, stations):
        self.stations = stations    
        
    def get_metars(self):
        metars = []
        url = 'http://adds.aviationweather.gov/metars/index.php'
        user_agent = 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 2.0.50727)'
        values = {'station_ids': self.stations}
        headers = {'User-Agent': user_agent}
        data = urllib.urlencode(values)
        req = urllib2.Request(url, data, headers)
        response = urllib2.urlopen(req)
        page = response.read()
        soup = BeautifulSoup.BeautifulSoup(page)
        fontTag = soup.find('font')
        stations = fontTag.findAllNext(text=True)
        metars = [station for station in stations if station.strip('\n')]
                
        return metars
            
def main():
    p = optparse.OptionParser(description=' Returns latest METAR text given a 4-letter ICAO station identifier',
                     usage="usage: %prog station1[,station2]",
                     version="%prog 0.1")
    
    options, arguments = p.parse_args()

    if len(arguments) == 1:
        stations = Metars(arguments[0])
        observations = stations.get_metars()
        if observations:
            for observation in observations:
                print observation
    else:
        p.print_help()
              
if __name__ == '__main__':
    main()

To use it from the command line simply enter a comma separated list of 4-letter ICAO station identifiers.

$ ./metars.py cyvr,cyxx
CYVR 201500Z 00000KT 20SM SCT120 OVC170 05/02 A2979 RMK AC3AC5 SLP088
CYXX 201500Z 00000KT 30SM SCT120 BKN210 07/M02 A2979 RMK AC4CS2 VIRGA SLP090

You can also use it interactively within the Python shell like this,

>>> import metars
>>> stations = metars.Metars("cyvr,cyxx")
>>> observations = stations.get_metars()
>>> observations
[u'CYVR 201500Z 00000KT 20SM SCT120 OVC170 05/02 A2979 RMK AC3AC5 SLP088',
u'CYXX 201500Z 00000KT 30SM SCT120 BKN210 07/M02 A2979 RMK AC4CS2 VIRGA SLP090']

A list of weather stations can be found in the Aviation Weather Center's station.txt file.

Comments are closed.

Comments have been closed for this post.