コード例 #1
0
ファイル: get_weather.py プロジェクト: Javafab/PM_2015_SUMMER
    def get_weather(self, location_id):
        """
        can enter location ID from weather.com
        or 5 digit zip code
        """
        if len(location_id) < 5:
            results = "No match for location entered could be found."

        elif len(location_id) == 5:
            weather_com_result = pywapi.get_weather_from_weather_com(location_id, units="imperial")
            results = (
                "According to Weather.com: It is "
                + string.lower(weather_com_result["current_conditions"]["text"])
                + " and "
                + weather_com_result["current_conditions"]["temperature"]
                + "F now in zip code %s .\n\n" % location_id
            )

        else:
            weather_com_result = pywapi.get_weather_from_weather_com(location_id, units="imperial")
            results = (
                "According Weather.com: It is "
                + string.lower(weather_com_result["current_conditions"]["text"])
                + " and "
                + weather_com_result["current_conditions"]["temperature"]
                + "F now in %s.\n\n" % self.given_location
            )
        return results
コード例 #2
0
ファイル: weather.py プロジェクト: jbkuczma/PythonScripts
def getWeather():
    global cityID_, zip_, city_, temperature_, conditions_
    if city_ != "":
        city = pywapi.get_location_ids(city_)
        cityID = list(city.keys())
        tmp = list(city.values())
        city_ = tmp[0]
        cityID_ = cityID
        result = pywapi.get_weather_from_weather_com(cityID[0])
        conditions_ = str(result['current_conditions']['text'])
        temperature_ = float(result['current_conditions']['temperature']) * 1.8 + 32
    else:
        newCity = ""
        zip = pywapi.get_location_ids(zip_)
        cityName = list(zip.values())
        for i in cityName[0]:
            if not i.isdigit() and i != '(' and i != ')':
                newCity += i
        city_ = newCity
        cityList = pywapi.get_location_ids(newCity)
        cityID = list(cityList.keys())
        cityID_ = cityID
        result = pywapi.get_weather_from_weather_com(cityID[0])
        conditions_ = str(result['current_conditions']['text'])
        temperature_ = float(result['current_conditions']['temperature']) * 1.8 + 32
コード例 #3
0
ファイル: fetchdata.py プロジェクト: tloeb/CCC
def getData():
	cities = pywapi.get_cities_from_google('de') # or (country = 'fr', hl = 'de')
	locidparis = pywapi.get_loc_id_from_weather_com("Paris")
	locidbs = pywapi.get_loc_id_from_weather_com("Braunschweig")
	locidlondon = pywapi.get_loc_id_from_weather_com("London")

	Bs = pywapi.get_weather_from_weather_com("GMXX0013")
	Paris = pywapi.get_weather_from_weather_com("FRXX0076")
	London = pywapi.get_weather_from_weather_com("UKXX0085")

	datetime = time.strftime("Date: %d-%B-%Y  Time: %H:%M:%S")

	tempBs = str(Bs['current_conditions']['temperature'])
	tempLondon = str(London['current_conditions']['temperature'])
	tempParis = str(Paris['current_conditions']['temperature'])

##	pp.pprint(datetime)
##	pp.pprint("Aktuelle Temperatur in Braunschweig: " + tempBs +" Grad")
##	pp.pprint("Aktuelle Temperatur in London: " + tempLondon +" Grad")
##	pp.pprint("Aktuelle Temperatur in Paris: " + tempParis +" Grad")

	werte = [('Braunschweig', tempBs, str(datetime)),
                 ('London', tempLondon, str(datetime)),
                 ('Paris', tempParis, str(datetime))]
	cursor.executemany("INSERT INTO temperatures VALUES (?,?,?)", werte)
	connection.commit()
コード例 #4
0
    def weersomstandigheden():
        """Haalt huidige weersomstandigheden van weather.com."""
        global weather_com_result_hvh, weather_com_result_r, weather_com_result_d
        weather_com_result_hvh = pywapi.get_weather_from_weather_com('NLXX0025', units='metric')
        weather_com_result_r = pywapi.get_weather_from_weather_com('NLXX0015', units='metric')
        weather_com_result_d = pywapi.get_weather_from_weather_com('NLXX0006', units='metric')

        root.after(60000, weersomstandigheden)
コード例 #5
0
    def weersomstandigheden_pred():
        """Haalt huidige weersomstandigheden van weather.com."""
        global weather_com_pred_hvh, weather_com_pred_r, weather_com_pred_d, dag1, dag2, dag3, dag4
        try:
            weather_com_pred_hvh = pywapi.get_weather_from_weather_com( 'NLXX0025', units = 'metric' )
            weather_com_pred_r = pywapi.get_weather_from_weather_com( 'NLXX0015', units = 'metric' )
            weather_com_pred_d = pywapi.get_weather_from_weather_com( 'NLXX0006', units = 'metric' )

            dag1 = weather_com_pred_hvh['forecasts'][1]['date']
            dag2 = weather_com_pred_hvh['forecasts'][2]['date']
            dag3 = weather_com_pred_hvh['forecasts'][3]['date']
            dag4 = weather_com_pred_hvh['forecasts'][4]['date']

        except:
            print("Kan weersvoorspelling niet ophalen.")
コード例 #6
0
ファイル: basic_functions.py プロジェクト: reybre/AI-Morty
def weather(loc,type):


    '''
    tells you the weather
    :param loc: a str containing a location
    :param type: the type of weather asked for (current only works right now)
    :return:
    '''

    lookup = pywapi.get_location_ids(loc)
    loc_id='blank'
    for i in lookup:
        loc_id = i
    if(loc_id=='blank'):
        print("\n\nI couldn't figure out where " + loc + " is, try again?")
        return 0
    weather_com_result = pywapi.get_weather_from_weather_com(loc_id,'imperial')
    try:
        if(type=='current'):

            text = weather_com_result['current_conditions']['text']

            if text == 'N/A':
                text = "I dont know current cloud conditions here :("
            temp = str(weather_com_result['current_conditions']['temperature'])
            moon = weather_com_result['current_conditions']['moon_phase']['text']
            print("\n\nAcquiring current conditions in " + weather_com_result['location']['name'] + "\n" + text +
                 "\nTemperature is " + temp + '\nMoon phase is ' + moon )
    except KeyError or IndexError or ValueError:

        print("\n\nSorry, something broken...\n\nTry again!")
        pass
コード例 #7
0
def forecast(bot, event, *args):
    if args:
        place = ' '.join(args)
        lookup = pywapi.get_location_ids(place)
        for i in lookup:
            location_id = i
    else:
        location_id = 'USVA0140'
        yield from bot.coro_send_message(event.conv, _("No location given; defaulting to Chantilly, VA"))
    weather_com_result = pywapi.get_weather_from_weather_com(
        location_id, units='imperial')
    place = weather_com_result['location']['name']
    high = weather_com_result['forecasts'][1]['high']
    low = weather_com_result['forecasts'][1]['low']
    day = weather_com_result['forecasts'][1]['day']['text']
    if day == '':
        day = 'N/A'
    night = weather_com_result['forecasts'][1]['night']['text']
    if night == '':
        night = 'N/A'
    date = weather_com_result['forecasts'][1]['date']
    url = links.shorten(
        'http://www.weather.com/weather/today/l/' + location_id)
    msg = _("<b>Forecast for {} on {}:</b><br>Conditions: Day - {}; Night - {}<br>High: {}<br>Low: {}<br>For more information visit {}").format(
        place, date, day, night, high, low, url)
    yield from bot.coro_send_message(event.conv, msg)
