How to Get Battery Status Using Termux:API Script

How to Get Battery Status Using Termux:API Script

Have you ever wanted to check your Android device's power levels straight from the command line? If you love working in a terminal environment, keeping an eye on your hardware stats is a huge part of the daily workflow. Whether you are running a lightweight server on an old phone or just automating tasks, knowing how to track your power source matters. That is where a good termux battery script comes into play.

Monitoring your hardware from a shell environment sounds complicated. But with the right tools, it is actually quite simple. In this comprehensive guide, we are going to look closely at how you can fetch, parse, and utilize your device's power data. We will also dive deep into the specific termux-battery-status python script approach, giving you a fully working, copy-paste ready utility that goes far beyond basic bash commands.

What is Termux:API and Why Do You Need It?

Termux is an incredible Android terminal emulator and Linux environment. Out of the box, it gives you a robust shell with access to package management, Python, Node.js, and plenty of other utilities. However, standard Linux commands do not know anything about Android-specific hardware like cameras, GPS sensors, or power management systems.

That is where the Termux:API add-on package comes in. It serves as a bridge between the Linux terminal environment and the underlying Android operating system. By installing the companion app from an app store (like F-Droid or Google Play) and installing the corresponding package inside Termux, you unlock a suite of command-line tools that can query your phone's native sensors.

When it comes to power tracking, the core command you will rely on is termux-battery-status. When executed, this command queries the Android system power manager and spits out a JSON-formatted string containing vital metrics. Understanding how to parse this data is the key to building robust automation scripts.

Quick Answer: Getting Battery Status in Termux

If you just want a quick, one-line solution to see your current power levels without writing a full program, you can run this quick command right inside your terminal:

termux-battery-status

If you have installed Termux:API correctly, your terminal will instantly output a block of JSON data that looks something like this:

{
  "percentage": 85,
  "plugged": "UNPLUGGED",
  "status": "DISCHARGING",
  "health": "GOOD",
  "temperature": 28.5,
  "current": -450
}

This quick snapshot gives you everything you need to know: how much juice is left, whether it is plugged into a charger, the physical health of the battery, its current temperature in Celsius, and the electrical current flow.

Prerequisites: Setting Up Your Environment

Before we can run our advanced Python script, we need to make sure all dependencies are properly installed on your Android device. If you skip any of these steps, the script will throw errors or fail to fetch data.

  1. Install Termux:API App: Download and install the Termux:API application on your Android device from F-Droid or an authorized source. Ensure it has the necessary permissions to read device status if prompted.
  2. Update Packages: Open your Termux app and run the standard update command to ensure your repositories are fresh:
    pkg update && pkg upgrade -y
  3. Install the Termux API Package: Run the package manager command to install the command-line bridge:
    pkg install termux-api python -y
  4. Verify Installation: Test the setup by running:
    termux-battery-status

Full Working Python Script (Copy-Paste Ready)

Many basic tutorials only show simple Bash one-liners or rely heavily on external utilities like jq. While those work fine, writing a native termux-battery-status python script gives you much more control over error handling, logging, and conditional automation.

Below is a clean, robust, full working script. You can copy this code directly into your Termux environment.

#!/usr/bin/env python3
import subprocess
import json
import sys
import time

def get_battery_data():
    """Executes the termux-battery-status command and returns parsed JSON data."""
    try:
        # Run the termux-api command via subprocess
        result = subprocess.run(
            ['termux-battery-status'],
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            text=True,
            check=True
        )
        # Parse the JSON output from the command
        battery_info = json.loads(result.stdout)
        return battery_info
    except FileNotFoundError:
        print("Error: 'termux-battery-status' command not found.", file=sys.stderr)
        print("Please ensure you have installed the 'termux-api' package and app.", file=sys.stderr)
        sys.exit(1)
    except subprocess.CalledProcessError as e:
        print(f"Error executing command: {e.stderr}", file=sys.stderr)
        sys.exit(1)
    except json.JSONDecodeError:
        print("Error: Failed to parse JSON response from Termux API.", file=sys.stderr)
        sys.exit(1)

def display_battery_report(data):
    """Displays a clean, formatted report of the device power status."""
    print("========================================")
    print("         TERMUX BATTERY REPORT          ")
    print("========================================")
    print(f"  Percentage  : {data.get('percentage', 'N/A')}%")
    print(f"  Status      : {data.get('status', 'N/A')}")
    print(f"  Power Source: {data.get('plugged', 'N/A')}")
    print(f"  Health      : {data.get('health', 'N/A')}")
    print(f"  Temperature : {data.get('temperature', 'N/A')}°C")
    
    current = data.get('current')
    if current is not None:
        print(f"  Current Flow: {current} mA")
    else:
        print("  Current Flow: Not reported by device")
        
    print("========================================")

if __name__ == "__main__":
    # Fetch and display the data once when run directly
    battery_data = get_battery_data()
    display_battery_report(battery_data)

Line-by-Line Code Explanation

Let's break down how this script works so you can customize it to fit your exact needs. Understanding every single line ensures you can troubleshoot any issues that might pop up.

  • #!/usr/bin/env python3: This is the shebang line. It tells the Unix shell which interpreter to use when executing the file directly as an executable script.
  • import subprocess, json, sys, time: We import standard Python libraries. subprocess lets us run terminal commands from inside Python, json handles data parsing, sys handles system exits, and time is useful if you expand the script into a continuous monitoring loop.
  • def get_battery_data():: Defines our core function responsible for talking to the operating system.
  • subprocess.run(...): This safely executes the termux-battery-status command. We capture standard output and standard error so we can catch any failures gracefully.
  • json.loads(result.stdout): Converts the raw JSON text string returned by the API into a native Python dictionary, making it easy to extract values using keys.
  • except FileNotFoundError:: Catches errors if the user forgot to install the Termux:API package, preventing the script from crashing with an ugly stack trace.
  • display_battery_report(data):: A formatting function that extracts specific dictionary keys using the safe .get() method, printing out a neat text interface.

