iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
😎

Using Python on Termux

に公開

https://zenn.dev/dameyodamedame/articles/937421d81b5949

This is a detailed follow-up to the article mentioned above.

In Japan, Scratch is often the first programming language taught, but since the Termux environment is fundamentally CLI-based, it doesn't work. Therefore, we will choose Python here as the first step.

Installing Python

~ $ pkg install python

If you are asked anything during the installation, just press ⏎. The default options will be selected automatically as appropriate.

Writing a Python Program in an Editor

Use nano to create a file named loop.py with the following content (if you prefer vim, you can replace the nano command with the vim command).

~ $ nano loop.py
loop.py
for i in range(10):
    print(f'{i+1}回目')

Running the Python Program

~ $ python loo.py
1回目
2回目
3回目
4回目
5回目
6回目
7回目
8回目
9回目
10回目
~ $

It works without any trouble, doesn't it?

About Learning Python

I don't intend to introduce everything about Python here. For learning materials, let's rely on resources on the internet or AI. While a Google account is required, either of the following is recommended in terms of content:

https://www.python.jp/train/index.html
https://utokyo-ipp.github.io/

Both utilize Google Colab, so it feels more like using Python from a browser rather than using Termux. On Android, it's inconvenient since you can't press the TAB key, so it's a good idea to supplement it with something like CodeBoard Keyboard for Coding.

Jupyter Lab

Google Colab can only be used online (with internet access). Since not everyone has a constant online environment, I have prepared a way to achieve almost the same thing on Termux even offline. It's called Jupyter Lab. As shown in the previous explanation link, the substance of Google Colab is just a Jupyter Notebook execution environment, so it is possible to set it up yourself.

1. Installing and Starting Jupyter Lab

~ $ pkg install -y build-essential libzmq rust python
~ $ pkg install -y patchelf # for zmq
~ $ pkg install -y libjpeg-turbo # for Pillow
~ $ pkg install -y matplotlib git
~ $ mkdir jupyter
~ $ cd jupyter
~/jupyter $ python -m venv env
~/jupyter $ . env/bin/activate # required every time
((env) ) ~/jupyter $ python -m pip install -U pip
((env) ) ~/jupyter $ pip install jupyter jupyterlab-language-pack-ja-JP
((env) ) ~/jupyter $ pip install Pillow matplotlib
((env) ) ~/jupyter $ patchelf --add-needed libpython3.12.so ./env/lib/python3.12/site-packages/zmq/backend/cython/_zmq.cpython-312.so # required every time
((env) ) ~/jupyter $ PYTHONPATH=$(python -c "import sys;print(':'.join(sys.path))";echo -n ":/data/data/com.termux/files/usr/lib/python3.12/site-packages") jupyter-lab # required every time. Adding --ip='*' allows you to view it from a PC browser
...(Paste the URL output here into your browser)
((env) ) ~/jupyter $ patchelf --remove-needed libpython3.12.so ./env/lib/python3.12/site-packages/zmq/backend/cython/_zmq.cpython-312.so # required every time
((env) ) ~/jupyter $ deactivate # required every time
~/jupyter $ 

Note: Building might occur during pip install, which can take a very long time. Do not assume it has frozen just because it isn't moving; wait for as many minutes as needed.

By pasting the URL displayed when you run the jupyter-lab command into your browser, you can use features similar to Google Colab offline. It will likely be in English when first started, but you can change it to Japanese by selecting Settings > Language > Japanese (Japan) - 日本語 (日本) from the menu.

Browser screen

2. Stopping Jupyter Lab

You can stop it by selecting Shutdown from the menu on the browser screen, or by pressing Ctrl+C in Termux and answering Y to the question.

3. Subsequent Startups

Since it is tedious to type the commands marked as "required every time" in the comments every time, I have prepared the following script.

jupyter.sh
. env/bin/activate
patchelf --add-needed libpython3.12.so ./env/lib/python3.12/site-packages/zmq/backend/cython/_zmq.cpython-312.so
PYTHONPATH=$(python -c "import sys;print(':'.join(sys.path))";echo -n ":/data/data/com.termux/files/usr/lib/python3.12/site-packages") jupyter-lab # Adding --ip='*' allows you to view it from a PC browser
patchelf --remove-needed libpython3.12.so ./env/lib/python3.12/site-packages/zmq/backend/cython/_zmq.cpython-312.so
deactivate

Using this, you can start it as follows from the next time onwards:

~/jupyter $ sh jupyter.sh

Trying out llama-cpp-python

Once you have finished learning the basics of Python, let's try some computational processing, which is one of Python's specialties. This time, we will try running an LLM on a smartphone. We aren't using a very large model, but it is still about 1.9GB, so it's at a level where it barely runs on a smartphone with decent specs.

However, I have prepared this for you to check if it works.

https://github.com/abetlen/llama-cpp-python
https://huggingface.co/unsloth/Qwen3-4B-GGUF

1. Setting Up the Execution Environment

~ $ mkdir -p python/llama_example
~ $ cd python/llama_example
~/python/llama_example $ python -m venv env
~/python/llama_example $ . env/bin/activate
((env) ) ~/python/llama_example $ python -m pip install -U pip
((env) ) ~/python/llama_example $ pip install llama-cpp-python huggingface-hub

foo.py
from llama_cpp import Llama
import time

llm = Llama.from_pretrained(
    repo_id="unsloth/Qwen3-4B-GGUF",
    filename="Qwen3-4B-Q3_K_S.gguf",
    verbose=False
)

while True:
    q = input('質問: ')
    if q == '終了':
        break
    s = time.perf_counter()
    output = llm(
          f"質問: {q}\n",
          max_tokens=1024,
          stop=["質問:", "\n"],
          echo=False
    )
    e = time.perf_counter()
    print(f'({e-s:.2f}[秒])')
    print(output["choices"][0]["text"])

2. Execution

((env) ) ~/python/llama_example $ python foo.py
llama_context: n_ctx_per_seq (512) < n_ctx_train (40960) -- the full capacity of the model will not be utilized
質問: LLMを上手に使うコツを教えてください。
(65.86[秒])
回答: 1. 極力自然な日本語で話して、LLMが理解しやすいように、文の構造をシンプルにしてください。2. その場その場の状況を具体的に説明してください。3. 重要な情報を先に伝えてから、背景や詳細を追加してください。4. 過去の会話や上下文を活用してください。5. あなたの意図を明確にし、LLMがその意図を正確に理解できるよう、指示を明確にしてください。6. 長文は避け、段階的に話してください。7. 使 いたい言葉がなければ、新しい単語や専門用語は使わず、毎回同じ卂数語で説明してください。
質問: 終了
((env) ) ~/python/llama_example $

Note: The first run involves downloading approximately 1.9GB for the model, so please perform this in a Wi-Fi environment.

As you can see, local LLMs can run even on a smartphone. Since the model being used is Chinese-made, please excuse the occasional strange characters.

You can finish by typing "終了" when prompted for a question (it can also be stopped normally with Ctrl+C).

3. Cleanup

((env) ) ~/python/llama_example $ deactivate
~/python/llama_example $ 

4. Finally

For practical purposes, as of May 2025, Gemini 2.0 is available for free and without authentication, so you should generally use that if there is something you want to know. This might be useful, at most, for something like a makeshift translation in an environment without internet access (while foo.py has a download function and will try to connect to the network, it won't if you use Llama() to directly read the model file in the local cache). Still, the experience of running it yourself before understanding the mechanism might be important. If you just want to learn how to use LLMs, you might not need to go through this effort (since it's quite simple).

GitHubで編集を提案

Discussion