How to Build a Simple Weather App Using Termux and Python

How to Build a Simple Weather App Using Termux and Python

Do you want to check local forecasts right from your command line? Building a simple weather tool on your Android device is easier than you think. You do not need a desktop computer or complex software development environments to create something useful. By combining the power of an Android terminal emulator with a beginner-friendly programming language, you can build your own command-line forecasting utility in minutes.

In this comprehensive guide, we will walk through how to build a simple weather app using Termux and Python. We will cover environment setup, script writing, API integration, automation, and best practices. Whether you are a beginner learning to code or an advanced user looking to automate daily tasks, this project offers a practical way to interact with real-time web services from your mobile device.

What is Termux and Why Use Python for Weather Scripts?

Termux is an Android terminal emulator and Linux environment app that works directly with no rooting required. It provides a complete package management system, allowing you to install programming languages, text editors, and network utilities. It turns your smartphone or tablet into a portable Linux workstation.

Why choose Python for this project? Python features a clean, readable syntax that makes handling web requests straightforward. Unlike bash scripts that rely heavily on external parsing utilities like jq or complex string manipulation tools, Python includes robust built-in libraries and easy-to-use packages for fetching and parsing JSON data from web APIs.

Quick Summary: Termux Weather Tools at a Glance

Tool / Method Language Requirements Pros Cons
Bash Weather Script Bash termux-api, curl, jq Very lightweight Harder to debug and parse complex JSON
Wego Client Go termux-api, jq, wego binary Visual column/bar-graph layouts Requires external binary installation
Python Weather Script Python 3 requests library, API key Highly customizable, readable, easy parsing Requires writing custom script logic

Prerequisites and Environment Setup

Before we write our termux weather script, we need to prepare our mobile environment. Open your Termux app and update the default package repositories to ensure you have access to the latest stable software versions.

pkg update && pkg upgrade

Next, we need to install Python. Termux provides Python through its package manager. Run the following command to install Python 3:

pkg install python

Verify that Python installed correctly by checking its version:

python --version

We also need a library to handle HTTP requests. While Python has a built-in urllib module, using the requests library simplifies things significantly. Install it using Python's package installer, pip:

pip install requests

Getting Your Weather API Key

To display current weather conditions, our script needs to fetch data from a weather service provider. OpenWeatherMap is a popular choice because it offers a generous free tier for developers.

  1. Go to the official OpenWeatherMap website and create a free account.
  2. Navigate to your account settings and select "My API Keys".
  3. Generate a new key and copy it to your clipboard.

Keep your API key private. If you share your script publicly, make sure you do not hardcode your private key directly into repositories where others can see it.

The Full Working Script (Copy-Paste Ready)

Below is the complete, working Python script designed specifically for Termux. This code satisfies our primary termux python weather api script requirement. Create a new file named weather.py using your preferred text editor (like nano) and paste the code below.

import sys
import requests

def get_weather(city_name, api_key):
    base_url = "https://api.openweathermap.org/data/2.5/weather"
    params = {
        "q": city_name,
        "appid": api_key,
        "units": "metric"
    }
    
    try:
        response = requests.get(base_url, params=params)
        response.raise_for_status()
        data = response.json()
        
        city = data["name"]
        country = data["sys"]["country"]
        temp = data["main"]["temp"]
        feels_like = data["main"]["feels_like"]
        humidity = data["main"]["humidity"]
        description = data["weather"][0]["description"]
        
        print(f"\n--- Weather Report for {city}, {country} ---")
        print(f"Condition: {description.capitalize()}")
        print(f"Temperature: {temp}°C (Feels like: {feels_like}°C)")
        print(f"Humidity: {humidity}%")
        print("----------------------------------------\n")
        
    except requests.exceptions.HTTPError as http_err:
        print(f"HTTP error occurred: {http_err}")
    except Exception as err:
        print(f"An error occurred: {err}")

if __name__ == "__main__":
    # Replace with your actual OpenWeatherMap API key
    API_KEY = "YOUR_API_KEY_HERE"
    
    if len(sys.argv) > 1:
        city = " ".join(sys.argv[1:])
    else:
        city = input("Enter city name: ")
        
    get_weather(city, API_KEY)

Line-by-Line Explanation of the Code