コード例 #8
0
ファイル: reply.py プロジェクト: etsa/WeatherTweeter
 def on_status(self, status):
     print status.text
     reply = status.user.screen_name
     print status.user.screen_name
     weather_com_result = pywapi.get_weather_from_weather_com('zipcodehere', units ='imperial') #can be imperial or metric
     now = time.strftime("[%I:%M %p] ")
     api.update_status(now + "@" + reply + " It is currently " + weather_com_result['current_conditions']['text'].lower() + " and " + weather_com_result['current_conditions']['temperature'] + "F.", in_reply_to_status_id = status.id)
コード例 #9
0
def handle(text, mic, profile):
    filename = "Weather.CSV"
    weather_com_result = pywapi.get_weather_from_weather_com('NPXX0002')
    weather_status = weather_com_result['current_conditions']['text'] 
    weather_felttemp = weather_com_result['current_conditions']['feels_like']
    weather = "The weather conditions are "+weather_status+" with a felt temperature of "+ weather_felttemp+ " degrees Celsius. "
    rainprop = rainchance(weather_com_result['forecasts'])
    text =  '"' + weather_status + '"' + ',"' +weather_felttemp + "Celsius" + '"' + ',"' + rainprop +'"'
    logdata(filename,text)
    if ("clothes" in text.lower()) or ("wear" in text.lower()):
        chance_rain = rain(weather_com_result['forecasts'])
        felttemp_int = int(weather_felttemp)
        weather_suggestion = temperatureSuggestion(felttemp_int)
        weather_suggestion += chance_rain
        
        mic.say(weather_suggestion)

    elif ("hot" in text.lower()) or ("temperature" in text.lower()) or ("cold" in text.lower()):
        mic.say("There's currently a felt temperature of "+weather_felttemp+" degrees Celsius.")	
    elif "rain" in text.lower():
        rainprop = "Chance of" + rain(weather_com_result['forecasts'])
        mic.say(rainprop)

    else :
    	mic.say(weather)
コード例 #10
0
ファイル: plugin.py プロジェクト: plotaBot/rpi_wordclock
    def run(self, wcd, wci):
        """
        Displaying expected temperature
        """
        # Get current forecast
        if self.weather_service == 'yahoo':
            current_weather_forecast = pywapi.get_weather_from_yahoo(self.location_id)
        elif self.weather_service == 'weather_dot_com':
            current_weather_forecast = pywapi.get_weather_from_weather_com(self.location_id)
        else:
            print('Warning: No valid weather_forecast found!')
            return
        outdoor_temp = current_weather_forecast['current_conditions']['temperature']
        if self.temp_sensor_registered:
            try:
                indoor_temp = str(int(round(am2302_ths.get_temperature(self.pin_temp_sensor))))
                wcd.showText(outdoor_temp + '*', count=1, fps=8)
                wcd.showText(indoor_temp + '*', count=1, fg_color=wcc.GREEN, fps=8)
                wcd.showText(outdoor_temp + '*', count=1, fps=8)
                wcd.showText(indoor_temp + '*', count=1, fg_color=wcc.GREEN, fps=8)
            except:
                print('  Failed to read temperature sensor!')
                wcd.showText(outdoor_temp + '*   ' + outdoor_temp + '*   ' + outdoor_temp + '*', count=1, fps=8)
        else:
            wcd.showText(outdoor_temp + '*   ' + outdoor_temp + '*   ' + outdoor_temp + '*', count=1, fps=8)

        if wci.waitForExit(1.0):
            return
コード例 #11
0
ファイル: weather.py プロジェクト: jbkuczma/PythonScripts
def printWeather(choice):
    if str(choice) != str(1):
        print("-----------------------------------------------")
        print("City: " + str(city_))
        print("Zip: " + str(zip_))
        print("Temperature: " + str(temperature_) + "°F")
        print("Conditions: " + str(conditions_))
        print("-----------------------------------------------")
        exit(0)
    else:
        result = pywapi.get_weather_from_weather_com(str(cityID_[0]))
        print("----------- Current Conditions ----------------")
        print("City: " + str(city_))
        print("Zip: " + str(zip_))
        print("Temperature: " + str(temperature_) + "°F")
        print("Conditions: " + str(conditions_) + '\n')
        print("----------- 5 Day Forecast --------------------")
        for i in range(0, 5):
            date = str(result['forecasts'][i]['date'])
            dayofweek = str(result['forecasts'][i]['day_of_week'])
            conditions = str(result['forecasts'][i]['day']['brief_text'])
            high = str(float(result['forecasts'][i]['high']) * 1.8 + 32)
            low = str(float(result['forecasts'][i]['low']) * 1.8 + 32)
            print(dayofweek + "," + date + ": High: " + high + "°F Low: " + low + "°F Forecast: " + conditions)
        print("-----------------------------------------------")
コード例 #12
0
    def run(self, wcd, wci):
        """
        Displaying expected temperature
        """
        # Get current forecast
        if self.weather_service == "yahoo":
            current_weather_forecast = pywapi.get_weather_from_yahoo(self.location_id)
        elif self.weather_service == "weather_dot_com":
            current_weather_forecast = pywapi.get_weather_from_weather_com(self.location_id)
        else:
            print("Warning: No valid weather_forecast found!")
            return
        outdoor_temp = current_weather_forecast["current_conditions"]["temperature"]
        if self.temp_sensor_registered:
            try:
                indoor_temp = str(int(round(am2302_ths.get_temperature(4))))
                wcd.showText(outdoor_temp + "*", count=1, fps=8)
                wcd.showText(indoor_temp + "*", count=1, fg_color=wcc.GREEN, fps=8)
                wcd.showText(outdoor_temp + "*", count=1, fps=8)
                wcd.showText(indoor_temp + "*", count=1, fg_color=wcc.GREEN, fps=8)
            except:
                print("  Failed to read temperature sensor!")
                wcd.showText(outdoor_temp + "*   " + outdoor_temp + "*   " + outdoor_temp + "*", count=1, fps=8)
        else:
            wcd.showText(outdoor_temp + "*   " + outdoor_temp + "*   " + outdoor_temp + "*", count=1, fps=8)

        time.sleep(1)
コード例 #13
0
def lookup_weather(name):
	import pywapi
	import pprint
	
	myzip_file = open ("/home/pi/421_521_final_project/Anand_Test/Personal_Stuff/ZCode/" + name + "_myzip" + ".txt", 'r')		
	myzip = myzip_file.read()
	#this will give you a dictionary of all cities in the world with this city's name - be specific
	#myzip = str(input("Please enter your zipcode "))
	
	fname = "/home/pi/421_521_final_project/Anand_Test/US/US.txt"
	with open(fname) as fin:
		data_str = fin.read()
	
	#create a list of lists
	data_list = []
	for line in data_str.split('\n'):
		mylist = line.split('\t')
		if len(mylist) > 11:
			data_list.append(mylist)
	
	for sublist in data_list:
		zip_code = sublist[1]
		if zip_code == myzip:
			location = "{}, {} {}".format(sublist[2], sublist[3], myzip)
		 
	#location_id now contains the city's code
	weather_com_result = pywapi.get_weather_from_weather_com(myzip, units = 'imperial')
	
	#Prints the current weather and the three day forecast
	print ("Current weather: " +  weather_com_result['current_conditions']['text'].lower() + " and " + weather_com_result['current_conditions']['temperature'] + " F in " + location + " with a " + weather_com_result['forecasts'][0]['day']['chance_precip'] + "% chance of precipitation.")
	print ("Tomorrow's forecast: (" + weather_com_result['forecasts'][1]['date'] + ") is a high/low of " + weather_com_result['forecasts'][1]['high'] + '/' + weather_com_result['forecasts'][1]['low'] + " F with a " + weather_com_result['forecasts'][1]['day']['chance_precip'] + "% chance of precipitation.") 
	print ("2 days from now: (" + weather_com_result['forecasts'][2]['date'] + ") is a high/low of " + weather_com_result['forecasts'][2]['high'] + '/' + weather_com_result['forecasts'][2]['low'] + " F with a " + weather_com_result['forecasts'][2]['day']['chance_precip'] + "% chance of precipitation.")
	print ("3 days from now: (" + weather_com_result['forecasts'][3]['date'] + ") is a high/low of " + weather_com_result['forecasts'][3]['high'] + '/' + weather_com_result['forecasts'][3]['low'] + " F with a " + weather_com_result['forecasts'][3]['day']['chance_precip'] + "% chance of precipitation." )
