How to Install and Use Python in Termux — Complete 2026 Guide
How to Install and Use Python in Termux — Complete 2026 Guide
- Introduction — Why Python in Termux?
- Setting Up Termux Before Installing Python
- How to Install Python in Termux
- Running Your First Python Script in Termux
- Installing Python Packages with pip in Termux
- Real-World Python Projects You Can Run in Termux
- Common Errors and Fixes
- Pro Tips for Python in Termux
- Python vs Other Languages in Termux
- Frequently Asked Questions
- Conclusion
// 01 — Introduction: Why Learn Python in Termux?
If you've ever wanted to run Python in Termux on your Android device, you're in the right place. Python is one of the most powerful, beginner-friendly, and widely used programming languages in the world — and the great news is that you can run it fully on your Android phone using Termux, with no root required. Whether you're a student learning to code, a cybersecurity enthusiast writing automation scripts, or a developer who wants a portable Linux environment in your pocket, Python in Termux opens up an entire universe of possibilities.
Termux is a free, open-source Android terminal emulator that gives you access to a real Linux environment without rooting your phone. It runs a package manager similar to Debian's apt system, and Python is one of the most well-supported packages available. Once installed, you get access to the full Python 3 interpreter, the pip package manager, and the ability to install hundreds of popular libraries like requests, numpy, flask, and more.
In this complete 2026 guide, we'll walk you through every step — from first installing Termux correctly, to writing your first Python script, to installing third-party packages, and even running real projects like web scrapers, API bots, and automation tools. This guide is written to be beginner-friendly, meaning every command is explained so you understand not just what to type, but why you're typing it.
By the end of this tutorial, you'll have a fully working Python environment on your Android device, and you'll know enough to start building real scripts and tools. Let's dive in.
// 02 — Setting Up Termux Before Installing Python
Before you can install and use Python in Termux, you need to make sure Termux itself is properly set up. Many users run into problems because they skip this step. A properly configured Termux environment will make everything else in this guide go smoothly.
Step 1 — Download Termux from F-Droid
The most important thing to know before anything else: do not use the Google Play Store version of Termux. That version has not been updated in years and is missing critical features. You need to download Termux from F-Droid, which is a free and open-source app store for Android.
Download F-Droid
Visit f-droid.org from your Android browser and download the F-Droid APK. Install it by enabling "Install from unknown sources" in your Android settings if prompted.
Install Termux from F-Droid
Open F-Droid, search for "Termux", and install it. Once installed, open the Termux app. You'll see a black terminal screen — this is your Linux environment.
Step 2 — Update and Upgrade Termux Packages
The very first command you should run every time you set up a fresh Termux install is the update and upgrade command. This refreshes the package list and upgrades any outdated packages to their latest versions. Think of it as syncing your Termux with the latest software catalog.
pkg update && pkg upgrade -y
This command does two things: pkg update downloads the latest package list from the Termux repository servers, and pkg upgrade -y upgrades all installed packages automatically (the -y flag means "yes to all prompts"). This may take a minute or two depending on your internet speed.
Step 3 — Give Termux Storage Permission
If you plan to work with files on your phone's internal storage (like saving Python scripts to your Downloads folder), you'll need to grant Termux access to your device storage. Run this command:
termux-setup-storage
A permission dialog will pop up on your screen. Tap "Allow". After this, you'll have a ~/storage folder in Termux that links to your Android storage directories, including Downloads, Pictures, Music, and more.
Step 4 — Install Essential Tools
Before installing Python, it's a good idea to install a few essential utilities that Python and its packages may depend on. These include git for cloning repositories, curl for downloading files, and wget for fetching web content.
pkg install git curl wget -y
// 03 — How to Install Python in Termux
Installing Python in Termux is surprisingly simple — it's just a single command. Termux's package manager handles everything for you, including downloading the correct version, installing dependencies, and setting up the Python interpreter. Here's how to do it.
The Main Installation Command
To install Python in Termux, run the following command:
pkg install python -y
This installs Python 3 (the current standard version) along with pip, the Python package manager. The installation typically takes between 30 seconds and 2 minutes depending on your internet connection. You'll see a progress bar as Termux downloads and installs the package.
Verifying the Installation
Once installation is complete, verify that Python was installed correctly by checking its version:
python --version
You should see output similar to this:
Python 3.12.3
The exact version number may differ, but as long as you see "Python 3.x.x", the installation was successful. Also verify that pip (the Python package installer) is working:
pip --version
Expected output:
pip 24.0 from /data/data/com.termux/files/usr/lib/python3.12/site-packages/pip (python 3.12)
python command always refers to Python 3. Unlike some desktop Linux systems where you might need to type python3, Termux maps python directly to the latest Python 3 version.Upgrading pip
It's good practice to immediately upgrade pip after installing Python. This ensures you have the latest version of the package manager, which fixes bugs and adds support for newer packages:
pip install --upgrade pip
What Gets Installed?
When you run pkg install python, Termux installs the following components:
- Python 3 interpreter — the core runtime that executes your Python code
- pip — the package installer for downloading Python libraries
- Standard library — Python's built-in modules like os, sys, json, http, and hundreds more
- Python headers — needed for compiling certain packages that have C extensions
This is a complete Python installation. You're not getting a limited or stripped-down version — you get the full Python 3 experience on your Android device.
// 04 — Running Your First Python Script in Termux
Now that Python is installed in Termux, it's time to actually use it. There are two main ways to run Python code in Termux: interactively (using the Python shell) or by writing and running script files. Both are useful and we'll cover both in this section.
Method 1 — The Interactive Python Shell
The interactive Python shell (also called the REPL — Read, Evaluate, Print, Loop) lets you type Python code one line at a time and see the result immediately. This is great for testing small snippets of code or learning how Python works.
To open the interactive shell, simply type:
python
You'll see something like this:
Python 3.12.3 (main, Jan 17 2026, 00:00:00)
[Clang 17.0.6] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>
The >>> prompt means Python is ready and waiting for your input. Try typing some basic commands:
>>> print("Hello from Termux!")
Hello from Termux!
>>> 2 + 2
4
>>> name = "Rixon"
>>> print(f"Welcome, {name}!")
Welcome, Rixon!
>>> import sys
>>> sys.version
'3.12.3 (main, Jan 17 2026, 00:00:00) [Clang 17.0.6]'
To exit the Python shell, type exit() or press Ctrl + D.
Method 2 — Writing and Running Python Script Files
For more serious work, you'll want to write Python code into files and run those files. This is how real Python development works. Let's create and run a simple Python script.
Create a directory for your scripts
Stay organized by creating a dedicated folder for your Python projects.
mkdir ~/python-projects
cd ~/python-projects
Create your first Python file
Use the nano text editor (comes with Termux) to write your script.
nano hello.py
In the nano editor, type the following Python code:
# My first Python script in Termux
print("Hello, World!")
print("Python is running on Android!")
# Basic variable usage
my_name = "Termux User"
my_year = 2026
print(f"Welcome, {my_name}! Year: {my_year}")
# Simple math
a = 15
b = 4
print(f"{a} + {b} = {a + b}")
print(f"{a} * {b} = {a * b}")
print(f"{a} / {b} = {a / b:.2f}")
# A simple loop
print("\nCounting to 5:")
for i in range(1, 6):
print(f" Count: {i}")
Save the file by pressing Ctrl + X, then Y, then Enter.
Run the script
Execute your Python script using the python command followed by the filename.
python hello.py
You should see this output:
Hello, World!
Python is running on Android!
Welcome, Termux User! Year: 2026
15 + 4 = 19
15 * 4 = 60
15 / 4 = 3.75
Counting to 5:
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
Using a Better Text Editor — Micro
While nano works fine, many users prefer a more feature-rich editor. Micro is an excellent terminal text editor that supports syntax highlighting, mouse support, and keyboard shortcuts similar to modern editors. Install it with:
pkg install micro -y
Then open files with micro filename.py instead of nano. It makes writing longer scripts much easier.
// 05 — Installing Python Packages with pip in Termux
One of Python's greatest strengths is its massive ecosystem of third-party libraries. Need to make HTTP requests? There's a library for that. Want to scrape websites? There's a library. Machine learning? Data analysis? Building a web server? Python has libraries for all of it. In Termux, you install these libraries using pip — Python's package installer.
Basic pip Usage
The basic syntax for installing a package is:
pip install package-name
Let's install some of the most popular and useful Python packages for Termux users:
Installing the requests Library
The requests library makes it easy to send HTTP requests — perfect for fetching web pages, calling APIs, or testing web applications.
pip install requests
Test it immediately:
import requests
response = requests.get("https://httpbin.org/get")
print(f"Status Code: {response.status_code}")
print(f"Response: {response.json()['headers']['Host']}")
Installing BeautifulSoup for Web Scraping
BeautifulSoup is the go-to library for parsing HTML and scraping information from websites. It works perfectly in Termux for learning web scraping concepts.
pip install beautifulsoup4 lxml
Installing Flask for Web Development
Flask is a lightweight web framework that lets you build web servers and APIs with Python. You can actually run a real web server from your Android phone using Termux and Flask!
pip install flask
Installing Colorama for Colorful Terminal Output
Colorama lets you add colors to your terminal output, which makes your scripts look much more professional and readable.
pip install colorama
Installing Scientific/Data Packages
For data science and scientific computing, you'll want numpy and other math libraries. These can sometimes require extra dependencies in Termux:
pkg install python-numpy -y
pkg install python-numpy rather than pip install numpy. The Termux package manager provides pre-compiled versions that work better on Android's ARM architecture.Managing pip Packages
Here are the most useful pip commands you'll need to know:
# List all installed packages
pip list
# Show info about a specific package
pip show requests
# Uninstall a package
pip uninstall package-name
# Upgrade a package
pip install --upgrade package-name
# Install multiple packages at once
pip install requests flask colorama
# Save your installed packages to a file
pip freeze > requirements.txt
# Install from a requirements file
pip install -r requirements.txt
Understanding requirements.txt
The requirements.txt file is a standard way to list your project's dependencies. If you're sharing a Python project with someone else (or saving it for later), you can save all your dependencies with pip freeze > requirements.txt, and then anyone can install all those same packages by running pip install -r requirements.txt. This is a professional practice used by developers worldwide.
// 06 — Real-World Python Projects You Can Run in Termux
Now comes the fun part. Let's look at some real, practical Python projects you can actually build and run in Termux right now. These examples range from beginner-level scripts to more advanced automation tools — all runnable on your Android device with no root required.
Project 1 — Simple IP Information Tool
This script fetches information about any IP address using a free public API. It's a great example of using the requests library for real-world data retrieval.
import requests
import json
def get_ip_info(ip_address):
"""Fetch information about an IP address."""
try:
url = f"https://ipapi.co/{ip_address}/json/"
response = requests.get(url, timeout=10)
if response.status_code == 200:
data = response.json()
print("\n===== IP Information =====")
print(f"IP Address : {data.get('ip', 'N/A')}")
print(f"City : {data.get('city', 'N/A')}")
print(f"Region : {data.get('region', 'N/A')}")
print(f"Country : {data.get('country_name', 'N/A')}")
print(f"ISP : {data.get('org', 'N/A')}")
print(f"Timezone : {data.get('timezone', 'N/A')}")
print(f"Latitude : {data.get('latitude', 'N/A')}")
print(f"Longitude : {data.get('longitude', 'N/A')}")
print("==========================\n")
else:
print(f"Error: Received status code {response.status_code}")
except requests.exceptions.RequestException as e:
print(f"Network error: {e}")
# Get your own IP info
print("Fetching your public IP information...")
get_ip_info("me")
# Or check a specific IP
# get_ip_info("8.8.8.8")
Save this as ip_info.py and run it with python ip_info.py. Make sure you have requests installed first.
Project 2 — Simple Port Scanner (Educational)
This is a basic educational port scanner. It demonstrates Python's socket library, which is used for network communication. This is how professional tools like Nmap work at their core — they probe ports to see which ones are open.
import socket
import sys
from datetime import datetime
def scan_ports(host, start_port, end_port):
"""Educational port scanner — only use on your own systems."""
print(f"\n{'='*40}")
print(f" Educational Port Scanner")
print(f" Target: {host}")
print(f" Ports: {start_port} - {end_port}")
print(f" Started: {datetime.now().strftime('%H:%M:%S')}")
print(f"{'='*40}\n")
open_ports = []
for port in range(start_port, end_port + 1):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(0.5)
result = sock.connect_ex((host, port))
if result == 0:
try:
service = socket.getservbyport(port)
except:
service = "unknown"
print(f" [OPEN] Port {port:5d} — {service}")
open_ports.append(port)
sock.close()
print(f"\nScan complete. {len(open_ports)} open port(s) found.")
return open_ports
# ONLY scan localhost (your own device) for learning
scan_ports("127.0.0.1", 1, 1000)
Project 3 — Simple Web Server with Flask
This project runs an actual web server on your Android device. You can access it from any browser on the same Wi-Fi network.
from flask import Flask, jsonify, request
from datetime import datetime
import socket
app = Flask(__name__)
@app.route('/')
def home():
return '''
<h1>Flask Running in Termux!</h1>
<p>Your Android phone is a web server.</p>
<p>Try visiting /api/info</p>
'''
@app.route('/api/info')
def api_info():
return jsonify({
"status": "running",
"server": "Termux Flask Server",
"time": datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
"message": "Hello from Android!"
})
@app.route('/api/echo', methods=['POST'])
def echo():
data = request.json
return jsonify({"you_sent": data, "received": True})
if __name__ == '__main__':
hostname = socket.gethostname()
local_ip = socket.gethostbyname(hostname)
print(f"\nFlask server running!")
print(f"Local URL: http://{local_ip}:5000")
print(f"Localhost: http://127.0.0.1:5000\n")
app.run(host='0.0.0.0', port=5000, debug=True)
Run it with python server.py and open your phone's browser to http://127.0.0.1:5000.
Project 4 — Password Generator
A practical utility script that generates secure random passwords. This is a great example of Python's built-in secrets module, which is specifically designed for generating cryptographically secure random values.
import secrets
import string
def generate_password(length=16, use_symbols=True, use_numbers=True, use_uppercase=True):
"""Generate a cryptographically secure random password."""
characters = string.ascii_lowercase
if use_uppercase:
characters += string.ascii_uppercase
if use_numbers:
characters += string.digits
if use_symbols:
characters += "!@#$%^&*()_+-=[]{}|;:,.<>?"
while True:
password = ''.join(secrets.choice(characters) for _ in range(length))
# Ensure the password meets all requirements
has_lower = any(c in string.ascii_lowercase for c in password)
has_upper = any(c in string.ascii_uppercase for c in password) if use_uppercase else True
has_digit = any(c in string.digits for c in password) if use_numbers else True
has_symbol = any(c in "!@#$%^&*()_+-=[]{}|;:,.<>?" for c in password) if use_symbols else True
if all([has_lower, has_upper, has_digit, has_symbol]):
return password
print("===== Secure Password Generator =====\n")
print("Short (8 chars) :", generate_password(8))
print("Medium (12 chars):", generate_password(12))
print("Strong (16 chars):", generate_password(16))
print("Ultra (24 chars):", generate_password(24))
print("\nNo symbols (12) :", generate_password(12, use_symbols=False))
print("No numbers (12) :", generate_password(12, use_numbers=False))
print("\n=====================================")
Project 5 — System Information Script
This script uses Python's built-in libraries to display information about your Termux/Android system. It's a great way to learn how Python interacts with the operating system.
import platform
import os
import sys
from datetime import datetime
def system_info():
print("\n===== System Information =====")
print(f"Python Version : {sys.version.split()[0]}")
print(f"Platform : {platform.system()}")
print(f"Machine : {platform.machine()}")
print(f"Processor : {platform.processor() or 'ARM (Android)'}")
print(f"OS : {platform.platform()}")
print(f"Current Dir : {os.getcwd()}")
print(f"Home Dir : {os.path.expanduser('~')}")
print(f"Timestamp : {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
# Environment info
print("\n===== Python Path =====")
for path in sys.path[:3]:
if path:
print(f" {path}")
# Disk usage of Termux home
statvfs = os.statvfs(os.path.expanduser('~'))
total = statvfs.f_frsize * statvfs.f_blocks
free = statvfs.f_frsize * statvfs.f_bfree
used = total - free
print(f"\n===== Storage (Termux) =====")
print(f"Total : {total / (1024**3):.2f} GB")
print(f"Used : {used / (1024**3):.2f} GB")
print(f"Free : {free / (1024**3):.2f} GB")
print("================================\n")
system_info()
// 07 — Common Errors and Fixes
Even with a clean installation, you'll sometimes run into errors when using Python in Termux. Here are the most common problems and exactly how to fix them.
Error 1 — "EXTERNALLY-MANAGED-ENVIRONMENT"
Error message: error: externally-managed-environment
Cause: Newer versions of pip show this error to protect system packages from being accidentally overwritten.
Fix: Add the --break-system-packages flag or use a virtual environment:
# Option 1: Use the flag
pip install package-name --break-system-packages
# Option 2: Use a virtual environment (recommended)
python -m venv myenv
source myenv/bin/activate
pip install package-name
Error 2 — pip: command not found
Cause: pip was not installed with Python, or the installation was incomplete.
Fix:
pkg install python -y
python -m ensurepip --upgrade
Error 3 — ModuleNotFoundError
Error message: ModuleNotFoundError: No module named 'requests'
Cause: The package is not installed in your current Python environment.
Fix: Install the missing package:
pip install requests
Error 4 — Package Installation Fails (Build Error)
Cause: Some Python packages require compiling C code, which needs build tools and header files.
Fix:
pkg install build-essential libffi-dev openssl-dev -y
pip install package-name
Error 5 — SSL Certificate Error
Error message: SSLError: [SSL: CERTIFICATE_VERIFY_FAILED]
Cause: SSL certificates issue in Termux.
Fix:
pkg install ca-certificates -y
pip install certifi
python -m certifi
Error 6 — SyntaxError (IndentationError)
Cause: Python is very strict about indentation. Mixing tabs and spaces, or having incorrect indentation levels, causes SyntaxErrors.
Fix: Always use spaces (not tabs) for indentation in Python. 4 spaces per indent level is the standard. If you're using nano, you can configure it to use spaces instead of tabs by adding this to your nano config.
echo "set tabsize 4
set tabstospaces" >> ~/.nanorc
// 08 — Pro Tips for Python in Termux
Here are some advanced tips and best practices that will make your Python in Termux experience much more productive and professional.
python -m venv env to create and source env/bin/activate to activate.pip install ipython for a much more powerful interactive shell with syntax highlighting, auto-completion, and command history.#!/data/data/com.termux/files/usr/bin/python as the first line of your scripts to make them directly executable without typing "python" every time.# Make a script executable
chmod +x myscript.py
./myscript.py # Now runs directly!
pkg install tmux to run multiple terminal sessions at once. This way you can run a Python server in one pane and write code in another.git clone https://github.com/user/repo.git then cd repo && pip install -r requirements.txt.cronie to schedule Python scripts to run automatically at set times — great for automation tasks like daily data fetching or backups.pkg install cronie -y
crond # Start the cron daemon
crontab -e # Edit scheduled tasks
// 09 — Python vs Other Languages in Termux
Termux supports many programming languages. Here's how Python compares to other popular options for various use cases:
| Feature | Python | Bash | Node.js | Ruby | PHP |
|---|---|---|---|---|---|
| Beginner Friendly | ⭐⭐⭐⭐⭐ | ⭐⭐⭐ | ⭐⭐⭐⭐ | ⭐⭐⭐⭐ | ⭐⭐⭐ |
| Package Ecosystem | ⭐⭐⭐⭐⭐ | ⭐⭐ | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐ | ⭐⭐⭐ |
| Scripting / Automation | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ | ⭐⭐⭐ | ⭐⭐⭐ | ⭐⭐ |
| Web Development | ⭐⭐⭐⭐ | ⭐ | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ |
| Cybersecurity Tools | ⭐⭐⭐⭐⭐ | ⭐⭐⭐ | ⭐⭐ | ⭐⭐ | ⭐⭐ |
| Data Science / ML | ⭐⭐⭐⭐⭐ | ⭐ | ⭐⭐ | ⭐ | ⭐ |
| Termux Install Size | Medium | Built-in | Large | Medium | Small |
| Performance | Medium | Fast | Fast | Medium | Medium |
| Install Command | pkg install python | Built-in | pkg install nodejs | pkg install ruby | pkg install php |
As the table shows, Python excels in nearly every category relevant to Termux users — especially cybersecurity education, scripting, and data science. It's the best first language to learn in Termux, and the most versatile one once you start building real projects. The blog hydratermux.blogspot.com consistently recommends Python as the primary language for Termux learners because of its enormous ecosystem and clear, readable syntax.
When to Choose Python Over Bash
Bash is great for simple one-liner automation and system administration. But as soon as your script gets longer than about 20 lines, or you need to do things like parse JSON, make HTTP requests, or work with data structures, Python becomes the better choice. Python's readability and error messages are also much more beginner-friendly than Bash's cryptic error outputs.
When to Choose Node.js Over Python
If you're building real-time applications, WebSocket servers, or anything that needs to handle many simultaneous connections efficiently, Node.js is the better choice due to its non-blocking I/O model. For everything else — especially learning, scripting, and security tools — Python wins.
// FAQ — Frequently Asked Questions
pkg install python -y. No subscriptions, no hidden costs, no root required.pkg update && pkg upgrade periodically will keep your Python version current. Python 2 is no longer available in Termux repositories as it has been end-of-life since 2020.pkg update && pkg upgrade -y. This will upgrade Python along with all other installed packages to their latest versions. You don't need to uninstall and reinstall Python manually.// 10 — Conclusion
Learning Python in Termux is one of the most rewarding things you can do as a mobile Linux user. In this guide, written by Rixon Xavier for the HYDRA TERMUX community, you've learned everything from properly setting up Termux for the first time, to installing Python with a single command, to writing and running real Python scripts, to installing packages with pip, and even building functional projects like IP info tools, a web server, a port scanner, and a password generator.
The key takeaways from this guide are: always use the F-Droid version of Termux, always run pkg update && pkg upgrade first, install Python with pkg install python -y, and use virtual environments for your projects. These habits will serve you well as you continue your Python journey.
Python's versatility means the skills you learn here apply everywhere — not just on your Android phone, but on any Linux server, Raspberry Pi, Mac, or Windows machine. The syntax is the same, the libraries are the same, and the logic is the same. By learning Python in Termux, you're gaining skills that are genuinely useful in the real world.
The next step is to keep building things. Pick a project idea that interests you — a web scraper, a Telegram bot, a network scanner, a data analyzer — and build it. The best way to learn Python is to write Python code every day, break things, fix them, and gradually take on more complex challenges.
