#!/usr/bin/env python # -*- coding: utf-8 -*- """ 中国天气网天气查询命令行工具 数据来源:www.weather.com.cn """ import argparse import json import sys from weather import query_weather, query_current_weather, search_city, find_city_code def cmd_query(args): """查询天气预报""" city_code = find_city_code(args.city) if not city_code: print(f"错误:未找到城市 \"{args.city}\",请使用 search 命令搜索城市") return 1 if args.current: # 查询当前天气 result = query_current_weather(args.city) if result: print(result) return 0 else: print(f"错误:无法获取 {args.city} 的当前天气") return 1 else: # 查询天气预报 days = args.days or 7 result = query_weather(args.city, days) if result: print(result) return 0 else: print(f"错误:无法获取 {args.city} 的天气预报") return 1 def cmd_search(args): """搜索城市""" cities = search_city(args.keyword) if not cities: print(f"未找到包含 \"{args.keyword}\" 的城市") return 1 print(f"找到 {len(cities)} 个匹配的城市:") print("-" * 40) for city in cities[:args.limit]: print(f" {city['name']}: {city['code']}") return 0 def cmd_json(args): """输出JSON格式的天气数据""" city_code = find_city_code(args.city) if not city_code: print(f"错误:未找到城市 \"{args.city}\"") return 1 from weather import WeatherQuery query = WeatherQuery() weather_info = query.query(args.city, args.days or 7) if weather_info: data = { "city": weather_info[0].city, "update_time": weather_info[0].update_time, "forecast": [ { "date": info.date, "weather": info.weather, "temperature": info.temperature, "wind": info.wind, } for info in weather_info ] } print(json.dumps(data, ensure_ascii=False, indent=2)) return 0 else: print(f"错误:无法获取 {args.city} 的天气数据") return 1 def main(): parser = argparse.ArgumentParser( description="中国天气网天气查询工具", formatter_class=argparse.RawDescriptionHelpFormatter, epilog=""" 示例: %(prog)s query 杭州 # 查询杭州7天天气预报 %(prog)s query 北京 --days 3 # 查询北京3天天气预报 %(prog)s query 深圳 --current # 查询深圳当前天气 %(prog)s search 州 # 搜索带"州"字的城市 %(prog)s json 杭州 --days 3 # 输出JSON格式的天气数据 """ ) subparsers = parser.add_subparsers(dest="command", help="子命令") # query 命令 query_parser = subparsers.add_parser("query", help="查询天气预报") query_parser.add_argument("city", help="城市名称,如:杭州、北京、上海") query_parser.add_argument("--days", type=int, choices=[1, 3, 7, 15, 40], help="查询天数 (1, 3, 7, 15, 40),默认7天") query_parser.add_argument("--current", "-c", action="store_true", help="查询当前天气而非预报") query_parser.set_defaults(func=cmd_query) # search 命令 search_parser = subparsers.add_parser("search", help="搜索城市") search_parser.add_argument("keyword", help="搜索关键词") search_parser.add_argument("--limit", type=int, default=20, help="返回结果数量限制,默认20") search_parser.set_defaults(func=cmd_search) # json 命令 json_parser = subparsers.add_parser("json", help="输出JSON格式的天气数据") json_parser.add_argument("city", help="城市名称") json_parser.add_argument("--days", type=int, choices=[1, 3, 7, 15, 40], help="查询天数,默认7天") json_parser.set_defaults(func=cmd_json) args = parser.parse_args() if not args.command: parser.print_help() return 1 return args.func(args) if __name__ == "__main__": sys.exit(main())