コード例 #14
0
ファイル: app.py プロジェクト: arushshah/SmartHands
def weather():
	city = pywapi.get_weather_from_weather_com('USNJ0190')

	curr_temp = c_to_f(int(city['current_conditions']['temperature']))
	curr_real_feel = c_to_f(int(city['current_conditions']['feels_like']))
	curr_wind_speed = int(city['current_conditions']['wind']['speed'])
	curr_wind_dir = city['current_conditions']['wind']['text']
	text = city['current_conditions']['text']
	curr_humidity = city['current_conditions']['humidity']

	tonight_temp = c_to_f(int(city['forecasts'][0]['low']))
	tonight_wind_speed = int(city['forecasts'][0]['night']['wind']['speed'])
	tonight_text = city['forecasts'][0]['night']['text']
	tonight_wind_dir = city['forecasts'][0]['night']['wind']['text']

	tomorrow_temp = c_to_f(int(city['forecasts'][1]['high']))
	tomorrow_wind_speed = int(city['forecasts'][1]['day']['wind']['speed'])
	tomorrow_text = city['forecasts'][1]['day']['text']
	tomorrow_wind_dir = city['forecasts'][1]['day']['wind']['text']

	ser = serial.Serial('COM3', 9600)
	message = ser.readline()
	ser.write(message)

	return render_template('weather.html', temp=curr_temp, actual_temp=curr_real_feel, wind_speed=curr_wind_speed, status=text, 
		humidity=curr_humidity, wind_direction = curr_wind_dir, night_temp=tonight_temp, night_wind_speed=tonight_wind_speed, 
		night_wind_dir=tonight_wind_dir, night_status=tonight_text, tom_temp=tomorrow_temp, tom_wind_speed=tomorrow_wind_speed,
		tom_status=tomorrow_text, tom_wind_dir=tomorrow_wind_dir)
コード例 #15
0
def lookup_weather():
    import pywapi
    import pprint

    city_file = open("/home/pi/421_521_final_project/Anand_Test/Personal_Stuff/city/Dan_city.txt", "r")
    city = city_file.read()
    # this will give you a dictionary of all cities in the world with this city's name - be specific
    print("Your city is " + city)

    lookup = pywapi.get_location_ids(city)

    # workaround to access last item of dictionary
    for i in lookup:
        location_id = i

        # location_id now contains the city's code
    weather_com_result = pywapi.get_weather_from_weather_com(location_id)

    print(
        "The current weather is "
        + weather_com_result["current_conditions"]["text"].lower()
        + " and  "
        + weather_com_result["current_conditions"]["temperature"]
        + "C in "
        + city
        + "."
    )
コード例 #16
0
ファイル: weather.py プロジェクト: jasonkuehl/JasperModules
def handle(text, mic, profile):
    
    weather_com_result = pywapi.get_weather_from_weather_com('SZXX0728')
    weather_status = weather_com_result['current_conditions']['text'] 
    weather_felttemp = weather_com_result['current_conditions']['feels_like']
    weather = "The weather conditions are "+weather_status+" with a felt temperature of "+ weather_felttemp+ " degrees Celsius. "

    if ("clothes" in text.lower()) or ("wear" in text.lower()):

        chance_rain = rain(weather_com_result['forecasts'])
        felttemp_int = int(weather_felttemp)
        weather_suggestion = temperatureSuggestion(felttemp_int)

        weather_suggestion += chance_rain
        
        mic.say(weather_suggestion)

    elif ("hot" in text.lower()) or ("temperature" in text.lower()) or ("cold" in text.lower()):
	mic.say("There's currently a felt temperature of "+weather_felttemp+" degrees Celsius.")	
    elif "rain" in text.lower():
	rainprop = rain(weather_com_result['forecasts'])
	mic.say(rainprop)

    else :
    	mic.say(weather)
コード例 #17
0
ファイル: clock.py プロジェクト: JBarrada/7seg
def blink_weather():
    weather_com_result = pywapi.get_weather_from_weather_com("78728")
    mycol = random.randint(0, 6)

    temp_now_f = str(int(float(weather_com_result["current_conditions"]["temperature"]) * 1.8 + 32.0))
    for ch in temp_now_f:
        mycol = (mycol + 1) % 7
        display.set_display_fade(int(ch), False, colors[mycol], 300)
    mycol = (mycol + 1) % 7
    display.set_display_fade(17, False, colors[mycol], 300)
    mycol = (mycol + 1) % 7
    display.set_display_fade(15, False, colors[mycol], 300)
    time.sleep(0.5)

    mycol = (mycol + 1) % 7
    temp_now_c = weather_com_result["current_conditions"]["temperature"]
    for ch in temp_now_c:
        mycol = (mycol + 1) % 7
        display.set_display_fade(int(ch), False, colors[mycol], 300)
    mycol = (mycol + 1) % 7
    display.set_display_fade(17, False, colors[mycol], 300)
    mycol = (colors.index(display.current_color) + 1) % 7

    display.set_display_fade(12, False, colors[mycol], 300)

    time.sleep(1)
