为什么python会在失去互联网后退出
我目前正在开发的程序每5分钟从weather.com获取一次信息。我目前有一个与互联网丢失的问题,如果该程序试图检查更新它将退出该程序。检查internet错误并让其稍后重试的最佳方法是什么。这段代码现在是一个非常粗糙的模型,所以对于可读性很抱歉为什么python会在失去互联网后退出,python,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()
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()
我不熟悉
pywapi
,但我猜pywapi.get\u weather\u from\u weather\u 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
您好,欢迎来到stackoverflow。为了吸引更好的答案,你应该减少你的样本程序,直到你得到一个显示问题的最小样本。在空白处签出此页是一个坏主意,如果您预计会出现套接字错误,您应该捕获“捕获所有”反模式的下一个,您可能希望在某个地方打印错误消息。@Padraiccningham同意,但由于我不熟悉
pywapi
我不希望OP使用它,我将编辑我的答案……如果您真的想继续发生任何事情(服务可以理解),最起码的是记录您不希望在程序失败时可以查看的异常。@spectras完全可以接受,但我不是来为OPs程序编写全部逻辑的:)