Newer
Older
tgetwx / tgetwx.py
@tundra tundra on 3 Mar 2014 6 KB Cleaned up time reporting.
#!/usr/bin/env python
# tgetwx.py - Get And Report Weather Conditions
# Copyright (c) 2014 TundraWare Inc., Des Plaines, IL 60018 USA
# All Rights Reserved. For Terms Of Use See: tgetwx-license.txt
# For Program Updates See: http://www.tundraware.com/Software/tgetwx
# $Id: tgetwx.py,v 1.104 2014/03/04 01:12:48 tundra Exp $

# Embed the source control ID string for use by program

CVSID='$Id: tgetwx.py,v 1.104 2014/03/04 01:12:48 tundra Exp $'

#####
# Program Information
#####

PROGNAME = "tgetwx.py"
PROGENV  = "tgetwx".upper()
VERSION  = CVSID.split()[2]
PROGVER  = PROGNAME + " " + VERSION + " - Get And Report Weather Conditions"


#####
# Copyright Information
#####

COPYRIGHT    = "Copyright (c) 2014 TundraWare Inc., Des Plaines, IL 60018 USA"

#####
# List Of All Legal Options - Update This When You Add More!!!!
#####

OPTIONSLIST = 'Hhv'


#----------------------------------------------------------#
#            Variables User Might Change                   #
#----------------------------------------------------------#



#------------------- Nothing Below Here Should Need Changing ------------------#


#----------------------------------------------------------#
#                       Imports                            #
#----------------------------------------------------------#

import getopt
import json
import os
import sys
import time
import urllib2


#----------------------------------------------------------#
#                 Aliases & Redefinitions                  #
#----------------------------------------------------------#



#----------------------------------------------------------#
#                Constants & Literals                      #
#----------------------------------------------------------#



#####
# Constants
#####

KELVIN = 273.15

#####
# Literals
#####

WEATHERURL = 'http://api.openweathermap.org/data/2.5/weather?q=%s'


#----------------------------------------------------------#
#              Prompts, & Application Strings              #
#----------------------------------------------------------#


#####
# Error Messages
#####

eBADARG      =  "Invalid command line: %s!"
eBADLOCATION =  "Location, %s, Not Found!"
eERROR       =  "ERROR"
eLOOKUPFAIL  =  "Weather Lookup For, %s, Failed!"


#####
# Usage Prompts
#####

# Make the options list more human readable

optionslist =  OPTIONSLIST.replace(':', ' arg -').strip()
if optionslist[-1] == '-':
    optionslist = optionslist[:-1].strip()

uTable = [PROGVER,
          "usage:  " + PROGNAME + " [%s]" % optionslist,
          "   where,",
          "          -H       Generate HTML (default: Plain Text)",
          "          -h       Print this help information",
          "          -v       Print detailed version information",
          ]


#----------------------------------------------------------#
#          Global Variables & Data Structures              #
#----------------------------------------------------------#

HTMLOUT = False


#--------------------------- Code Begins Here ---------------------------------#


#----------------------------------------------------------#
#             Object Base Class Definitions                #
#----------------------------------------------------------#

    

#----------------------------------------------------------#
#                General Utility Functions                 #
#----------------------------------------------------------#


def ColumnPad(list, padchar=" ", padwidth=20):

    retval = ""
    for l in list:
        l = str(l)
        retval += l + ((padwidth - len(l)) * padchar)

    return retval.strip()

# End of 'ColumnPad()'


#####
# Print An Error Message
#####

def ErrorMsg(emsg):
    PrintStderr(PROGNAME + " " + eERROR + ": " + emsg)

# End of 'ErrorMsg()'


#####
# Print To stderr
#####

def PrintStderr(msg, trailing="\n"):
    sys.stderr.write(msg + trailing)

# End of 'PrintStderr()'


#####
# Print To stdout
#####

def PrintStdout(msg, trailing="\n"):
    sys.stdout.write(msg + trailing)

# End of 'PrintStdout'


#####
# Print Usage Information
#####

def Usage():
    for line in uTable:
        PrintStdout(line)

# End of 'Usage()'


#----------------------------------------------------------#
#                Program-Specific Functions                #
#----------------------------------------------------------#


def ReportWeather(location, EmitHTML):

    results = []

    try:
        f = urllib2.urlopen(WEATHERURL % location)
        lookup = f.read()

    except:
        results.append(eLOOKUPFAIL % s)

    finally:
        f.close()

    data = json.loads(lookup)
    # Handle cities not found
    if "message" in data:
        results.append(data["message"])

    # Lookup was successful, populate data
    else:

        # Order is City Name, Country, Date, Temp, Humidity, Pressure, Wind Speed, Wind Direction, Cloud Cover, Description
        
        results.append(data["name"])
        results.append(data["sys"]["country"])
        results.append(time.strftime("%D %H:%M", time.localtime(int(data["dt"]))))
        results.append("%.0f" % (((data["main"]["temp"] - KELVIN) * 9/5) + 32) + "F" )
        results.append("%.0f" % (data["main"]["humidity"])+ "%")
        results.append("%.2f" % (data["main"]["pressure"] * 0.0295299830714) + "in")
        results.append("%.1f" % (data["wind"]["speed"]) + "mph")
        results.append("%.0f" % (data["wind"]["deg"])   + "deg")
        results.append("%.0f" % (data["clouds"]["all"]) + "%")
        results.append(data["weather"][0]["description"])
        
        

    if EmitHTML:
        print "This is where HTML will come out!"

    else:
        print results



    

    

    

# End of 'ReportWeather()'


#----------------------------------------------------------#
#                    Program Entry Point                   #
#----------------------------------------------------------#

# Command line processing - Process any options set in the
# environment first, and then those given on the command line

OPTIONS = sys.argv[1:]
envopt = os.getenv(PROGENV)
if envopt:
    OPTIONS = envopt.split() + OPTIONS

try:
    opts, args = getopt.getopt(OPTIONS, OPTIONSLIST)

except getopt.GetoptError, (errmsg, badarg):

    ErrorMsg(eBADARG % errmsg)
    sys.exit(1)

for opt, val in opts:

    if opt == "-H":
        HTMLOUT =  True

    if opt == "-h":
        Usage()
        sys.exit(0)

    if opt == "-v":
        PrintStdout(CVSID)
        sys.exit(0)


# Command line arguments are presumed to be locations to lookup

for location in args:
    ReportWeather(location, HTMLOUT)