python - 使用 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
解决方案
如前所述,可能有许多软件包可以解决问题,而且很可能它们都不适用于某些城市名称。但是,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)
推荐阅读
- c# - 在构造函数 C# 中使用静态只读字段
- sftp - 从 SFTP 服务器下载特定文件名模式的最新文件
- javascript - 递归展平对象数组中的嵌套对象
- sonos - 如何防止对用户的主播放列表容器中的项目进行重新排序?
- excel - 如何检查我的工作簿(excel)是否从word文档中打开?
- r - 我的输出在 R 中使用 b 样条函数关闭
- angular - 在左侧的 https://angular.io/docs 上使用哪个元素/小部件进行导航?
- .net - 获取 Razor 页面中具有特定角色的用户
- arrays - 数组必须用大括号括起来的初始化器初始化
- html - 我在 youtube iframe 之后有一个标题,而标题在 iframe 的右侧,为什么?