How to Save, Make Executable, and Run the Script

Writing the code is only half the battle. You need to save it inside your Termux storage and give it execution permissions so you can run it easily.

  1. Open your Termux terminal.
  2. Create a new file using your preferred text editor (like nano):
    nano battery_check.py
  3. Paste the Python code provided above into the editor.
  4. Save and exit (if using nano, press Ctrl + O, then Enter to save, and Ctrl + X to exit).
  5. Make the script executable by running the chmod command:
    chmod +x battery_check.py
  6. Run your new script anytime by typing:
    ./battery_check.py

How to Auto-Run Your Script (Automation & Monitoring)

Checking your power levels manually is fun, but the real power of Termux comes from automation. What if you want to log your device health over time, or trigger an alert when your power drops below 20%?

You can automate your script using a few different approaches depending on what you want to achieve:

1. Using Cron Jobs in Termux

Termux supports cron jobs via the termux-services package or standard crontab configurations. To run your script automatically at regular intervals:

  • Install the cron utilities: pkg install cronie -y
  • Start the cron daemon: crond
  • Edit your cron table: crontab -e
  • Add a rule to run your script every hour, for instance:
    0 * * * * /usr/bin/python3 /data/data/com.termux/files/home/battery_check.py >> /data/data/com.termux/files/home/battery_log.txt

2. Continuous Loop Scripting

If you are running an active monitoring session while keeping your device plugged in, you can modify the bottom of your Python script to run in a continuous loop with a sleep timer:

if __name__ == "__main__":
    import time
    while True:
        data = get_battery_data()
        display_battery_report(data)
        # Sleep for 300 seconds (5 minutes) before checking again
        time.sleep(300)

Comparison: Bash Scripts vs. Python Scripts for Termux API

When searching for solutions online, you will often find both Bash and Python approaches. Here is a quick comparison table to help you understand which method suits your technical needs best.

Feature Bash Script (+ jq) Python Script
Ease of Writing Very fast for simple one-liners Requires basic programming knowledge
Dependency Requirements Needs jq package installed Requires Python 3 interpreter
Error Handling Difficult and prone to silent failures Robust via try/except blocks
Data Manipulation Limited to text filtering utilities Extensive libraries for logging, math, and alerts

Safety, Legal, and Hardware Considerations

Whenever you write automation scripts that query hardware parameters continuously, you need to keep safety in mind. Running heavy polling routines or waking up the CPU constantly can generate unnecessary heat and drain your power source faster than normal.

  • Thermal Management: Avoid setting polling intervals lower than a few seconds. Excessive hardware querying can keep the device awake, driving up temperatures.
  • Background Restrictions: Modern Android versions aggressively kill background processes to save resources. If your script stops running automatically, look into disabling battery optimization for the Termux app in your Android system settings.
  • Permissions & Privacy: The Termux:API package only accesses data locally on your device. It does not transmit your hardware status anywhere unless you explicitly write code to send network requests. Always review scripts from untrusted sources to ensure they do not include malicious data-exfiltration logic.

Common Mistakes and Troubleshooting Tips

Even experienced developers run into snags when working with Termux integrations. Here are some common hurdles and how to fix them:

  • "Command not found" Error: This happens when the Termux:API app is missing or the CLI package hasn't been installed. Run pkg install termux-api and make sure the companion app is installed on your device.
  • Empty or Null JSON Output: If the command returns empty brackets or errors out, your Android power manager might be temporarily blocking the request. Restarting your Termux session usually clears this up.
  • Permission Denied on Execute: If you cannot run ./battery_check.py, you forgot to give the file execution rights. Run chmod +x battery_check.py to fix it.

Expert Tips for Advanced Users

Ready to take your power management setup to the next level? Consider these professional integration ideas:

  • Webhook Alerts: Combine your Python script with the requests library to send a Discord or Telegram notification when your battery drops below 15%.
  • CSV Logging: Append timestamps and percentage values to a CSV file every time the script runs, then plot your device's power degradation over months of usage.
  • Dynamic Theming: Use the output percentage to dynamically change your terminal color schemes or prompt indicators based on how much energy your node has left.

Frequently Asked Questions (FAQ)

Can I run termux-battery-status without installing the Android app?

No. The command-line utility inside Termux relies on an intents bridge provided by the standalone Termux:API app to communicate with the Android operating system.

Does this script work on non-rooted Android devices?

Yes! One of the best things about Termux and Termux:API is that they work entirely within user-space permissions. You do not need to root your phone to read hardware stats.

Why does the current flow show up as None or missing?

Some Android device kernels and hardware manufacturers do not expose real-time electrical current (mA) metrics through standard Android power APIs. If your device returns null for current, your hardware simply does not support reporting that specific metric.

Conclusion

Monitoring your Android hardware from the command line opens up endless possibilities for automation, lightweight server management, and custom scripting. With the fully working termux-battery-status python script provided in this guide, you now have a reliable, robust tool to track your device's power health.

Take what you've learned here, adjust the polling intervals to suit your project, and start building smarter terminal workflows today. If you want to explore more automation guides, check out our other tutorials on Termux sensor scripts and remote monitoring setups!