コード例 #18
0
ファイル: voiceWeather.py プロジェクト: qpaulson/VoiceExec
    def speakWeather( config, string ):
        location_code = config.get( "weather", "weather_location_code" )

        weather_com_result = pywapi.get_weather_from_weather_com( str(location_code ))
        print weather_com_result
        print string


        lookupString = ''
        ### TODAY
        if ( re.compile( "today", re.IGNORECASE ).findall( string ,1 )):
            todayData = weather_com_result['forecasts'][0]
            if ( todayData['day']['text'] != 'N/A' ):
                    if ( int( todayData['day']['chance_precip'] ) > 40 ):
                        lookupString = "Today will be " + str( todayData['day']['text'] ) + " with a chance of showers and a high of " + str( todayData['high'] ) + "degrees"
                    else:
                        lookupString = "Today will be " + str( todayData['day']['text'] ) + " with a high of " + str( todayData['high'] ) + "degrees"
            else:
                    if ( int(todayData['night']['chance_precip'] ) > 40 ):
                        lookupString = "Tonight will be " + str( todayData['night']['text'] ) + " with a chance of showers"
                    else:
                        lookupString = "Tonight will be " + str( todayData['night']['text'] )


        ### TONIGHT
        elif ( re.compile( "tonight", re.IGNORECASE).findall( string ,1 )):
            todayData = weather_com_result['forecasts'][0]
            if ( int(todayData['night']['chance_precip'] ) > 40 ):
                lookupString = "Tonight will be " + str( todayData['night']['text'] ) + " with a chance of showers"
            else:
                lookupString = "Tonight will be " + str( todayData['night']['text'] )

        ### Tomorrow Night
        elif ( re.compile( "tomorrow night", re.IGNORECASE).findall( string ,1 )):
            todayData = weather_com_result['forecasts'][1]
            if ( int(todayData['night']['chance_precip'] ) > 40 ):
                lookupString = "Tomorrow night will be " + str( todayData['night']['text'] ) + " with a chance of showers"
            else:
                lookupString = "Tomorrow night will be " + str( todayData['night']['text'] )

        ### TODAY
        elif ( re.compile( "tomorrow", re.IGNORECASE ).findall( string ,1 )):
            todayData = weather_com_result['forecasts'][1]
            if ( todayData['day']['text'] != 'N/A' ):
                    if (( int( todayData['day']['chance_precip'] ) > 40 ) or ( int( todayData['night']['chance_precip'] ) > 40 )):
                        lookupString = "Tomorrow will be " + str( todayData['day']['text'] ) + " with a chance of showers and a high of " + str( todayData['high'] ) + " degrees"
                    else:
                        lookupString = "Tomorrow will be " + str( todayData['day']['text'] ) + " with a high of " + str( todayData['high'] ) + "degrees"


        else:
            lookupString = "It is currently " + str(weather_com_result['current_conditions']['text']) + " and " + weather_com_result['current_conditions']['temperature'] + "degrees.\n\n"


        print lookupString
        ## Work our magic
        if ( lookupString != '' ):
            GoogleSpeech.tts( lookupString )
        else:
            GoogleSpeech.tts( "Sorry, Weather information un-available at this time, please try again later" )
コード例 #19
0
def lookup_weather(name):
	#Imports the relevant modules
	import pywapi
	import pprint
	
	#Opens the folder ZCode and imports the text file containing the user specified zipcode
	myzip_file = open ("/home/pi/421_521_final_project/Code/Personal_Stuff/ZCode/" + name + "_myzip" + ".txt", 'r')		
	myzip = myzip_file.read()
	
	#Opens the US.txt file, which contains a list of the US zip codes with corresponding city, state identifers
	fname = "/home/pi/421_521_final_project/Code/US/US.txt"
	with open(fname) as fin:
		data_str = fin.read()
	
	#Create a list of lists
	data_list = []
	for line in data_str.split('\n'):
		mylist = line.split('\t')
		if len(mylist) > 11:
			data_list.append(mylist)
	
	#Searches the lists to find the city and state location corresponding to the input zip code
	for sublist in data_list:
		zip_code = sublist[1]
		if zip_code == myzip:
			location = "{}, {} {}".format(sublist[2], sublist[3], myzip)
		 
	#From the pywapi python module pulls the weather information for the input zip code and converts the units to imperial (fahrenheit)
	weather_com_result = pywapi.get_weather_from_weather_com(myzip, units = 'imperial')
	
	#Prints the current weather and the three day forecast as well the current city, state
	print ("Current weather: " +  weather_com_result['current_conditions']['text'].lower() + " and " + weather_com_result['current_conditions']['temperature'] + " F in " + location + " with a " + weather_com_result['forecasts'][0]['day']['chance_precip'] + "% chance of precipitation.")
	print ("Tomorrow's forecast: (" + weather_com_result['forecasts'][1]['date'] + ") is a high/low of " + weather_com_result['forecasts'][1]['high'] + '/' + weather_com_result['forecasts'][1]['low'] + " F with a " + weather_com_result['forecasts'][1]['day']['chance_precip'] + "% chance of precipitation.") 
	print ("2 days from now: (" + weather_com_result['forecasts'][2]['date'] + ") is a high/low of " + weather_com_result['forecasts'][2]['high'] + '/' + weather_com_result['forecasts'][2]['low'] + " F with a " + weather_com_result['forecasts'][2]['day']['chance_precip'] + "% chance of precipitation.")
	print ("3 days from now: (" + weather_com_result['forecasts'][3]['date'] + ") is a high/low of " + weather_com_result['forecasts'][3]['high'] + '/' + weather_com_result['forecasts'][3]['low'] + " F with a " + weather_com_result['forecasts'][3]['day']['chance_precip'] + "% chance of precipitation." )
コード例 #20
0
	def __init__(self, setCity, setLocation, setUnits = "metric"):
		self.location = setLocation
		self.units = setUnits
		self.city = setCity
		self.weatherData = pywapi.get_weather_from_weather_com(self.location, units = self.units )
		self.astrology = Astral()
		self.sunLocation = self.astrology[self.city]
コード例 #21
0
ファイル: weather.py プロジェクト: sebastien247/sixthsensepy
    def Weather(self):
        for i in self.trying:
            i.Destroy()
            
        self.trying = []
        sizer = wx.GridBagSizer()
        temp_actuel=T.time()
        weather_com_result = pywapi.get_weather_from_weather_com('10001')
        yahoo_result = pywapi.get_weather_from_yahoo('10001')
        noaa_result = pywapi.get_weather_from_noaa('KJFK')
        weather1 = self.trying.append(wx.StaticText(self.BoxStock,-1,str("Yahoo says: It is " + string.lower(yahoo_result['condition']['text']) + " and " +
         yahoo_result['condition']['temp'] + " C now "),pos=(50,50)))
       # labelStock = wx.StaticText(self.BoxStock,-1,label=weather1,pos=(30,30))
        #self.text.SetLabel(str(labelStock))
        #weather2 = "Weather.com says: It is " + string.lower(weather_com_result['current_conditions']['text']) + " and " + weather_com_result['current_conditions']['temperature'] + " C now "
        #labelStock = wx.StaticText(self.BoxStock,label=weather2,pos=(30,80))
        #self.text.SetLabel(str(labelStock))

        wx.CallLater(10000,self.Weather)
        message=string.lower(yahoo_result['condition']['text'])
        if message=="fair":
            #from PIL import Image
            #bidule = Image.open("image/nuage-noir-avec-de-la-pluie.jpg")
            #bidule.show()
            
            app= Application(redirect=True)
            app.MainLoop()
コード例 #22
0
ファイル: aicontroller.py プロジェクト: matbaj/cambot
	def weather(self, order):
		words = order.split(" ")
		try:
			city_index = words.index("in") + 1
		except ValueError:
			self.add_anger()
			print "Wrong syntax"
			return("No!")
		if words[city_index] == "city":
			city_index+=1
		if words[-1] == "please":
			city_arr = words[city_index:-1]
			self.add_please()
		else:
			city_arr = words[city_index:]
		city = " ".join(city_arr)
		loc_id = pywapi.get_location_ids(city)
		city_id = self.get_city_id(loc_id)
		try:
			self.add_please()
			all_info = pywapi.get_weather_from_weather_com( city_id , units = 'metric' )
			weather = all_info['current_conditions']['temperature'] 
			text = all_info['current_conditions']['text']
			weather_respone = ('It is ' + text + ', Temperature: ' + weather  + ' celsius degrees in ' + city)
			return(weather_respone)
		except:
			e = sys.exc_info()[0]
			print "Error: %s" % e 
			print "Weather occurs some problems"
			return("NO!")
