首页 > 解决方案 > 使用 sys.argv 进行天气检查

问题描述

我正在尝试使用sys.argv并且只是想要一些帮助来制作天气搜索工具。我有当前的代码

问题是当我使用命令行搜索时,我需要输入国家。有没有办法只搜索城市?:

#! /usr/bin/env python3
import webbrowser
import sys
import pyperclip
import re

if len(sys.argv) > 1:
    #Get address from command line.
    address = ' '.join(sys.argv[1:])
else:
    address = pyperclip.paste()


webbrowser.open('https://www.timeanddate.com/weather/' + address)

命令行:

./weather.py spain/madrid
./weather.py uk/london

标签: pythonpython-3.xsys

解决方案


如前所述,可能有许多软件包可以解决问题,而且很可能它们都不适用于某些城市名​​称。但是,geonamescache 非常易于使用,并且可以使用唯一名称。这是一个示例(将为“多伦多”返回“加拿大”作为输入)

pip install geonamescache
import geonamescache as gnc
gc = gnc.GeonamesCache()
query = 'Toronto'
citykey = list(gc.get_cities_by_name(query)[0])[0]
ccode = gc.get_cities_by_name(query)[0][citykey]['countrycode']
countries = gc.get_countries()
country_name = countries[ccode]['name']
print(country_name)

推荐阅读