python - 在pyowm中找不到城市时如何创建输出?
问题描述
当找不到国家(例如,用户写错了城市)时,如何在终端上创建自定义输出?
默认输出是错误代码:
raise exceptions.NotFoundError('Unable to find the resource') pyowm.commons.exceptions.NotFoundError: Unable to find the resource
我希望输出类似于:
抱歉,我找不到您搜索的城市。请再试一次...
到目前为止,这是我的代码:
import pyowm
owm = pyowm.OWM('api code')
weather = True
while weather == True:
weather_input = input('Enter the name of the city you want me to search - ')
mgr = owm.weather_manager()
weather_city1 = mgr.weather_at_place(weather_input)
w = weather_city1.weather
print('Weather in ' + weather_input + ' - ' + str(w.temperature('celsius')))
解决方案
尝试异常处理!继承自 C 派生语言的一个不错的 Python 特性:
from pyowm import OWM
from pyowm.commons.exceptions import NotFoundError
owm = OWM('api code')
mgr = owm.weather_manager()
while True:
weather_input = input('Enter the name of the city you want me to search - ')
try:
weather_city1 = mgr.weather_at_place(weather_input)
w = weather_city1.weather
print('Weather in ' + weather_input + ' - ' + str(w.temperature('celsius')))
except NotFoundError:
print('Sorry, I was unable to find the city you searched for. Please try again...')
推荐阅读
- aws-cli - AWS CLI S3 同步存储桶并保留权限
- react-native - TouchableHighlight 未被禁用
- azure - Azure CLI - 运行脚本文件
- javascript - 如何在nodeJS和knexJS中重复数组长度的id
- python - discord.py - 更新特定消息
- aspnetboilerplate - 扩展租户
- ios - 从点云创建网格
- java - 如何从 Windows 命令行运行 Geb TestCases?
- mysql - 在 PhpMyAdmin 上使用 SQL 创建新用户
- sas - 如何从 SAS Base javaobj 语句创建对象的 java 数组?