コード例 #23
0
def weather(bot, event, *args):
    '''Gets weather from weather.com. Defaults to Chantilly, VA if no location given. Format is /bot weather <city>,<state/country>'''
    try:
        if args:
            place = ' '.join(args)
            lookup = pywapi.get_location_ids(place)
            for i in lookup:
                location_id = i
        else:
            location_id = 'USVA0140'
            yield from bot.coro_send_message(event.conv, _("No location given; defaulting to Chantilly, VA"))
        weather_com_result = pywapi.get_weather_from_weather_com(
            location_id, units='imperial')
        condition = weather_com_result['current_conditions']['text'].lower()
        temp = weather_com_result['current_conditions']['temperature']
        feelslike = weather_com_result['current_conditions']['feels_like']
        place = weather_com_result['location']['name']
        url = links.shorten(
            'http://www.weather.com/weather/today/l/' + location_id)
        msg = _('<b>Today in {}:</b><br>Temp: {}°F (Feels like: {}°F)<br>Conditions: {}<br>For more information visit {}').format(
            place, temp, feelslike, condition, url)
        yield from bot.coro_send_message(event.conv, msg)
    except BaseException as e:
        msg = _('{} -- {}').format(str(e), event.text)
        yield from bot.coro_send_message(CONTROL, msg)
コード例 #24
0
ファイル: main.py プロジェクト: ben-e-whitney/pack-me-up
def get_trip_info(args):
    info = vars(args)
    #TODO: add something for when forecast cannot be fetched.
    forecasts = pywapi.get_weather_from_weather_com(info['zip_code'],
        units='imperial')['forecasts']
    if len(forecasts) < info['days']+1:
        print('warning: forecast unavailable for part of trip duration')
    info.update(minimum_temperature=min(float(daily['low'])
        for daily in forecasts[1:info['days']+1]))
    info.update(maximum_temperature=max(float(daily['high'])
        for daily in forecasts[1:info['days']+1]))

    prob_no_rain = 1
    prob_no_snow = 1
    #When evaluating the chance of precipitation, include the day you're
    #leaving/arriving (excluded above when looking at temperatures).
    for daily in forecasts[0:info['days']+1]:
        #Could argue that the first *day* shouldn't factor in the daytime
        #forecast. Simpler this way, though.
        prob_no_precip = (1-0.01*float(daily['day']['chance_precip'])*
                          1-0.01*float(daily['night']['chance_precip']))
        if float(daily['high']) >= WATER_FREEZING_POINT:
            prob_no_rain *= prob_no_precip
        if float(daily['low']) <= WATER_FREEZING_POINT:
            prob_no_snow *= prob_no_precip
    info.update(rain=1-prob_no_rain >= info['rain_threshold'])
    info.update(snow=1-prob_no_snow >= info['snow_threshold'])
    return info
コード例 #25
0
 def get_weather(self, target, sender, **kwargs):
     if kwargs["location"] in weather_locations_dict:
         current_weather = pywapi.get_weather_from_weather_com(weather_locations_dict[kwargs["location"]])
         self.message(target, "Current weather in {0} is {1} and it's {2}°C.".format(kwargs["location"], 
                                                             current_weather['current_conditions']['text'],
                                                             current_weather['current_conditions']['temperature']))
     else:
         self.message(target, "Location not found, run '.loc CITYname', then add the location ID with '.aloc CITYname is LocID' and rerun.")
コード例 #26
0
ファイル: app.py プロジェクト: monicating/Wheather
def weather():
	if request.method == "POST":
		zip = request.form["user_search"]
		weather_com_result = pywapi.get_weather_from_weather_com(zip)
		#return "Weather.com says: It is " + string.lower(weather_com_result['current_conditions']['text']) + " and " + weather_com_result['current_conditions']['temperature'] + "C now in " + zip
		return render_template("results.html", api_data=weather_com_result)
	else: # GET
		return render_template("search.html")
コード例 #27
0
def SetWeather(userId):
	global CoffeeDatabase

	weather_com_result = pywapi.get_weather_from_weather_com('UKXX0085')
	weather_type = string.lower(weather_com_result['current_conditions']['text'])
	current_temp = weather_com_result['current_conditions']['temperature']
	CoffeeDatabase[str(userId)]["Weather"] = weather_type
	CoffeeDatabase.sync()
コード例 #28
0
ファイル: weather.py プロジェクト: toxa1711/helper
 def getposit(city):
     x = 0
     pos = pywapi.get_location_ids(city)
     for i in pos:
         x += 1
         location_id = i
     result = pywapi.get_weather_from_weather_com(location_id)
     return(result['current_conditions']['temperature'])
コード例 #29
0
ファイル: clock.py プロジェクト: jitto/pi-clock
def updateWeather():
  global weather_com_result
  while True:
    try:
      weather_com_result = pywapi.get_weather_from_weather_com('75056', 'imperial')
    except:
      print("Unexpected error:", sys.exc_info()[0])
    time.sleep(600)
コード例 #30
0
def functionApiWeather():
    data = pywapi.get_weather_from_weather_com('MXJO0043', 'metric')
    message = data['location']['name']
    message = message + ", Temperature " + \
data['current_conditions']['temperature']
    message = message + ", Atmospheric Pressure " + \
data['current_conditions']['temperature']
    return message
コード例 #31
0
import  pywapi
import string

weather_com_result = pywapi.get_weather_from_weather_com('10001')
yahoo_result = pywapi.get_weather_from_yahoo('10001')
noaa_result = pywapi.get_weather_from_noaa('KJFK')

print "Weather.com says: It is " + string.lower(weather_com_result['current_conditions']['text']) + " and " + weather_com_result['current_conditions']['temperature'] + "C now in New York.\n\n"

print "Yahoo says: It is " + string.lower(yahoo_result['condition']['text']) + " and " + yahoo_result['condition']['temp'] + "C now in New York.\n\n"

print "NOAA says: It is " + string.lower(noaa_result['weather']) + " and " + noaa_result['temp_c'] + "C now in New York.\n"
コード例 #32
0
loc_id_list = pywapi.get_loc_id_from_weather_com(locale)

ans = 0

if locale != "13323" and loc_id_list['count'] > 1:
    for i in range(loc_id_list['count']):
        yn = raw_input("Did you mean, " + loc_id_list[i][1] + "? ")
        if re.match("[yY](es|)?", yn):
            ans = i
            break

loc_id = loc_id_list[ans][0]
loc_name = loc_id_list[ans][1]

weather_com_result = pywapi.get_weather_from_weather_com(loc_id)

if len(
        argv
) <= 2 or day == "TODAY" or day == "TONIGHT" or day == "NOW":  # just wants current weather
    print "It's currently " + weather_com_result['current_conditions']['text'] + " in " + loc_name + " with a temperature of " \
        + weather_com_result['current_conditions']['temperature'] + "C.",
    if (weather_com_result['current_conditions']['temperature'] !=
            weather_com_result['current_conditions']['feels_like']):
        print "But it feels a little more like " + weather_com_result[
            'current_conditions']['feels_like'] + "C. "

    want_forecast = raw_input("Do you want to see the forecast for today? ")
    if re.match("[yY](es|)?", want_forecast):
        print "Okay! "
        if weather_com_result['forecasts'][0]['day']['text'] != "":
コード例 #33
0
ファイル: dalamar.py プロジェクト: JPRbrs/telebot
def get_weather():
    # Returns a dict with two keys: out_feel and out_conditions
    return pywapi.get_weather_from_weather_com('BS3:4:UK')
