Pyowm API中的异常问题

时间:2019-03-05 14:21:51

标签: python api

我正在使用Python上非常原始的脚本工作,该脚本在控制台中提供了当前的信息。这样就可以了,但是如果我输入了错误的城市名称(例如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

我想捕获此异常并打印如下内容:

try:
owm.weather_at_place(place)
except (pyowm.exceptions.api_response_error.NotFoundError):
print("Wrong information, try again and find out mistakes please")
time.sleep(10)

我尝试了很多次,但总是失败了。您知道如何正确使用api的exceptons吗?

感谢您的关注! 下面是完整的代码。

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)

进一步仅在屏幕上显示功能的内容

2 个答案:

答案 0 :(得分:0)

“总是失败”是什么意思?您遇到什么样的错误/不当行为?

顺便说一句,您的异常捕获代码是错误的(因为它实际上实例化了一个异常!)。试试这个:

import pyowm
from pyowm.exceptions import api_response_error
try:
    owm.weather_at_place(place)
except api_response_error.NotFoundError:
    print('Wrong information, try again and find out mistakes please')
    time.sleep(10)

答案 1 :(得分:0)

我刚刚在try-catch周期中宣布了变量“ main”,并且代码现在正在工作。感谢您的关注并为大家提供帮助!