为什么python会因为失去实习生而退出

2024-09-22 16:40:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正在做的程序每5分钟从weather.com获取一次信息。我目前有一个与互联网丢失的问题,如果程序试图检查更新它将退出程序。检查internet错误并稍后再试的最佳方法是什么。这段代码是一个非常粗糙的模型,所以很抱歉可读性

RED_PIN = 17
GREEN_PIN = 22
BLUE_PIN = 24

import pigpio
import time
import pywapi
import string
import math

pi = pigpio.pi()
weather = 'none'
flashelse = 5

while weather != 'Exit':
    print time.ctime()
    #print time.strftime('%l:%M%p %z on %b %d, %Y')
    weather_com_result = pywapi.get_weather_from_weather_com('USTN0268')#USTN0268
    tempc = int(weather_com_result['current_conditions']['temperature'])
    tempf = (tempc*9/5) + 32
    weather = string.lower(weather_com_result['current_conditions']['text'])
    print "Weather.com says: It is " + string.lower(weather_com_result['current_conditions']['text']) + " and", tempf, "F now in Knoxville, TN."

    if weather == 'sunny':
        pi.set_PWM_dutycycle(RED_PIN, 224) 
        pi.set_PWM_dutycycle(GREEN_PIN, 255) 
        pi.set_PWM_dutycycle(BLUE_PIN, 0) 

    elif weather == 'Partly Cloudy':
        pi.set_PWM_dutycycle(RED_PIN, 0) 
        pi.set_PWM_dutycycle(GREEN_PIN, 255) 
        pi.set_PWM_dutycycle(BLUE_PIN, 25) 

    elif weather == 'cloudy':
        pi.set_PWM_dutycycle(RED_PIN, 82) 
        pi.set_PWM_dutycycle(GREEN_PIN, 0) 
        pi.set_PWM_dutycycle(BLUE_PIN, 255) 

    elif weather == 'rain shower':
        pi.set_PWM_dutycycle(RED_PIN, 0) 
        pi.set_PWM_dutycycle(GREEN_PIN, 0) 
        pi.set_PWM_dutycycle(BLUE_PIN, 255) 

    elif weather == 'Thunderstorm':
        pi.set_PWM_dutycycle(RED_PIN, 255) 
        pi.set_PWM_dutycycle(GREEN_PIN, 0) 
        pi.set_PWM_dutycycle(BLUE_PIN, 0) 

    elif weather == 'Snow':
        pi.set_PWM_dutycycle(RED_PIN, 0) 
        pi.set_PWM_dutycycle(GREEN_PIN, 174) 
        pi.set_PWM_dutycycle(BLUE_PIN, 255) 

    elif weather == 'Exit':
        break

    else:
        pi.set_PWM_dutycycle(RED_PIN, 50) 
        pi.set_PWM_dutycycle(GREEN_PIN, 0) 
        pi.set_PWM_dutycycle(BLUE_PIN, 0) 
        time.sleep(2)
        pi.set_PWM_dutycycle(RED_PIN, 0) 
        pi.set_PWM_dutycycle(GREEN_PIN, 0) 
        pi.set_PWM_dutycycle(BLUE_PIN, 0) 
    #text_file.close()
    time.sleep(300)

print("Exiting...")

time.sleep(.1)
pi.set_PWM_dutycycle(RED_PIN, 50) 
pi.set_PWM_dutycycle(GREEN_PIN, 0) 
pi.set_PWM_dutycycle(BLUE_PIN, 0) 

time.sleep(1)
pi.set_PWM_dutycycle(RED_PIN, 0)
pi.set_PWM_dutycycle(GREEN_PIN, 0)
pi.set_PWM_dutycycle(BLUE_PIN, 0)

pi.stop()

Tags: importcomtimepinpigreenbluered
1条回答
网友
1楼 · 发布于 2024-09-22 16:40:33

我对pywapi不太熟悉,但我猜pywapi.get_weather_from_weather_com()会在没有连接的情况下产生某种SocketException,所以应该用try/except来包装它

try:
    weather_com_result = pywapi.get_weather_from_weather_com('USTN0268')
except SocketException: # or what ever exception type ptwapi raises
    # probably log the exception for later review
    continue

相关问题 更多 >