コード例 #34
0
def weather_intent(chat):
    response = conversation.message(workspace_id=workspace_id,
                                    input={'text': chat})
    if (location != -1):  # location not available
        location_ID = pywapi.get_location_ids(location)
        loc_id = probable_location(location_ID)
        print(loc_id)
        if (loc_id != str(-1)):
            try:
                now = 'current_conditions'
                print(response)
                if (response['entities'] != []):
                    for i in response['entities']:
                        for j in i:
                            if (j == 'entity' and i[j] == 'location'):
                                location_ID = pywapi.get_location_ids(
                                    i['value'])
                                print('*')
                                loc_id = probable_location(location_ID)
                                if (loc_id == -1):
                                    return 0
                            if (j == 'entity' and i[j] == 'time'):
                                now = i['value']
                    Weather_details = pywapi.get_weather_from_weather_com(
                        loc_id)
                    #print(Weather_details)
                    if (now == 'current_conditions'):
                        print('It is ' + Weather_details[now]['text'] +
                              ' and ' + Weather_details[now]['wind']['speed'] +
                              'Km/hr now in ' +
                              Weather_details[now]['station'])
                    else:
                        overcast = 0
                        for i in Weather_details:
                            if (i == 'forecasts'):
                                for j in Weather_details[i]:
                                    #print(j)
                                    for k in j:
                                        #print (now)
                                        #print (str(k) + str(j[k]))
                                        if (k == 'day_of_week'
                                                and j[k].lower() == now):
                                            # print ('*')
                                            print('It is ' + j['day']['text'] +
                                                  ' on ' + now)
                                        if (j['day']['text'] == 'overcast' or
                                                j['day']['text'] == 'storm'):
                                            overcast += 1

                        if (overcast <= 1):
                            print(
                                'No need to worry, there are no overcast for this week'
                            )
                        else:
                            print(
                                'There are quite a few chances for overcast, please be patient and calm'
                            )

                    #if(response[])
                    #print (Weather_details)
                else:
                    Weather_details = pywapi.get_weather_from_weather_com(
                        loc_id)
                    print('It is ' + Weather_details[now]['text'] + ' and ' +
                          Weather_details[now]['wind']['speed'] +
                          'Km/hr now in ' + Weather_details[now]['station'])
            except:
                print(
                    'Server seems busy, cannot display weather information. till then have cup of tea'
                )
コード例 #35
0
import pywapi
import string
import sys

#this requires pywapi which can be installed from https://code.google.com/p/python-weather-api/
#If in the US 00000 should be your area code
#If in Britain, try using the BBC weather scripts found here: https://github.com/duncanj/voice_scripts

# pass a second parameter, 'imperial' if you are feeling like ferinheight instead of celsius
result = pywapi.get_weather_from_weather_com(str(sys.argv[1]))

print "It is " + string.lower(
    result['current_conditions']['text']
) + " and " + result['current_conditions']['temperature'] + " degrees."
print "Humidity " + result['current_conditions']['humidity'] + " percent."

today = result['forecasts'][0]
highToday = today['high']
if highToday > result['current_conditions']['temperature']:
    print "The expected high is " + highToday + "."

print "Overnight, " + today['night']['text'] + " with a low of " + today[
    'low'] + " "
if today['night']['chance_precip'] != "0":
    print " and a " + today['night'][
        'chance_precip'] + " percent chance of rain."

tomorrow = result['forecasts'][1]
print "Tomorrow, " + tomorrow['day']['text'] + " with a high of " + tomorrow[
    'high'] + " "
コード例 #36
0
ファイル: views.py プロジェクト: amarine-py/Craggapps
def craggarea(request, area_name_slug):

    #Create a context dictionary that we can pass to template rendering engine
    context_dict = {}

    try:
        # Can we find an area slug with the given area name?
        # If we can't, the .get() method raises a DoesNotExist exception.
        # So the .get() method returns one model instance or raises an exception.
        areas = CraggArea.objects.get(slug=area_name_slug)

    except CraggArea.DoesNotExist:
        # If area doesn't exist...
        # Let the template handle it with a "no area" message.
        pass

    # Try to get weather for Yahoo
    try:
        weather_yahoo = pywapi.get_weather_from_yahoo(areas.area_zip)
        temp_f_yahoo = (int(weather_yahoo['condition']['temp']) * 9 / 5) + 32

        # Create empty lists for Yahoo forecast data
        forecast_high_c_yahoo = []
        forecast_dayofweek_yahoo = []
        day_temp_yahoo = []

        # Populate forecast temps in fahrenheit (Yahoo)
        for x in range(1, 4):
            forecast_high_c_yahoo.append(
                (int(weather_yahoo['forecasts'][x]['high']) * 9 / 5) + 32)

        # Populate days of week
        for x in range(1, 4):
            forecast_dayofweek_yahoo.append(
                weather_yahoo['forecasts'][x]['day'])

        # Convert to full name of day of week
        for day in forecast_dayofweek_yahoo:
            if x == 'Thu':
                x = 'Thursday'
            elif x == 'Fri':
                x = 'Friday'
            elif x == 'Sat':
                x = 'Saturday'
            elif x == 'Sun':
                x = 'Sunday'
            elif x == 'Mon':
                x = 'Monday'
            elif x == 'Tue':
                x = 'Tuesday'
            else:
                x = 'Wednesday'

        # Zip the lists together for display
        day_temp_yahoo = zip(forecast_dayofweek_yahoo, forecast_high_c_yahoo)

        # Put Yahoo variables into context
        context_dict['yahoo_temp_f'] = temp_f_yahoo
        context_dict['day_temp_yahoo'] = day_temp_yahoo

    except KeyError:
        context_dict['yahoo_temp_f'] = False
        context_dict['day_temp_yahoo'] = False

    # Try to get data from Weather.com
    try:
        weather_com = pywapi.get_weather_from_weather_com(areas.area_zip)
        temp_f_com = (int(weather_com['current_conditions']['temperature']) *
                      9 / 5) + 32

        # Create empty lists for Weather.com forecast data
        forecast_high_c_com = []
        forecast_dayofweek_com = []
        day_temp_com = []

        # Populate forecast temps in celsius and convert fo fahrenheit (Weather.com)
        for x in range(1, 4):
            forecast_high_c_com.append(
                (int(weather_com['forecasts'][x]['high']) * 9 / 5) + 32)

        # Populate days of week
        for x in range(1, 4):
            forecast_dayofweek_com.append(
                weather_com['forecasts'][x]['day_of_week'])

        # Zip the lists together for display
        day_temp_com = zip(forecast_dayofweek_com, forecast_high_c_com)

        # Put Weather.com variables into context
        context_dict['com_temp_f'] = temp_f_com
        context_dict['day_temp_com'] = day_temp_com

    except KeyError:
        context_dict['com_temp_f'] = False
        context_dict['day_temp_com'] = False

    # Try to get data from Weather Underground
    try:
        weather_wunder = urllib2.urlopen(
            'http://api.wunderground.com/api/060cb0792aec8a1c/forecast/q/' +
            areas.area_zip + '.json')
        wunder_string = weather_wunder.read()
        wunder_parsed = json.loads(wunder_string)
        wunder_current = urllib2.urlopen(
            'http://api.wunderground.com/api/060cb0792aec8a1c/conditions/q/' +
            areas.area_zip + '.json')
        wunder_current_string = wunder_current.read()
        wunder_current_parsed = json.loads(wunder_current_string)
        temp_f_wunder = int(
            wunder_current_parsed['current_observation']['temp_f'])

        # Create empty lists for Weather Underground forecast data
        forecast_high_f_wunder = []
        forecast_dayofweek_wunder = []
        day_temp_wunder = []

        # Populate forecast temps in farhenheit (Weather Underground)
        for x in range(1, 4):
            forecast_high_f_wunder.append(
                wunder_parsed['forecast']['simpleforecast']['forecastday'][x]
                ['high']['fahrenheit'])

        # Populate days of week
        for x in range(1, 4):
            forecast_dayofweek_wunder.append(
                wunder_parsed['forecast']['simpleforecast']['forecastday'][x]
                ['date']['weekday'])

        # Zip the lists together for display
        day_temp_wunder = zip(forecast_dayofweek_wunder,
                              forecast_high_f_wunder)

        # Add variables for Weather Underground into context
        context_dict['wunder_temp_f'] = temp_f_wunder
        context_dict['day_temp_wunder'] = day_temp_wunder

    except KeyError:
        context_dict['wunder_temp_f'] = False
        context_dict['day_temp_wunder'] = False

    # Add other variables into the context
    context_dict['area_name'] = areas.area_name
    context_dict['area_city'] = areas.area_city
    context_dict['area_state'] = areas.area_state

    # Also add the area object from the database.
    # We will use this in teh template to verify that the user exists.
    context_dict['craggarea'] = areas

    # Is area a favorite of current user?
    if request.user.is_authenticated():
        current_user = UserProfile.objects.get(user__username=request.user)
        user_list = areas.cragg_users.all()

        if current_user in user_list:
            user_favorite = True
        else:
            user_favorite = False

        context_dict['user_favorite'] = user_favorite
        context_dict['current_user'] = current_user

    # Finally, render the response
    return render(request, 'climbcast/craggarea.html', context_dict)