Understanding how your code works ensures you can modify and troubleshoot it later. Let's break down the script line by line:

  • import sys and import requests: We import the sys module to handle command-line arguments (so you can pass a city name directly when running the script) and the requests module to make HTTP GET requests to the weather API.
  • def get_weather(city_name, api_key):: This defines a function that takes the target city and your API key as parameters.
  • base_url and params: We set the endpoint URL for the OpenWeatherMap API. The dictionary params holds our query parameters: q for the city name, appid for authorization, and units=metric to return temperatures in Celsius.
  • response = requests.get(...): This sends the HTTP request to the server with our parameters.
  • response.raise_for_status(): This built-in check catches bad HTTP responses (such as 404 Not Found if you misspell a city name) and triggers an exception.
  • data = response.json(): This parses the raw JSON response from the server into a native Python dictionary.
  • Data extraction variables: We extract specific values from the nested dictionary structure—such as city name, country code, temperature, feels-like temperature, humidity percentage, and weather description.
  • The print() statements: These format the extracted data neatly into a clean, readable terminal output.
  • Error handling blocks: The try...except structure prevents the program from crashing abruptly if there is a network outage or invalid input.
  • if __name__ == "__main__":: This standard Python construct checks whether the script is being run directly. It looks for command-line arguments or prompts the user to input a city name interactively if none were provided.

How to Run Your Weather Script

Before running the script, make sure you replace YOUR_API_KEY_HERE with the actual key you generated on OpenWeatherMap. Save your file in nano by pressing Ctrl + O, hitting Enter, and exiting with Ctrl + X.

You can run your script interactively by typing:

python weather.py

Alternatively, you can pass the city name directly as an argument from the command line:

python weather.py London

How to Auto-Run Your Script

Want your weather report to greet you every time you open a new Termux session? You can automate this process by adding your script to your shell startup configuration, similar to how users configure environment startup scripts for CLI tools like Wego.

  1. Open your shell configuration file (usually .bashrc) located in your home directory:
nano ~/.bashrc
  1. Scroll to the very bottom of the file and add a command to execute your Python script:
python ~/weather.py Tokyo
  1. Save and exit the file. Reload your bash configuration to apply changes immediately:
source ~/.bashrc

Now, every time you launch Termux, your script will fetch and display live weather updates automatically.

Safety and Legal Considerations

When writing scripts that interact with public APIs on mobile devices, keep a few safety and ethical practices in mind:

  • API Rate Limits: Free tiers on weather APIs usually limit the number of requests you can make per day or per minute. Avoid putting your script inside an infinite loop that queries the API every second, or your account may be temporarily blocked.
  • Credential Security: Never upload scripts containing hardcoded API keys to public code repositories like GitHub. Use environment variables or local configuration files to keep your credentials safe.
  • Storage and Permissions: Ensure your Termux app has proper storage permissions only if your script needs to read or write local cache files. For this basic weather app, elevated permissions are unnecessary.

Common Mistakes and Troubleshooting

Even experienced developers run into roadblocks. Here are some common issues you might encounter while building your Termux weather application:

  • ModuleNotFoundError: If Python throws an error stating that the requests module does not exist, it means you skipped the pip installation step. Run pip install requests to fix it.
  • HTTP 401 Unauthorized: This error means your API key is invalid or has not yet been activated by the provider. Double-check that you copied the entire key correctly.
  • HTTP 404 Not Found: This usually happens when you enter a city name that the API cannot recognize. Try adding the country code (e.g., Paris, FR) to make your search more specific.
  • Permission Denied when saving files: Make sure you are creating and editing scripts inside your home directory (~/) rather than restricted system paths.

Expert Tips for Extending Your App

Once you have the basic script running, you can expand its functionality to improve your programming skills:

  • Add Termux-API Integration: Use the termux-api package along with termux-location to automatically fetch your device's GPS coordinates and pass them into your Python script, eliminating the need to type a city name manually.
  • Caching Responses: Save the last fetched weather data into a local JSON file with a timestamp. This prevents your app from hitting the API every single time you open your terminal within a short window.
  • Colorize Output: Use ANSI escape codes or libraries like colorama to add vibrant colors to your terminal temperature displays.

Frequently Asked Questions

Can I run this script without an internet connection?

No. The script relies on making live HTTP requests to an external weather web service. An active Wi-Fi or mobile data connection is required to fetch forecast data.

Do I need to root my Android device to use Termux and Python?

No, root access is not required. Termux runs safely in a user-space environment on unrooted Android devices.

Why use Python instead of a bash script?

While bash scripts work well for very basic tasks, Python makes parsing complex JSON data structures much easier and provides cleaner error handling capabilities.

Conclusion

Building a weather utility in your mobile terminal is a fantastic way to practice programming fundamentals while creating a genuinely useful daily tool. You have successfully learned how to configure your Termux environment, install Python dependencies, interact with a real-world web API, write robust error handling, and even automate script execution upon startup.

Ready to take your command-line automation skills further? Explore our other Termux tutorials and start building your own custom mobile development workflow today.