我正在编写Python上非常原始的脚本,它在控制台中提供当前的wheather信息。所以一切正常,但是如果我输入了错误的城市名称(例如,Nev Uork),控制台中会出现一个异常。在
API-pyowm
Traceback (most recent call last):
File "C:\Users\Dismay\Documents\Python\WeatherHelper2.py", line 28, in <module>
main = owm.weather_at_place(place)
File "C:\Users\Dismay\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pyowm\webapi25\owm25.py", line 210, in weather_at_place
_, json_data = self._wapi.cacheable_get_json(uri, params=params)
File "C:\Users\Dismay\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pyowm\commons\http_client.py", line 44, in cacheable_get_json
status_code, data = self.get_json(uri, params=params, headers=headers)
File "C:\Users\Dismay\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pyowm\commons\http_client.py", line 31, in get_json
HttpClient.check_status_code(resp.status_code, resp.text)
File "C:\Users\Dismay\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pyowm\commons\http_client.py", line 112, in check_status_code
raise api_response_error.NotFoundError('Unable to find the resource')
pyowm.exceptions.api_response_error.NotFoundError: The searched item was not found.
Reason: Unable to find the resource
我想捕捉这个异常并打印类似的内容:
^{pr2}$我试了很多次,但总是失败。你知道如何正确处理api的异常吗?
谢谢大家的关注! 下面是完整的代码。在
import pyowm
import time
from colorama import *
from pyowm.exceptions import *
init(autoreset = True)
print(Fore.BLACK + Back.WHITE + 'Let`s go')
owm = pyowm.OWM('bbc3649126d17d7bb4111c44c6a562d5')
place = input("Place you find: ")
main = owm.weather_at_place(place)
weather = main.get_weather()
maxtemp = weather.get_temperature("celsius")["temp_max"]
midtemp = weather.get_temperature("celsius")["temp"]
mintemp = weather.get_temperature("celsius")["temp_min"]
speedwind = weather.get_wind()["speed"]
status = weather.get_detailed_status()
azimuth = weather.get_wind()["deg"]
humidity = weather.get_humidity()
try:
owm.weather_at_place(place)
except (urllib3.exceptions.ReadTimeoutError,
api_response_error.NotFoundError('Unable to find the resource')):
print("""Wrong information, try again
and find out mistakes please""")
time.sleep(10)
此外,只在屏幕上显示功能的内容
我刚刚宣布了try-catch循环中的变量“main”,代码现在正在工作。谢谢大家的关注和帮助!在
你说“总是失败”是什么意思?你犯了什么样的错误/不当行为?在
顺便说一句,你的异常捕捉代码是错误的(因为它实际上实例化了一个异常!)。试试这个:
相关问题 更多 >
编程相关推荐