コード例 #37
0
#!/usr/bin/env python3

import pywapi
import pprint

pp = pprint.PrettyPrinter(indent=4)

kalamata = pywapi.get_weather_from_weather_com('GRXX0036')

pp.pprint(kalamata)
コード例 #38
0
def get_current_temperature(location):
    result = get_weather_from_weather_com(location)
    return result
コード例 #39
0
#! /bin/env/python3
# vim: set fileencoding=UTF-8 :
import pywapi
import pprint as pp
import os
import re
import datetime

now = datetime.datetime.now()
wcr = pywapi.get_weather_from_weather_com('ITUM1307')
curcond_file = os.environ['HOME'] + '/.conky/weather/current_condition'
forecast_file = os.environ['HOME'] + '/.conky/weather/forecast'
icons_path = os.environ['HOME'] + '/.conky/weather/weather_icons/'
_icons_path = os.environ['HOME'] + '/.conky/weather/weather_icons/'

cur_cond = wcr['current_conditions']
forcast = wcr['forecasts']
wind = cur_cond['wind']

sunrise = re.sub(r'[A-Z]', '', forcast[0]['sunrise']).split(':')
sunr_time = now.replace(hour=int(sunrise[0]), minute=int(sunrise[1]))
sunset = re.sub(r'[A-Z]', '', forcast[0]['sunset']).split(':')
suns_time = now.replace(hour=(int(sunset[0]) + 12), minute=int(sunset[1]))

forecasts_ready = {}
days = []
high = []
lows = []
cond = []

