How to Learn Python Scripting in Termux — Beginner Projects Guide (2026)
- Introduction — Why Learn Python Scripting in Termux?
- Installing Python in Termux — Complete Setup Guide
- Python Basics You Must Know Before Scripting
- Beginner Python Projects You Can Build in Termux
- Using pip — Installing Python Libraries in Termux
- Intermediate Python Scripting Projects for Termux
- Common Errors and Fixes
- Pro Tips for Python Scripting in Termux
- Python Script Types — Comparison Table
- Frequently Asked Questions
- Conclusion
// 01 — Introduction: Why Learn Python Scripting in Termux?
If you want to learn Python scripting in Termux on your Android device, you're making one of the smartest decisions a beginner programmer can make in 2026. Python is consistently ranked as the number one programming language in the world for beginners — and for good reason. Its syntax reads almost like plain English, its community is massive, and its use cases stretch from simple automation scripts all the way to artificial intelligence, cybersecurity tools, data science, and web development. The remarkable thing is that all of this is completely accessible from your Android phone using Termux — no root, no laptop, no expensive hardware required.
Termux provides a genuine Linux terminal environment on Android, and Python runs inside it exactly as it would on any Linux server or desktop machine. This means the Python scripting skills you build in Termux are real, transferable, professional-grade skills — not simplified educational versions. When you write a Python script in Termux that reads files, makes API calls, or automates system tasks, you're doing exactly what developers and security professionals do in production environments around the world.
In this guide, we're going to take you from zero to writing real Python scripts step by step. We'll cover installing Python and pip, the fundamentals you need to know before you start scripting, five hands-on beginner projects, five intermediate projects that use real Python libraries, and everything in between. By the time you finish reading — and more importantly, by the time you finish typing these commands — you'll have a fully functioning Python development environment on your phone and several working scripts you built yourself.
At HYDRA TERMUX, the mission has always been simple: give Android users access to real coding and cybersecurity education without barriers. Rixon Xavier created this resource so that whether you're a student, a curious tinkerer, or an aspiring developer, you can start building real skills today with whatever device you already own. Python scripting is the perfect starting point — and Termux is the perfect environment. Let's get to work.
// 02 — Installing Python in Termux — Complete Setup Guide
Before you can write a single line of Python, you need to set up your environment correctly. A lot of beginners run into problems because they skip the setup steps or use an outdated version of Termux. This section walks you through the entire process from the very beginning — from where to get Termux, to verifying that Python is installed and ready to use.
Step 1 — Get the Right Version of Termux
This is the most common mistake beginners make. The Google Play Store version of Termux is outdated and abandoned. Using it will cause broken package installations and strange errors. You must download Termux from one of these two trusted sources:
Step 2 — Update Termux Packages
Once Termux is open, always run an update before installing anything new. This ensures your package lists are current and your existing tools are up to date.
pkg update && pkg upgrade -y
This command refreshes your repository index (pkg update) and upgrades all installed packages to their latest versions (pkg upgrade -y). The -y flag skips manual confirmation prompts. The process may take a few minutes — let it finish completely before proceeding.
Step 3 — Install Python
Now install Python with a single command. Termux's package manager handles everything automatically — downloading Python, its dependencies, and configuring it in your environment.
pkg install python -y
This installs Python 3 (the current standard) along with pip, Python's package manager. In Termux, python always refers to Python 3 — there's no Python 2 confusion to worry about here.
Step 4 — Verify the Installation
After installation completes, confirm that both Python and pip are working correctly:
python --version
pip --version
Expected output:
Python 3.12.x
pip 24.x.x from /data/data/com.termux/files/usr/lib/python3.12/site-packages/pip (python 3.12)
If you see version numbers — you're good. If you see "command not found", close and reopen Termux, then try again.
Step 5 — Install a Text Editor and Set Up Your Workspace
You'll need a terminal text editor to write Python scripts. Install nano — it's the most beginner-friendly option:
pkg install nano -y
Now create a dedicated folder for all your Python projects:
mkdir ~/python-scripts
cd ~/python-scripts
The mkdir command creates a new directory called python-scripts inside your home folder. The cd command navigates into it. This will be your workspace for everything in this guide. Keeping projects organized from the start is a professional habit worth building early.
Step 6 — Launch the Python Interactive Shell
Python includes an interactive shell (called the REPL — Read, Eval, Print, Loop) that lets you type Python code and see the result instantly. It's excellent for testing ideas quickly. Launch it by typing:
python
>>> print("Python is running in Termux!")
Python is running in Termux!
>>> 10 + 25
35
>>> exit()
Type exit() or press Ctrl+D to leave the REPL and return to your Termux prompt.
// 03 — Python Basics Every Termux Scripter Must Know
Before jumping into full projects, you need a solid understanding of Python's core building blocks. This section covers the essential concepts you'll use in every script you write. Don't skip this — even five minutes spent understanding these fundamentals will save you hours of confusion later. We'll learn by doing, writing small examples you can test directly in Termux.
Variables and Data Types
A variable is a named container that holds a value. Python is dynamically typed — you don't need to declare a variable's type in advance.
# Variables and types
name = "Termux User" # String (text)
age = 21 # Integer (whole number)
version = 3.12 # Float (decimal)
is_rooted = False # Boolean (True/False)
print(f"Hello, {name}!")
print(f"Python version: {version}")
print(f"Root required: {is_rooted}")
The f"..." syntax is called an f-string — it lets you embed variables directly inside strings. It's the modern, preferred way to format text in Python 3.
Lists, Dictionaries, and Loops
Lists and dictionaries are Python's most important data structures. A list holds an ordered sequence of items. A dictionary holds key-value pairs — like a mini-database.
# List example
tools = ["nmap", "hydra", "metasploit", "sqlmap", "aircrack"]
print("Security tools:")
for tool in tools:
print(f" - {tool}")
# Dictionary example
tool_info = {
"name": "nmap",
"purpose": "network scanning",
"installed": True
}
print(f"\n{tool_info['name']} is used for {tool_info['purpose']}")
Functions — Reusable Blocks of Code
A function is a named block of code you can call multiple times. Functions keep your scripts organized and avoid repeating the same code.
def greet(username):
"""Function to greet a user."""
return f"Welcome to Termux, {username}! Let's script."
def add_numbers(a, b):
return a + b
print(greet("HydraUser"))
print(f"5 + 7 = {add_numbers(5, 7)}")
File Handling — Reading and Writing Files
File handling is one of the most important Python scripting skills. Almost every real-world script needs to read input from files or write results to files.
# Writing to a file
with open("output.txt", "w") as f:
f.write("Line 1: Python scripting in Termux\n")
f.write("Line 2: No root required\n")
f.write("Line 3: Learning is free\n")
print("File written.")
# Reading from a file
with open("output.txt", "r") as f:
content = f.read()
print("\nFile contents:")
print(content)
The with open() pattern is the correct, safe way to handle files in Python. It automatically closes the file when the block ends, even if an error occurs. The "w" mode writes (creates or overwrites), and "r" mode reads.
Error Handling with try/except
Real scripts encounter unexpected situations — files that don't exist, network timeouts, invalid user input. The try/except block lets your script handle errors gracefully instead of crashing.
try:
number = int(input("Enter a number: "))
result = 100 / number
print(f"100 divided by {number} = {result}")
except ValueError:
print("Error: That wasn't a valid number.")
except ZeroDivisionError:
print("Error: You can't divide by zero!")
except Exception as e:
print(f"Something went wrong: {e}")
This is the foundation of robust Python scripting. Every script you write that takes user input or interacts with external resources should use error handling.
// 04 — Beginner Python Scripting Projects You Can Build in Termux
Knowing syntax is one thing — building actual projects is where real learning happens. Here are three complete beginner Python scripting projects you can build right now in Termux. Each one teaches different core concepts, and each produces a genuinely useful tool.
Project 1 — Password Generator Script
A password generator is a classic beginner project that teaches randomness, string manipulation, and command-line arguments. Create the file:
nano ~/python-scripts/passgen.py
# passgen.py — Random Password Generator
import random
import string
import sys
def generate_password(length=16, use_symbols=True):
characters = string.ascii_letters + string.digits
if use_symbols:
characters += string.punctuation
password = ''.join(random.choices(characters, k=length))
return password
# Get length from command line argument if provided
length = int(sys.argv[1]) if len(sys.argv) > 1 else 16
print("\n🔐 Generated Passwords:")
print("-" * 40)
for i in range(5):
print(f" {i+1}. {generate_password(length)}")
print("-" * 40)
print(f"Length: {length} characters | With symbols: Yes\n")
python passgen.py # Default 16-char passwords
python passgen.py 24 # Custom 24-char passwords
This script uses Python's built-in random, string, and sys modules — no pip installs needed. string.ascii_letters gives you all uppercase and lowercase letters, string.digits gives 0-9, and string.punctuation adds symbols. random.choices() picks random characters from the combined pool.
Project 2 — System Information Script
This script collects and displays information about your Termux environment — a practical tool and a great introduction to Python's os and platform modules.
# sysinfo.py — System Information Tool
import os
import platform
from datetime import datetime
print("\n" + "="*45)
print(" SYSTEM INFO — TERMUX PYTHON SCRIPT")
print("="*45)
print(f" Date/Time : {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
print(f" OS : {platform.system()} {platform.release()}")
print(f" Machine : {platform.machine()}")
print(f" Python : {platform.python_version()}")
print(f" Home Dir : {os.path.expanduser('~')}")
print(f" Current Dir: {os.getcwd()}")
print(f" CPU Count : {os.cpu_count()}")
# List files in current directory
files = os.listdir('.')
print(f"\n Files in current dir ({len(files)} total):")
for f in sorted(files)[:10]:
print(f" 📄 {f}")
print("="*45 + "\n")
python sysinfo.py
Project 3 — Text File Word Counter
This project teaches file reading, string processing, and dictionary usage — three skills central to Python scripting for data analysis and text processing.
# wordcount.py — Text File Analyzer
import sys
from collections import Counter
def analyze_file(filename):
try:
with open(filename, 'r') as f:
text = f.read()
except FileNotFoundError:
print(f"Error: '{filename}' not found.")
return
words = text.lower().split()
word_count = len(words)
char_count = len(text)
line_count = text.count('\n') + 1
# Top 10 most common words
word_freq = Counter(words)
top_words = word_freq.most_common(10)
print(f"\n📊 Analysis of: {filename}")
print(f" Lines : {line_count}")
print(f" Words : {word_count}")
print(f" Characters : {char_count}")
print(f"\n Top 10 words:")
for word, count in top_words:
bar = '█' * count
print(f" {word:<15 count:="">3} {bar}")
filename = sys.argv[1] if len(sys.argv) > 1 else "output.txt"
analyze_file(filename)15>
python wordcount.py output.txt
// 05 — Using pip — Installing Python Libraries in Termux
Python's true power lies in its ecosystem of third-party libraries. pip is the tool that gives you access to over 400,000 packages on PyPI (the Python Package Index). Understanding how to install and use pip packages in Termux is a critical skill that unlocks an enormous range of capabilities — from web scraping to sending emails to building APIs.
How pip Works in Termux
In Termux, pip is installed alongside Python automatically. You can use it to install any package from PyPI. The key thing to understand is that Termux's filesystem is isolated from Android's — packages install into Termux's own directory structure, so nothing you install interferes with your Android system.
# Install a package
pip install package-name
# Install a specific version
pip install package-name==2.28.0
# Upgrade an installed package
pip install --upgrade package-name
# Uninstall a package
pip uninstall package-name
# List all installed packages
pip list
# Show info about a specific package
pip show requests
# Save your project's dependencies
pip freeze > requirements.txt
# Install all dependencies from a file
pip install -r requirements.txt
Essential Python Libraries for Termux Scripting
Here are the most useful pip packages for Python scripting in Termux, organized by use case. Install them as you need them:
requests — HTTP Requests Made Simple
The most popular Python library of all time. Makes sending HTTP requests (GET, POST, etc.) incredibly simple. Essential for any script that interacts with the web or APIs.
pip install requests
colorama — Colored Terminal Output
Adds color to your terminal output. Makes scripts look professional and output easy to read. Works perfectly in Termux.
pip install colorama
rich — Beautiful Terminal Output
A powerful library for rich text, tables, progress bars, syntax highlighting, and beautiful terminal formatting. One of the best modern Python libraries for CLI tools.
pip install rich
beautifulsoup4 — Web Scraping
Parses HTML and XML. Essential for web scraping projects where you want to extract data from websites.
pip install requests beautifulsoup4
pkg install python-numpy or pkg install python-pandas instead of pip — Termux maintains pre-compiled versions of these heavy packages.Virtual Environments in Termux
For larger projects, it's best practice to use a virtual environment — an isolated Python environment that keeps one project's dependencies separate from another's. This prevents package version conflicts.
# Create a virtual environment
python -m venv myproject-env
# Activate it
source myproject-env/bin/activate
# Your prompt will change to show (myproject-env)
# Now pip installs only affect this environment
# Deactivate when done
deactivate
// 06 — Intermediate Python Scripting Projects for Termux
Now that you know the basics and understand pip, let's build two more substantial Python scripting projects that use real third-party libraries. These are the kinds of scripts that actually impress people — and more importantly, solve real problems.
Project 4 — Weather Checker Script (Using an API)
This project teaches you how to work with public APIs — one of the most valuable real-world Python scripting skills. We'll use the wttr.in API, which requires no API key, making it perfect for beginners.
pip install requests
nano ~/python-scripts/weather.py
# weather.py — Terminal Weather Checker
import requests
import sys
def get_weather(city):
url = f"https://wttr.in/{city}?format=j1"
try:
response = requests.get(url, timeout=10)
response.raise_for_status()
data = response.json()
current = data['current_condition'][0]
area = data['nearest_area'][0]
city_name = area['areaName'][0]['value']
country = area['country'][0]['value']
temp_c = current['temp_C']
feels_like = current['FeelsLikeC']
humidity = current['humidity']
description = current['weatherDesc'][0]['value']
wind_speed = current['windspeedKmph']
visibility = current['visibility']
print("\n" + "="*42)
print(f" 🌍 Weather: {city_name}, {country}")
print("="*42)
print(f" 🌡️ Temperature : {temp_c}°C")
print(f" 🤔 Feels Like : {feels_like}°C")
print(f" 💧 Humidity : {humidity}%")
print(f" 💨 Wind Speed : {wind_speed} km/h")
print(f" 👁️ Visibility : {visibility} km")
print(f" ☁️ Condition : {description}")
print("="*42 + "\n")
except requests.exceptions.ConnectionError:
print("Error: No internet connection.")
except requests.exceptions.Timeout:
print("Error: Request timed out.")
except Exception as e:
print(f"Error: {e}")
city = " ".join(sys.argv[1:]) if len(sys.argv) > 1 else "London"
get_weather(city)
python weather.py London
python weather.py "New York"
python weather.py Tokyo
This script sends a GET request to the wttr.in JSON API, parses the response, and displays formatted weather information. It demonstrates JSON parsing, error handling, command-line arguments, and string formatting — all in one clean script.
Project 5 — Subdomain Finder Script (Ethical Use Only)
This project is a classic cybersecurity learning exercise — a subdomain enumeration script that checks which common subdomains exist for a domain by making HTTP requests. This is used in legitimate penetration testing to map an attack surface. Only use this on domains you own or have explicit written permission to test.
# subdomain_check.py — Educational Subdomain Scanner
import requests
import sys
# Common subdomains to check
SUBDOMAINS = [
"www", "mail", "ftp", "blog", "shop", "api",
"dev", "staging", "admin", "portal", "app",
"cdn", "static", "media", "forum", "support",
"docs", "help", "m", "mobile", "test"
]
def scan_subdomains(domain):
print(f"\n🔍 Scanning subdomains for: {domain}")
print("-" * 45)
found = []
for sub in SUBDOMAINS:
url = f"http://{sub}.{domain}"
try:
response = requests.get(url, timeout=3)
status = response.status_code
print(f" ✅ FOUND [{status}] {url}")
found.append(url)
except requests.exceptions.ConnectionError:
print(f" ❌ NOT FOUND: {sub}.{domain}")
except requests.exceptions.Timeout:
print(f" ⏱️ TIMEOUT: {sub}.{domain}")
except Exception as e:
pass
print("-" * 45)
print(f"\n Total found: {len(found)} / {len(SUBDOMAINS)}\n")
if len(sys.argv) < 2:
print("Usage: python subdomain_check.py example.com")
sys.exit(1)
domain = sys.argv[1]
scan_subdomains(domain)
python subdomain_check.py yourowndomain.com
This script demonstrates loops, HTTP requests with error handling, list iteration, and formatted output — all core Python scripting skills applied in a real cybersecurity context.
// 07 — Common Python Scripting Errors in Termux and How to Fix Them
Error: "ModuleNotFoundError: No module named 'xyz'"
The library isn't installed. Run pip install xyz. If it's a heavy package like numpy, try pkg install python-numpy instead — Termux has pre-built versions of common scientific packages.
Error: "IndentationError: unexpected indent"
Python uses indentation to define code blocks — mixing tabs and spaces causes this error. In nano, always use the spacebar (4 spaces per indent level). Never mix tabs with spaces in the same file.
Error: "pip: command not found"
pip didn't install with Python or isn't in your PATH. Try python -m pip install package-name as an alternative. Or reinstall Python: pkg reinstall python -y.
Error: "ConnectionError" when using requests
Your device has no internet connection, or the target server is down. Check your Wi-Fi or mobile data. Also verify the URL is correct. Use curl https://example.com in Termux to test basic connectivity.
Error: "SyntaxError: EOL while scanning string literal"
You have an unclosed string — a quote was opened but never closed. Check the line number in the error message and make sure every opening " or ' has a matching closing quote.
pip install fails with "error: externally-managed-environment"
On newer Python versions, use: pip install package --break-system-packages. Or better yet, create and use a virtual environment: python -m venv env && source env/bin/activate.
// 08 — Pro Tips for Python Scripting in Termux
sys.argv directly, use Python's built-in argparse module to build command-line interfaces with proper help messages, flags, and argument validation. It makes your scripts look and feel professional.#!/data/data/com.termux/files/usr/bin/python as the very first line of your script, then run chmod +x script.py. After that, you can run it as ./script.py instead of typing python script.py every time.rich library transforms ordinary print() statements into beautiful formatted output with color, tables, progress bars, and syntax highlighting. It requires zero extra complexity and makes your tools look outstanding.crond service to run Python scripts on a schedule. Install it with pkg install cronie, start it with crond, then add jobs with crontab -e. Great for automation scripts that need to run daily or hourly.logging module is far more powerful than print() for scripts that run unattended. It lets you set severity levels (DEBUG, INFO, WARNING, ERROR), write logs to files, and filter output — all essential for production-quality scripts.pkg install git), create a free GitHub account, and push your scripts there regularly. This gives you a backup, version history, and a portfolio to show potential employers. It's also the professional way to manage code.// 09 — Python Script Types — What to Learn and When
As you grow as a Python scripter in Termux, you'll encounter different types of scripts used for different purposes. Here's a guide to the main categories, their use cases, and which Python tools are best for each.
| Script Type | Use Case | Key Libraries | Difficulty |
|---|---|---|---|
| Automation Scripts | Rename files, organize folders, batch processing | os, shutil, pathlib | ⭐ Beginner |
| API Interaction | Fetch data, post data, web integrations | requests, httpx | ⭐⭐ Beginner+ |
| Web Scraping | Extract data from websites | requests, BeautifulSoup, lxml | ⭐⭐ Intermediate |
| Network Scripts | Port scanning, ping tools, socket tools | socket, scapy, nmap | ⭐⭐⭐ Intermediate |
| Data Processing | Analyze CSV/JSON, statistics | csv, json, pandas | ⭐⭐ Intermediate |
| CLI Tools | Command-line utilities with flags/args | argparse, click, rich | ⭐⭐ Intermediate |
| Security Scripts | Hash cracking, recon, CTF tools | hashlib, requests, socket | ⭐⭐⭐ Advanced |
| Bot Scripts | Telegram bots, Discord bots | python-telegram-bot, discord.py | ⭐⭐⭐ Intermediate+ |
// 10 — Frequently Asked Questions
~/.termux/boot/. You can also use cronie for scheduled execution of scripts at specific times or intervals — great for automation tasks.python --version. Termux updates Python regularly, so running pkg upgrade -y periodically keeps it current.pkg install rather than pip install. Termux maintains pre-compiled versions optimized for Android: pkg install python-numpy, pkg install python-pandas. Installing these via pip may fail due to missing C compilers or architecture issues.#!/data/data/com.termux/files/usr/bin/python. Then make it executable: chmod +x script.py. Finally, move or symlink it to your PATH: cp script.py ~/bin/mycommand (after creating ~/bin with mkdir ~/bin and adding it to PATH in ~/.bashrc). Now you can run it from anywhere by typing mycommand.pip install python-telegram-bot for Telegram or pip install discord.py for Discord), write your bot script, and run it from Termux. Your bot will stay active as long as Termux is running. For persistent bots, look into running them in a Termux session kept alive with tmux (pkg install tmux).// 11 — Conclusion: Start Your Python Scripting Journey Today
Learning Python scripting in Termux is one of the most rewarding things you can do with your Android phone. We've covered an enormous amount of ground in this guide: installing Python and pip correctly, understanding the core building blocks of the language, building five real projects from a password generator to a weather checker to a cybersecurity learning script, understanding pip and Python libraries, troubleshooting common errors, and picking up professional development habits.
The most important thing to understand is that none of this is simulated or watered down. The Python you're running in Termux is the real Python runtime on a real Linux system. The scripts you write here work exactly the same on a remote server, a cloud VM, or a developer's MacBook. The skills you build now are directly applicable to real jobs in software development, data science, DevOps, and cybersecurity.
Python's philosophy is that code should be readable and clear — and that makes it the perfect language to learn by reading other people's scripts, modifying them, and gradually understanding how they work. Every script in this guide was written to be readable and well-commented. Go back, read them again, and try modifying them. Change the password length. Add more subdomains to scan. Output the weather for three cities at once. Experimentation is how you move from beginner to intermediate.
The hydratermux.blogspot.com community grows every week with new tutorials covering everything from Python automation to ethical hacking tools to Linux fundamentals — all designed for Android users who want to learn real skills. Bookmark it, share it, and come back for the next post in this series.
Ready to go further with Python scripting in Termux? Check out our upcoming guides on building a full Telegram bot in Python, web scraping with BeautifulSoup, and Python socket programming for network tools. The path from beginner scripter to confident Python developer is shorter than you think — and it starts with the commands you just ran.

Comments
Post a Comment