CLI Weather is a versatile command-line application built with Python that provides current weather information, detailed forecasts, and personalized activity recommendations. It leverages the OpenWeatherMap API to fetch up-to-date weather data and offers multiple user interfaces to suit different use cases.
This project follows modern Python architecture with clean separation of concerns, multiple UI implementations, and is optimized for use with the uv package manager.
- Current Weather: Get real-time weather conditions for any chosen location.
- Hourly Forecasts: View weather predictions for the next 24 hours.
- 5-Day Forecasts: Plan ahead with a 5-day weather outlook.
- Specific Day Forecast: Get detailed weather for a particular day within the 5-day range.
- Activity-Based Recommendations: Discover the best days for your favorite activities based on customizable weather criteria (e.g., temperature, rain, wind, time of day).
- Typhoon Tracking & Alerts: View active weather alerts, including typhoon warnings, for your chosen location and save them to a file.
- Location Management:
- Save and manage a list of your favorite locations.
- Add new locations by name or coordinates.
- Automatically fetch and save your current location.
- Search for locations globally.
- Activity Management:
- Define and customize weather criteria for different activities (e.g., walking, fishing).
- View, add, edit, and delete your saved activities.
- Data Management:
- Cache weather data locally to improve performance and reduce API calls.
- Option to clear cached data.
- Option to clear application logs.
- Save Forecasts: Save weather forecasts to a text file for offline viewing.
- Python 3.10+
- An OpenWeatherMap API Key
- Dependencies are managed in pyproject.toml and include:
- geopy - Location geocoding and geospatial calculations
- python-dotenv - Environment variable management
- requests - HTTP client for weather API calls
- tzdata - Timezone data
- rich - Enhanced terminal output with modern styling
- typer - Command-line interface framework
This project is managed with uv for modern Python dependency management.
-
Clone the repository:
git clone https://github.com/Onehand-Coding/cli-weather.git cd cli-weather -
Install with uv (recommended):
uv sync
This command automatically creates a virtual environment, installs all dependencies, and sets up the project in editable mode.
If you prefer to use standard Python tools:
-
Create and activate a virtual environment:
python -m venv .venv # On Linux/macOS source .venv/bin/activate # On Windows .\.venv\Scripts\activate
-
Install the project in editable mode:
pip install -e .
This application requires an API key from OpenWeatherMap to fetch weather data.
- Sign up for a free account on OpenWeatherMap and obtain your API key.
- Create a
.envfile in the root directory of the project (cli-weather/.env). - Add your API key to the
.envfile like this:OWM_API_KEY=your_actual_api_key_here
You can also set the following optional environment variables in your .env file:
TZ: Set your local timezone (e.g.,Asia/Manila). Defaults toUTCif not set.LOG_LEVEL: Set the logging level (e.g.,DEBUG,INFO,WARNING,ERROR). Defaults toERROR.- You can also define sensitive locations directly in the
.envfile using a custom name and comma-separated coordinates, for example:MY_SECRET_SPOT=12.345,67.890
- Configuration File (
data/config.json): Stores your saved locations and activity criteria. This file is automatically created and managed by the application. - Cache (
data/cache/): Weather data is cached here to speed up requests and reduce API usage. Cache expires after 30 minutes. - Logs (
logs/weather_app.log): Application logs are stored here.
CLI Weather offers multiple user interfaces to suit different workflows and preferences:
Launches a modern, interactive menu system with enhanced visuals, tables, progress bars, and styled output:
uv run cli-weather # Default mode
# or
uv run python -m cli_weather
# or
cli-weather # If installed with pipFor automation, scripting, and direct command execution:
# Weather commands
uv run cli-weather weather current --current
uv run cli-weather weather daily --location "New York"
uv run cli-weather weather hourly --lat 40.7128 --lon -74.0060
uv run cli-weather weather day 3 --location "Denver" --hourly
uv run cli-weather weather activity hiking --current
uv run cli-weather weather alerts --current
# Location management
uv run cli-weather location list
uv run cli-weather location add "Home" --lat 40.7128 --lon -74.0060
uv run cli-weather location current --name "My Location"
uv run cli-weather location search "Tokyo"
# Activity management
uv run cli-weather activity list
uv run cli-weather activity add "jogging" --temp-min 15 --temp-max 25 --rain 0
uv run cli-weather activity show hiking
# Configuration
uv run cli-weather config clear-cache
uv run cli-weather config clear-logsFor backwards compatibility with the original interface:
uv run cli-weather --legacyCommon Location Options:
--location NAMEor-l NAME: Use a saved location--currentor-c: Auto-detect current location via IP--lat LAT --lon LON: Use specific coordinates
Output Options:
--json: Output data in JSON format (CLI mode only)--output FILEor-o FILE: Save results to file--hours N: Number of hours for hourly forecasts (1-120)--hourly: Show hourly details for specific day forecasts
Activity Options:
--temp-min N: Minimum temperature in Celsius--temp-max N: Maximum temperature in Celsius--rain N: Maximum rainfall in mm--wind-min N: Minimum wind speed in km/h--wind-max N: Maximum wind speed in km/h--start HH:MM: Activity start time--end HH:MM: Activity end time
Examples:
# Get current weather for saved location
uv run cli-weather weather current -l "New York"
# Get 5-day forecast for current location
uv run cli-weather weather daily --current
# Get specific day with hourly details
uv run cli-weather weather day 2 --current --hourly
# Find best days for activity with JSON output
uv run cli-weather weather activity hiking --current --json
# Get hourly forecast and save to file
uv run cli-weather weather hourly --lat 35.6762 --lon 139.6503 -o forecast.txt
# Add location by address geocoding
uv run cli-weather location add "Office" --address "Times Square, New York"# General help
uv run cli-weather --help
# Command-specific help
uv run cli-weather weather --help
uv run cli-weather location --help
uv run cli-weather activity --helpCLI Weather follows a clean, modular architecture with clear separation of concerns:
src/cli_weather/
βββ core/ # Pure business logic (no UI concerns)
β βββ app.py # Main app orchestrator
β βββ weather_service.py # Weather API and data processing
β βββ location_service.py # Location management and geocoding
β βββ activity_service.py # Activity criteria management
β βββ config_service.py # Configuration management
β βββ cache_service.py # Data caching
β βββ models.py # Data models (Location, Activity, WeatherData)
β βββ exceptions.py # Custom exceptions
βββ ui/ # UI layer (multiple implementations)
β βββ rich_ui.py # Rich-based interactive UI
β βββ typer_cli.py # Typer-based command-line UI
βββ legacy/ # Original mixed-concern modules
βββ __main__.py # Main entry point with UI selection
- Separation of Concerns: Business logic is completely isolated from UI concerns
- Multiple UI Support: Same core functionality accessible through different interfaces
- Dependency Injection: Services are injected rather than directly instantiated
- Clean Data Models: Well-defined data structures for all entities
- Comprehensive Testing: Full test coverage of business logic with proper mocking
- Error Handling: Consistent error handling across all layers
UI Layer β App Orchestrator β Services β External APIs/Storage
β β β β
Rich UI WeatherApp Weather OpenWeatherMap
Typer CLI Location Nominatim
Legacy UI Activity Config Files
Cache File System
- WeatherService: Handles all weather-related operations (API calls, data parsing, caching)
- LocationService: Manages locations (geocoding, IP-based detection, persistence)
- ActivityService: Manages activity criteria and weather filtering
- ConfigService: Handles configuration persistence and retrieval
- CacheService: Manages data caching with expiration
CLI Weather includes a comprehensive test suite covering all core business logic with proper mocking and isolation. The tests are designed to validate the separation of concerns and ensure reliability across different components.
The project uses pytest for testing with development dependencies managed through the dev extra group:
# Install with development dependencies
uv sync --extra dev
# Or add dev dependencies to existing installation
uv sync --extra dev# Run all tests with pytest (recommended)
uv run pytest
# Run tests with verbose output
uv run pytest -v
# Run specific test files
uv run pytest tests/test_services.py # Core business logic services
uv run pytest tests/test_ui.py # UI components and CLI
uv run pytest tests/test_core.py # Legacy functionality
# Run tests for specific functionality
uv run pytest tests/test_services.py::TestWeatherService
uv run pytest tests/test_services.py::TestLocationService::test_geocode_address
# Alternative: Run with unittest discovery
uv run python -m unittest discover testsThe test suite includes 74 comprehensive tests covering:
- WeatherService: API integration, data parsing, caching, activity filtering
- LocationService: Geocoding, coordinate validation, location management
- ActivityService: Activity criteria management, CRUD operations
- WeatherApp: Application orchestration and service integration
- Data Models: Location, Activity, and WeatherData model validation
- CacheService: Data caching with expiration and cleanup
- Rich UI: Interactive menu system, weather displays, formatting
- Typer CLI: Command-line parsing, argument handling, output formatting
- Main Entry: UI mode detection, help system, command routing
- Weather Operations: API calls, data processing, forecast parsing
- Location Management: Address geocoding, coordinate handling, persistence
- Activity Management: Criteria definition, weather filtering
- Typhoon Tracking: Alert fetching, data processing, user interaction
- Comprehensive Mocking: All external dependencies (APIs, file system, network) are mocked
- Isolation: Each test runs independently with proper setup and teardown
- Edge Cases: Tests cover error conditions, invalid inputs, and boundary cases
- Data Validation: Ensures data models work correctly with various inputs
- UI Testing: Validates both Rich interactive UI and Typer CLI functionality
- Float Precision: Uses appropriate precision handling for coordinate comparisons
Tests are designed to run without:
- External API keys (all API calls are mocked)
- Network connectivity (no real HTTP requests)
- File system modifications (temporary directories used)
- User input (interactive prompts are mocked)
This ensures tests can run in CI/CD environments and isolated development setups.
Test configuration is managed in pyproject.toml:
- pytest configuration with test discovery
- Development dependencies including pytest
- Proper Python path configuration for imports
This project is licensed under the MIT License.
Onehand Coding (onehand.coding433@gmail.com) GitHub Repository: https://github.com/Onehand-Coding/CLI-weather