# pp.pprint(wcr)
コード例 #40
0
        This function finds all the mp3 files in a folder and it's subfolders and returns a random music filename.
        """
        music_list = []
        for root, dirs, files in os.walk(music_path):
            for filename in files:
                if os.path.splitext(filename)[1] == ".mp3":
                    music_list.append(os.path.join(root, filename))
        music_play = random.choice(music_list)
        return music_play

    music_playing = mp3gen()
    tts("Now playing: " + music_playing)
    music_player(music_playing)

elif check_message(['how', 'weather']):
    weather_com_result = pywapi.get_weather_from_weather_com(city_code)
    weather_result = "Weather.com says: It is " + weather_com_result['current_conditions']['text'].lower() + " and " + weather_com_result['current_conditions']['temperature'] + "degree celcius now in " + city_name
    tts(weather_result)

elif check_message(['connect', 'proxy']):
    tts("Connecting to proxy server.")
    browser = webdriver.Firefox()
    browser.get('http://10.1.1.9:8090/httpclient.html')

    id_number = browser.find_element_by_name('username')
    password = browser.find_element_by_name('password')

    id_number.send_keys(proxy_username)
    password.send_keys(proxy_password)

    browser.find_element_by_name('btnSubmit').click()
コード例 #41
0
ファイル: WeatherReaderLEDs.py プロジェクト: EsEverde/RasPi
import string
import pywapi
import opc
import time
import colorsys
from random import randint
from datetime import datetime

TimeToUpdate = 15  #Update time in min
numLEDs = 30  #Init LEDs
MaxLED = 64
Strips = 5
Map = [[0 for x in range(numLEDs + 2)] for x in range(Strips + 2)]
client = opc.Client('localhost:7890')

weather_com_result = pywapi.get_weather_from_weather_com(
    'GMXX0053')  #Read weather in _____
#weather_com_result = pywapi.get_weather_from_weather_com('WAXX0004')
#weather_com_result = pywapi.get_weather_from_weather_com('RSXX0122')

hour = datetime.now().hour  #What time is it? (only hour)
SunsetHour = weather_com_result['forecasts'][0]['sunset']
SunriseHour = weather_com_result['forecasts'][0]['sunrise']
pixels = [(0, 0, 0)] * (MaxLED * Strips)
if len(SunsetHour) > 7:  #Sunset hour in am/pm
    SunsetHour = str(SunsetHour[0] + SunsetHour[1])
    SunsetHour = int(SunsetHour)
else:
    SunsetHour = int(SunsetHour[0])

SunriseHour = int(SunriseHour[0])
コード例 #42
0
ファイル: z.py プロジェクト: onlinux/zibase-thermostat
    def run(self):
        try:
            start = time.time()
            weather_com_result = pywapi.get_weather_from_weather_com(
                self.code, units='metric')
            elapsed = (time.time() - start) * 1000

            pp.pprint(weather_com_result)

            # extract current data for today
            # today = weather_com_result['current_conditions']['last_updated']

            windSpeed = weather_com_result['current_conditions']['wind'][
                'speed']
            if windSpeed.isdigit():
                currWind = "{:.0f}km/h ".format(int(windSpeed)) + \
                    weather_com_result['current_conditions']['wind']['text']
            else:
                currWind = windSpeed
            logging.debug(' retrieve today wind')
            # currTemp = weather_com_result['current_conditions']['temperature'] + u'\N{DEGREE SIGN}' + "C"
            currTempAndHum = weather_com_result['current_conditions']['temperature'] + \
                u'\N{DEGREE SIGN}' + "C" + " / " + \
                weather_com_result['current_conditions']['humidity'] + "%"
            currPress = weather_com_result['current_conditions']['barometer'][
                'reading'][:-3] + " hPa"
            uv = "UV {}".format(
                weather_com_result['current_conditions']['uv']['text'])
            # humid = "Hum {}%".format(weather_com_result['current_conditions']['humidity'])
            locationName = weather_com_result['location']['name']
            city = locationName.split(',')[0]
            logging.debug(
                ' retrieve data from weather.com for %s (%s) [%d ms]' %
                (self.code, locationName, elapsed))

            # extract forecast data
            forecastDays = {}
            forecaseHighs = {}
            forecaseLows = {}
            forecastPrecips = {}
            forecastWinds = {}

            start = 0
            try:
                float(
                    weather_com_result['forecasts'][0]['day']['wind']['speed'])
            except ValueError:
                start = 1

            for i in range(start, 5):

                if not (weather_com_result['forecasts'][i]):
                    break
                forecastDays[i] = weather_com_result['forecasts'][i][
                    'day_of_week'][0:3]
                forecaseHighs[i] = weather_com_result['forecasts'][i]['high'] + \
                    u'\N{DEGREE SIGN}' + "C"
                forecaseLows[i] = weather_com_result['forecasts'][i]['low'] + \
                    u'\N{DEGREE SIGN}' + "C"
                forecastPrecips[i] = weather_com_result['forecasts'][i]['day'][
                    'chance_precip'] + "%"
                forecastWinds[i] = "{:.0f}".format(int(weather_com_result['forecasts'][i]['day']['wind']['speed'])) + \
                    weather_com_result['forecasts'][i]['day']['wind']['text']

            # blank the screen
            lcd.fill(self.location['color'])

            # Render the weather logo at 0,0
            icon = installPath + \
                (weather_com_result['current_conditions']['icon']) + ".png"
            logo = pygame.image.load(icon).convert_alpha()
            lcd.blit(logo, (140, 0))

            # set the anchor for the current weather data text
            textAnchorX = 0
            textAnchorY = 5
            textYoffset = 20

            # add current weather data text artifacts to the screen
            text_surface = font.render(city, True, WHITE)
            lcd.blit(text_surface, (textAnchorX, textAnchorY))
            textAnchorY += textYoffset
            text_surface = font.render(currTempAndHum, True, WHITE)
            lcd.blit(text_surface, (textAnchorX, textAnchorY))
            textAnchorY += textYoffset
            text_surface = font.render(currWind, True, WHITE)
            lcd.blit(text_surface, (textAnchorX, textAnchorY))
            textAnchorY += textYoffset
            text_surface = font.render(currPress, True, WHITE)
            lcd.blit(text_surface, (textAnchorX, textAnchorY))
            textAnchorY += textYoffset
            text_surface = font.render(uv, True, WHITE)
            lcd.blit(text_surface, (textAnchorX, textAnchorY))
            textAnchorY += textYoffset
            #text_surface = font.render(humid, True, WHITE)
            #lcd.blit(text_surface, (textAnchorX, textAnchorY))

            if (display == 1):
                thermostat.read()
                textAnchorY += textYoffset
                text_surface = fontTemperature.render(thermostat.indoorTemp,
                                                      True, WHITE)
                lcd.blit(text_surface, (textAnchorX, textAnchorY))

            # set X axis text anchor for the forecast text
            textAnchorX = 0
            textXoffset = 65
            if (display == 0):
                # add each days forecast text
                for i in forecastDays:
                    textAnchorY = 130
                    text_surface = fontSm.render(forecastDays[int(i)], True,
                                                 WHITE)
                    lcd.blit(text_surface, (textAnchorX, textAnchorY))
                    textAnchorY += textYoffset
                    text_surface = fontSm.render(forecaseHighs[int(i)], True,
                                                 WHITE)
                    lcd.blit(text_surface, (textAnchorX, textAnchorY))
                    textAnchorY += textYoffset
                    text_surface = fontSm.render(forecaseLows[int(i)], True,
                                                 WHITE)
                    lcd.blit(text_surface, (textAnchorX, textAnchorY))
                    textAnchorY += textYoffset
                    text_surface = fontSm.render(forecastPrecips[int(i)], True,
                                                 WHITE)
                    lcd.blit(text_surface, (textAnchorX, textAnchorY))
                    textAnchorY += textYoffset
                    text_surface = fontSm.render(forecastWinds[int(i)], True,
                                                 WHITE)
                    lcd.blit(text_surface, (textAnchorX, textAnchorY))
                    textAnchorX += textXoffset

            # refresh the screen with all the changes
            pygame.display.update()
            #logging.debug(" End of thread: %s -> %s for %s" % (threading.current_thread(), today, locationName))

        except ValueError:
            logging.warning(' PYWAPI %s CONNECTION ERROR ' %
                            (threading.current_thread()))
            scope.clear()
            title = 'ERROR'
            text = fontTitle.render(title, True, WHITE)
            textrect = text.get_rect()
            textrect.center = (160, 20)
            lcd.blit(text, textrect)
            pygame.display.update()
コード例 #43
0
import pywapi

weather = pywapi.get_weather_from_weather_com('CAXX0151')

rain = weather["current_conditions"]["humidity"]
moon = weather["current_conditions"]["moon_phase"]["text"]
stablepressure = weather["current_conditions"]["barometer"]["direction"]
pressure = weather["current_conditions"]["barometer"]["reading"]
print "Weather pressure and moons script. By: traBpUkciP"
print "================================================="
print "Moon phase: {}".format(moon)
print "Pressure {} at {}pu.".format(stablepressure, pressure)

# CAXX0151
コード例 #44
0
ファイル: test.py プロジェクト: graemeb52096/Edison
# Set city to Toronto ID#
city = 'CAXX0504'

# Print it.
x = 100000

# when is it too cold?
too_cold = -10

now = datetime.datetime.now()
#for i in range(0, x):
while int(datetime.datetime.now().year) < 2020:

    now = datetime.datetime.now()

    weather = pywapi.get_weather_from_weather_com(city, units='metric')

    try:
        current_temp = weather['current_conditions']['temperature']
    except:
        print "exception"
    year = now.year
    month = now.month
    day = now.day
    hour = now.hour
    minute = now.minute

    if minute < 10:
        myString = '%s:0%s  %s/%s/%s' % (hour, minute, month, day,
                                         str(year)[2:])
    else:
コード例 #45
0
ファイル: panel.py プロジェクト: shure/pi
fastlane1 = ("34.84571", "31.99926")
fastlane2 = ("34.84184", "32.00369")


def get_waze(a, b):
    request = "https://www.waze.com/il-RoutingManager/routingRequest?from=x%3A" + a[
        0] + "+y%3A" + a[1] + "+bd%3Atrue&to=x%3A" + b[0] + "+y%3A" + b[
            1] + "+bd%3Atrue&returnXML=true&returnGeometries=false&returnInstructions=false&timeout=60000&nPaths=1&AVOID_TRAILS=false&AVOID_LONG_TRAILS=false"
    url = urllib.urlopen(request)
    data = url.read()
    tree = lxml.etree.fromstring(data)
    time = tree.xpath("/route/summary")[0].get("time")
    return int(time) / 60


weather = pywapi.get_weather_from_weather_com('ISXX0011')
weather_text = weather['current_conditions']['text']
weather_temp = weather['current_conditions']['temperature']

line1 = weather_temp + "c " + weather_text.replace(" ", "")

mentor_time = get_waze(home, mentor)
mentor_time_fastlane = get_waze(home, fastlane1) + get_waze(fastlane2, mentor)
amdocs_time = get_waze(home, amdocs)

if mentor_time_fastlane < mentor_time:
    fastlane_price = get_fast_lane_price()
    line2 = "M:" + str(mentor_time) + "/" + str(
        mentor_time_fastlane) + "+" + fastlane_price
else:
    line2 = "M:" + str(mentor_time)